Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

258
LINES

< > BotCompany Repo | #1000265 // Standard Function Adder

JavaX translator [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (258L/3K/9K).

1  
import java.util.*;
2  
import java.io.*;
3  
import java.util.regex.*;
4  
import java.net.*;
5  
6  
public class main {
7  
  static String[] standardFunctions = {
8  
    "#1000810/join",
9  
    "#2000323/saveTextFile",
10  
    "#2000322/loadTextFile",
11  
    "#1002380/loadMainJava",
12  
    "#1001807/saveMainJava",
13  
    "#2000326/toLines",
14  
    "#2000330/loadSnippet",
15  
    "#2000331/makeJavaStringLiteral"
16  
  };
17  
  
18  
  public static void main(String[] args) throws IOException {
19  
    String s = loadMainJava();
20  
    List<String> defd = findFunctions(s);
21  
    for (int i = 0; i < 2; i++)
22  
      for (String x : standardFunctions) {
23  
        String[] f = x.split("/");
24  
        if (hasInvocation(s, f[1]) && !defd.contains(f[1])) {
25  
          System.out.println("Adding function: " + f[1] + " (" + f[0] + ")");
26  
          s = addFunction(s, f[0]);
27  
          defd.add(f[1]);
28  
        }
29  
      }
30  
    saveMainJava(s);
31  
  }
32  
  
33  
  static boolean hasInvocation(String src, String f) {
34  
    return src.indexOf(f) >= 0; // generous matching :)
35  
  }
36  
  
37  
  static List<String> findFunctions(String src) {
38  
    System.out.println("Scanning for functions");
39  
    List<String> functions = new ArrayList<String>();
40  
    for (String line : toLines(src)) {
41  
      Matcher matcher = Pattern.compile("static.*\\s+(\\w+)\\(").matcher(line);
42  
      if (matcher.find()) {
43  
        String f = matcher.group(1);
44  
        functions.add(f);
45  
        System.out.println("Function found: " + f);
46  
      }
47  
    }
48  
    return functions;
49  
  }
50  
  
51  
  public static String addFunction(String s, String fID) throws IOException {
52  
    int i = s.lastIndexOf('}');
53  
    String function = loadSnippet(fID);
54  
    return s.substring(0, i) + "\n" + function +"\n" + s.substring(i);
55  
  }
56  
  
57  
  public static List<String> toLines(String s) {
58  
    List<String> lines = new ArrayList<String>();
59  
    int start = 0;
60  
    while (true) {
61  
      int i = toLines_nextLineBreak(s, start);
62  
      if (i < 0) {
63  
        if (s.length() > start) lines.add(s.substring(start));
64  
        break;
65  
      }
66  
67  
      lines.add(s.substring(start, i));
68  
      if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
69  
        i += 2;
70  
      else
71  
        ++i;
72  
73  
      start = i;
74  
    }
75  
    return lines;
76  
  }
77  
78  
  private static int toLines_nextLineBreak(String s, int start) {
79  
    for (int i = start; i < s.length(); i++) {
80  
      char c = s.charAt(i);
81  
      if (c == '\r' || c == '\n')
82  
        return i;
83  
    }
84  
    return -1;
85  
  }
86  
  
87  
  static String loadMainJava() throws IOException {
88  
    return loadTextFile("input/main.java", "");
89  
  }
90  
  
91  
  static void saveMainJava(String s) throws IOException {
92  
    saveTextFile("output/main.java", s);
93  
  }
94  
  
95  
  static String charsetForTextFiles = "UTF-8";
96  
  
97  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
98  
    if (!new File(fileName).exists())
99  
      return defaultContents;
100  
101  
    FileInputStream fileInputStream = new FileInputStream(fileName);
102  
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles);
103  
    return loadTextFile(inputStreamReader);
104  
  }
105  
106  
  public static String loadTextFile(Reader reader) throws IOException {
107  
    StringBuilder builder = new StringBuilder();
108  
    try {
109  
      BufferedReader bufferedReader = new BufferedReader(reader);
110  
      String line;
111  
      while ((line = bufferedReader.readLine()) != null)
112  
        builder.append(line).append('\n');
113  
    } finally {
114  
      reader.close();
115  
    }
116  
    return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1);
117  
  }
118  
  
119  
  /** writes safely (to temp file, then rename) */
120  
  public static void saveTextFile(String fileName, String contents) throws IOException {
121  
    File file = new File(fileName);
122  
    File parentFile = file.getParentFile();
123  
    if (parentFile != null)
124  
      parentFile.mkdirs();
125  
    String tempFileName = fileName + "_temp";
126  
    FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
127  
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles);
128  
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
129  
    printWriter.print(contents);
130  
    printWriter.close();
131  
    if (file.exists() && !file.delete())
132  
      throw new IOException("Can't delete " + fileName);
133  
134  
    if (!new File(tempFileName).renameTo(file))
135  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
136  
  }  
137  
  
138  
  public static String loadSnippet(String snippetID) throws IOException {
139  
    return loadSnippet(snippetID, preferCached);
140  
  }
141  
  
142  
 public static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
143  
    return loadSnippet(parseSnippetID(snippetID), preferCached);
144  
  }
145  
146  
  public static long parseSnippetID(String snippetID) {
147  
    return Long.parseLong(shortenSnippetID(snippetID));
148  
  }
149  
150  
  private static String shortenSnippetID(String snippetID) {
151  
    if (snippetID.startsWith("#"))
152  
      snippetID = snippetID.substring(1);
153  
    String httpBlaBla = "http://tinybrain.de/";
154  
    if (snippetID.startsWith(httpBlaBla))
155  
      snippetID = snippetID.substring(httpBlaBla.length());
156  
    return snippetID;
157  
  }
158  
159  
  public static boolean isSnippetID(String snippetID) {
160  
    snippetID = shortenSnippetID(snippetID);
161  
    return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
162  
  }
163  
164  
  public static boolean isInteger(String s) {
165  
    return Pattern.matches("\\-?\\d+", s);
166  
  }
167  
  
168  
  static boolean preferCached = false;
169  
  
170  
  public static String loadSnippet(long snippetID) throws IOException {
171  
    return loadSnippet(snippetID, preferCached);
172  
  }
173  
174  
  public static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
175  
    if (preferCached) {
176  
      initSnippetCache();
177  
      String text = DiskSnippetCache_get(snippetID);
178  
      if (text != null)
179  
        return text;
180  
    }
181  
182  
    String text;
183  
    try {
184  
      URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
185  
      text = loadPage(url);
186  
    } catch (FileNotFoundException e) {
187  
      throw new IOException("Snippet #" + snippetID + " not found or not public");
188  
    }
189  
190  
    try {
191  
      initSnippetCache();
192  
      DiskSnippetCache_put(snippetID, text);
193  
    } catch (IOException e) {
194  
      System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
195  
    }
196  
197  
    return text;
198  
  }
199  
200  
  private static String loadPage(URL url) throws IOException {
201  
    System.out.println("Loading: " + url.toExternalForm());
202  
    URLConnection con = url.openConnection();
203  
    return loadPage(con, url);
204  
  }
205  
206  
  public static String loadPage(URLConnection con, URL url) throws IOException {
207  
    String contentType = con.getContentType();
208  
    if (contentType == null)
209  
      throw new IOException("Page could not be read: " + url);
210  
    //Log.info("Content-Type: " + contentType);
211  
    String charset = guessCharset(contentType);
212  
    Reader r = new InputStreamReader(con.getInputStream(), charset);
213  
    StringBuilder buf = new StringBuilder();
214  
    while (true) {
215  
      int ch = r.read();
216  
      if (ch < 0)
217  
        break;
218  
      //Log.info("Chars read: " + buf.length());
219  
      buf.append((char) ch);
220  
    }
221  
    return buf.toString();
222  
  }
223  
224  
  public static String guessCharset(String contentType) {
225  
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
226  
    Matcher m = p.matcher(contentType);
227  
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
228  
    return m.matches() ? m.group(1) : "ISO-8859-1";
229  
  }
230  
  
231  
  static File DiskSnippetCache_dir;
232  
233  
  public static void initDiskSnippetCache(File dir) {
234  
    DiskSnippetCache_dir = dir;
235  
    dir.mkdirs();
236  
  }
237  
238  
  public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
239  
    return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
240  
  }
241  
242  
  private static File DiskSnippetCache_getFile(long snippetID) {
243  
    return new File(DiskSnippetCache_dir, "" + snippetID);
244  
  }
245  
246  
  public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
247  
    saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
248  
  }
249  
250  
  public static File DiskSnippetCache_getDir() {
251  
    return DiskSnippetCache_dir;
252  
  }
253  
254  
  public static void initSnippetCache() {
255  
    if (DiskSnippetCache_dir == null)
256  
      initDiskSnippetCache(new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"));
257  
  }
258  
}

Author comment

Supersedes #595

download  show line numbers  debug dex  old transpilations   

Travelled to 21 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gkwdfizivqfm, gwrvuhgaqvyk, hxnwyiuffukg, ishqpsrjomds, jtubtzbbkimh, lpdgvwnxivlt, mqqgnosmbjvj, nrtiiiyxqhmw, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, qbtsjoyahagl, teubizvjbppd, tslmcundralx, tvejysmllsmz, ugbnzuvxksoj, vouqrxazstgt

No comments. add comment

Snippet ID: #1000265
Snippet name: Standard Function Adder
Eternal ID of this version: #1000265/1
Text MD5: 2e0cc257ee57a3d838dbecfa91382ab1
Transpilation MD5: 2e0cc257ee57a3d838dbecfa91382ab1
Author: stefan
Category: javax
Type: JavaX translator
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-01-22 00:00:35
Source code size: 8609 bytes / 258 lines
Pitched / IR pitched: No / No
Views / Downloads: 1012 / 3610
Referenced in: [show references]