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

212
LINES

< > BotCompany Repo | #1000693 // Resolve includes

JavaX translator [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (212L/2K/7K).

1  
import javax.imageio.*;
2  
import java.awt.image.*;
3  
import java.awt.*;
4  
import java.security.NoSuchAlgorithmException;
5  
import java.security.MessageDigest;
6  
import java.lang.reflect.*;
7  
import java.net.*;
8  
import java.io.*;
9  
import javax.swing.*;
10  
import java.util.regex.*;
11  
import java.util.List;
12  
import java.util.zip.*;
13  
import java.util.*;
14  
15  
public class main {
16  
  public static void main(String[] args) throws Exception {
17  
    String s = loadMainJava();
18  
    
19  
    // process include statements
20  
    
21  
    Matcher m = Pattern.compile("\n\\s*!include (#\\d+)").matcher(s);
22  
    StringBuffer buf = new StringBuffer();
23  
    while (m.find()) {
24  
      String includedSrc = loadSnippet(m.group(1));
25  
      m.appendReplacement(buf, m.quoteReplacement("\n" + includedSrc));
26  
    }
27  
    m.appendTail(buf);
28  
    s = buf.toString();
29  
    
30  
    saveMainJava(s);
31  
  }
32  
33  
 static String mainJava;
34  
  
35  
  static String loadMainJava() throws IOException {
36  
    if (mainJava != null) return mainJava;
37  
    return loadTextFile("input/main.java", "");
38  
  }
39  
40  
  static void saveMainJava(String s) throws IOException {
41  
    if (mainJava != null)
42  
      mainJava = s;
43  
    else
44  
      saveTextFile("output/main.java", s);
45  
  }
46  
  
47  
  static boolean preferCached = false;
48  
49  
  public static String loadSnippet(String snippetID) throws IOException {
50  
    return loadSnippet(parseSnippetID(snippetID), preferCached);
51  
  }
52  
53  
  public static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
54  
    return loadSnippet(parseSnippetID(snippetID), preferCached);
55  
  }
56  
57  
  public static long parseSnippetID(String snippetID) {
58  
    return Long.parseLong(shortenSnippetID(snippetID));
59  
  }
60  
61  
  private static String shortenSnippetID(String snippetID) {
62  
    if (snippetID.startsWith("#"))
63  
      snippetID = snippetID.substring(1);
64  
    String httpBlaBla = "http://tinybrain.de/";
65  
    if (snippetID.startsWith(httpBlaBla))
66  
      snippetID = snippetID.substring(httpBlaBla.length());
67  
    return snippetID;
68  
  }
69  
70  
  public static boolean isSnippetID(String snippetID) {
71  
    snippetID = shortenSnippetID(snippetID);
72  
    return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
73  
  }
74  
75  
  public static boolean isInteger(String s) {
76  
    return Pattern.matches("\\-?\\d+", s);
77  
  }
78  
79  
  public static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
80  
    if (preferCached) {
81  
      initSnippetCache();
82  
      String text = DiskSnippetCache_get(snippetID);
83  
      if (text != null)
84  
        return text;
85  
    }
86  
87  
    String text;
88  
    try {
89  
      URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
90  
      text = loadPage(url);
91  
    } catch (FileNotFoundException e) {
92  
      throw new IOException("Snippet #" + snippetID + " not found or not public");
93  
    }
94  
95  
    try {
96  
      initSnippetCache();
97  
      DiskSnippetCache_put(snippetID, text);
98  
    } catch (IOException e) {
99  
      System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
100  
    }
101  
102  
    return text;
103  
  }
104  
105  
  static File DiskSnippetCache_dir;
106  
107  
  public static void initDiskSnippetCache(File dir) {
108  
    DiskSnippetCache_dir = dir;
109  
    dir.mkdirs();
110  
  }
111  
112  
  public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
113  
    return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
114  
  }
115  
116  
  private static File DiskSnippetCache_getFile(long snippetID) {
117  
    return new File(DiskSnippetCache_dir, "" + snippetID);
118  
  }
119  
120  
  public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
121  
    saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
122  
  }
123  
124  
  public static File DiskSnippetCache_getDir() {
125  
    return DiskSnippetCache_dir;
126  
  }
127  
128  
  public static void initSnippetCache() {
129  
    if (DiskSnippetCache_dir == null)
130  
      initDiskSnippetCache(new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"));
131  
  }
132  
  
133  
134  
  /** writes safely (to temp file, then rename) */
135  
  public static void saveTextFile(String fileName, String contents) throws IOException {
136  
    File file = new File(fileName);
137  
    File parentFile = file.getParentFile();
138  
    if (parentFile != null)
139  
      parentFile.mkdirs();
140  
    String tempFileName = fileName + "_temp";
141  
    FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
142  
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
143  
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
144  
    printWriter.print(contents);
145  
    printWriter.close();
146  
    if (file.exists() && !file.delete())
147  
      throw new IOException("Can't delete " + fileName);
148  
149  
    if (!new File(tempFileName).renameTo(file))
150  
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
151  
  }
152  
153  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
154  
    if (!new File(fileName).exists())
155  
      return defaultContents;
156  
157  
    FileInputStream fileInputStream = new FileInputStream(fileName);
158  
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
159  
    return loadTextFile(inputStreamReader);
160  
  }
161  
162  
  public static String loadTextFile(Reader reader) throws IOException {
163  
    StringBuilder builder = new StringBuilder();
164  
    try {
165  
      BufferedReader bufferedReader = new BufferedReader(reader);
166  
      String line;
167  
      while ((line = bufferedReader.readLine()) != null)
168  
        builder.append(line).append('\n');
169  
    } finally {
170  
      reader.close();
171  
    }
172  
    return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1);
173  
  }
174  
175  
  public static String loadPage(String url) throws IOException {
176  
    if (url.indexOf("://") < 0)
177  
      url = "http://" + url;
178  
    return loadPage(new URL(url));
179  
  }
180  
  
181  
  public static String loadPage(URL url) throws IOException {
182  
    System.out.println("Loading: " + url.toExternalForm());
183  
    URLConnection con = url.openConnection();
184  
    return loadPage(con, url);
185  
  }
186  
187  
  public static String loadPage(URLConnection con, URL url) throws IOException {
188  
    String contentType = con.getContentType();
189  
    if (contentType == null)
190  
      throw new IOException("Page could not be read: " + url);
191  
    //Log.info("Content-Type: " + contentType);
192  
    String charset = loadPage_guessCharset(contentType);
193  
    Reader r = new InputStreamReader(con.getInputStream(), charset);
194  
    StringBuilder buf = new StringBuilder();
195  
    while (true) {
196  
      int ch = r.read();
197  
      if (ch < 0)
198  
        break;
199  
      //Log.info("Chars read: " + buf.length());
200  
      buf.append((char) ch);
201  
    }
202  
    return buf.toString();
203  
  }
204  
  
205  
  static String loadPage_guessCharset(String contentType) {
206  
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
207  
    Matcher m = p.matcher(contentType);
208  
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
209  
    return m.matches() ? m.group(1) : "ISO-8859-1";
210  
  }
211  
212  
}

Author comment

Began life as a copy of #636

download  show line numbers  debug dex  old transpilations   

Travelled to 18 computer(s): aoiabmzegqzx, bhatertpkbcr, cahelewubzku, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, jlatgrcjtklg, jtubtzbbkimh, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, teubizvjbppd, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1000693
Snippet name: Resolve includes
Eternal ID of this version: #1000693/1
Text MD5: 61d7e3b032bbd86dab622235c1b8dd4e
Transpilation MD5: 61d7e3b032bbd86dab622235c1b8dd4e
Author: stefan
Category:
Type: JavaX translator
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-01-21 03:00:55
Source code size: 7117 bytes / 212 lines
Pitched / IR pitched: No / No
Views / Downloads: 689 / 5209
Referenced in: [show references]