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).

import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.net.*;

public class main {
  static String[] standardFunctions = {
    "#2000323/saveTextFile",
    "#2000322/loadTextFile",
    "#2000324/loadMainJava",
    "#2000325/saveMainJava",
    "#2000326/toLines",
    "#2000330/loadSnippet"
  };
  
  public static void main(String[] args) throws IOException {
    String s = loadMainJava();
    List<String> defd = findFunctions(s);
    for (int i = 0; i < 2; i++)
      for (String x : standardFunctions) {
        String[] f = x.split("/");
        if (hasInvocation(s, f[1]) && !defd.contains(f[1])) {
          System.out.println("Adding function: " + f[1] + " (" + f[0] + ")");
          s = addFunction(s, f[0]);
          defd.add(f[1]);
        }
      }
    saveMainJava(s);
  }
  
  static boolean hasInvocation(String src, String f) {
    return src.indexOf(f) >= 0; // generous matching :)
  }
  
  static List<String> findFunctions(String src) {
    System.out.println("Scanning for functions");
    List<String> functions = new ArrayList<String>();
    for (String line : toLines(src)) {
      Matcher matcher = Pattern.compile("static.*\\s+(\\w+)\\(").matcher(line);
      if (matcher.find()) {
        String f = matcher.group(1);
        functions.add(f);
        System.out.println("Function found: " + f);
      }
    }
    return functions;
  }
  
  public static String addFunction(String s, String fID) throws IOException {
    int i = s.lastIndexOf('}');
    String function = loadSnippet(fID);
    return s.substring(0, i) + "\n" + function +"\n" + s.substring(i);
  }
  
  public static List<String> toLines(String s) {
    List<String> lines = new ArrayList<String>();
    int start = 0;
    while (true) {
      int i = toLines_nextLineBreak(s, start);
      if (i < 0) {
        if (s.length() > start) lines.add(s.substring(start));
        break;
      }

      lines.add(s.substring(start, i));
      if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n')
        i += 2;
      else
        ++i;

      start = i;
    }
    return lines;
  }

  private static int toLines_nextLineBreak(String s, int start) {
    for (int i = start; i < s.length(); i++) {
      char c = s.charAt(i);
      if (c == '\r' || c == '\n')
        return i;
    }
    return -1;
  }
  
  static String loadMainJava() throws IOException {
    return loadTextFile("input/main.java", "");
  }
  
  static void saveMainJava(String s) throws IOException {
    saveTextFile("output/main.java", s);
  }
  
  static String charsetForTextFiles = "UTF-8";
  
  public static String loadTextFile(String fileName, String defaultContents) throws IOException {
    if (!new File(fileName).exists())
      return defaultContents;

    FileInputStream fileInputStream = new FileInputStream(fileName);
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, charsetForTextFiles);
    return loadTextFile(inputStreamReader);
  }

  public static String loadTextFile(Reader reader) throws IOException {
    StringBuilder builder = new StringBuilder();
    try {
      BufferedReader bufferedReader = new BufferedReader(reader);
      String line;
      while ((line = bufferedReader.readLine()) != null)
        builder.append(line).append('\n');
    } finally {
      reader.close();
    }
    return builder.length() == 0 ? "" : builder.substring(0, builder.length()-1);
  }
  
  /** writes safely (to temp file, then rename) */
  public static void saveTextFile(String fileName, String contents) throws IOException {
    File file = new File(fileName);
    File parentFile = file.getParentFile();
    if (parentFile != null)
      parentFile.mkdirs();
    String tempFileName = fileName + "_temp";
    FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles);
    PrintWriter printWriter = new PrintWriter(outputStreamWriter);
    printWriter.print(contents);
    printWriter.close();
    if (file.exists() && !file.delete())
      throw new IOException("Can't delete " + fileName);

    if (!new File(tempFileName).renameTo(file))
      throw new IOException("Can't rename " + tempFileName + " to " + fileName);
  }  
  
  public static String loadSnippet(String snippetID) throws IOException {
    return loadSnippet(snippetID, preferCached);
  }
  
 public static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
    return loadSnippet(parseSnippetID(snippetID), preferCached);
  }

  public static long parseSnippetID(String snippetID) {
    return Long.parseLong(shortenSnippetID(snippetID));
  }

  private static String shortenSnippetID(String snippetID) {
    if (snippetID.startsWith("#"))
      snippetID = snippetID.substring(1);
    String httpBlaBla = "http://tinybrain.de/";
    if (snippetID.startsWith(httpBlaBla))
      snippetID = snippetID.substring(httpBlaBla.length());
    return snippetID;
  }

  public static boolean isSnippetID(String snippetID) {
    snippetID = shortenSnippetID(snippetID);
    return isInteger(snippetID) && Long.parseLong(snippetID) != 0;
  }

  public static boolean isInteger(String s) {
    return Pattern.matches("\\-?\\d+", s);
  }
  
  static boolean preferCached = false;
  
  public static String loadSnippet(long snippetID) throws IOException {
    return loadSnippet(snippetID, preferCached);
  }

  public static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
    if (preferCached) {
      initSnippetCache();
      String text = DiskSnippetCache_get(snippetID);
      if (text != null)
        return text;
    }

    String text;
    try {
      URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID);
      text = loadPage(url);
    } catch (FileNotFoundException e) {
      throw new IOException("Snippet #" + snippetID + " not found or not public");
    }

    try {
      initSnippetCache();
      DiskSnippetCache_put(snippetID, text);
    } catch (IOException e) {
      System.err.println("Minor warning: Couldn't save snippet to cache ("  + DiskSnippetCache_getDir() + ")");
    }

    return text;
  }

  private static String loadPage(URL url) throws IOException {
    System.out.println("Loading: " + url.toExternalForm());
    URLConnection con = url.openConnection();
    return loadPage(con, url);
  }

  public static String loadPage(URLConnection con, URL url) throws IOException {
    String contentType = con.getContentType();
    if (contentType == null)
      throw new IOException("Page could not be read: " + url);
    //Log.info("Content-Type: " + contentType);
    String charset = guessCharset(contentType);
    Reader r = new InputStreamReader(con.getInputStream(), charset);
    StringBuilder buf = new StringBuilder();
    while (true) {
      int ch = r.read();
      if (ch < 0)
        break;
      //Log.info("Chars read: " + buf.length());
      buf.append((char) ch);
    }
    return buf.toString();
  }

  public static String guessCharset(String contentType) {
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
    Matcher m = p.matcher(contentType);
    /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
    return m.matches() ? m.group(1) : "ISO-8859-1";
  }
  
  static File DiskSnippetCache_dir;

  public static void initDiskSnippetCache(File dir) {
    DiskSnippetCache_dir = dir;
    dir.mkdirs();
  }

  public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
    return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
  }

  private static File DiskSnippetCache_getFile(long snippetID) {
    return new File(DiskSnippetCache_dir, "" + snippetID);
  }

  public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
    saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
  }

  public static File DiskSnippetCache_getDir() {
    return DiskSnippetCache_dir;
  }

  public static void initSnippetCache() {
    if (DiskSnippetCache_dir == null)
      initDiskSnippetCache(new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"));
  }
}

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: 1254 / 3190
Referenced in: [show references]