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

256
LINES

< > BotCompany Repo | #595 // Standard Function Adder (outdated)

JavaX translator [tags: use-pretranspiled]

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

Author comment

Began life as a copy of #592

download  show line numbers  debug dex  old transpilations   

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

Comments [hide]

ID Author/Program Comment Date
404 #1000610 (pitcher) 2015-08-18 00:07:07
403 #1000604 (pitcher) 2015-08-20 15:28:24

add comment

Snippet ID: #595
Snippet name: Standard Function Adder (outdated)
Eternal ID of this version: #595/1
Text MD5: d16d06a6746fa5ddbd7787c0e2ef4f4c
Transpilation MD5: d16d06a6746fa5ddbd7787c0e2ef4f4c
Author: stefan
Category: javax
Type: JavaX translator
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-07-26 19:29:07
Source code size: 8548 bytes / 256 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 1103 / 3014
Referenced in: [show references]