1 | static boolean preferCached = false;
|
2 |
|
3 | public static String loadSnippet(String snippetID) throws IOException {
|
4 | return loadSnippet(parseSnippetID(snippetID), preferCached);
|
5 | }
|
6 |
|
7 | public static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
|
8 | return loadSnippet(parseSnippetID(snippetID), preferCached);
|
9 | }
|
10 |
|
11 | public static long parseSnippetID(String snippetID) {
|
12 | return Long.parseLong(shortenSnippetID(snippetID));
|
13 | }
|
14 |
|
15 | private static String shortenSnippetID(String snippetID) {
|
16 | if (snippetID.startsWith("#"))
|
17 | snippetID = snippetID.substring(1);
|
18 | String httpBlaBla = "http://tinybrain.de/";
|
19 | if (snippetID.startsWith(httpBlaBla))
|
20 | snippetID = snippetID.substring(httpBlaBla.length());
|
21 | return snippetID;
|
22 | }
|
23 |
|
24 | public static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
|
25 | if (preferCached) {
|
26 | initSnippetCache();
|
27 | String text = DiskSnippetCache_get(snippetID);
|
28 | if (text != null)
|
29 | return text;
|
30 | }
|
31 |
|
32 | String text;
|
33 | try {
|
34 | URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
|
35 | text = loadPage(url);
|
36 | } catch (FileNotFoundException e) {
|
37 | throw new IOException("Snippet #" + snippetID + " not found or not public");
|
38 | }
|
39 |
|
40 | try {
|
41 | initSnippetCache();
|
42 | DiskSnippetCache_put(snippetID, text);
|
43 | } catch (IOException e) {
|
44 | System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")");
|
45 | }
|
46 |
|
47 | return text;
|
48 | }
|
49 |
|
50 | static File DiskSnippetCache_dir;
|
51 |
|
52 | public static void initDiskSnippetCache(File dir) {
|
53 | DiskSnippetCache_dir = dir;
|
54 | dir.mkdirs();
|
55 | }
|
56 |
|
57 | public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
|
58 | return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
|
59 | }
|
60 |
|
61 | private static File DiskSnippetCache_getFile(long snippetID) {
|
62 | return new File(DiskSnippetCache_dir, "" + snippetID);
|
63 | }
|
64 |
|
65 | public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
|
66 | saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
|
67 | }
|
68 |
|
69 | public static File DiskSnippetCache_getDir() {
|
70 | return DiskSnippetCache_dir;
|
71 | }
|
72 |
|
73 | public static void initSnippetCache() {
|
74 | if (DiskSnippetCache_dir == null)
|
75 | initDiskSnippetCache(new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"));
|
76 | }
|