Exemplo n.º 1
0
  static void processFiles(Context cx, String[] files) throws IOException {
    StringBuffer cout = new StringBuffer();
    if (files.length > 0) {
      for (int i = 0; i < files.length; i++) {
        try {
          String source = (String) readFileOrUrl(files[i], true);
          cout.append(Compressor.compressScript(source, 0, 1, escapeUnicode, stripConsole));
        } catch (IOException ex) {
          // continue processing files
        }
      }
    } else {
      byte[] data = Kit.readStream(global.getIn(), 4096);
      // Convert to String using the default encoding
      String source = new String(data);
      if (source != null) {
        cout.append(Compressor.compressScript(source, 0, 1, escapeUnicode, stripConsole));
      }
    }

    global.getOut().println(cout);
  }
Exemplo n.º 2
0
  private static Object readFileOrUrl(String path, boolean convertToString) throws IOException {
    URL url = null;
    // Assume path is URL if it contains a colon and there are at least
    // 2 characters in the protocol part. The later allows under Windows
    // to interpret paths with driver letter as file, not URL.
    if (path.indexOf(':') >= 2) {
      try {
        url = new URL(path);
      } catch (MalformedURLException ex) {
      }
    }

    InputStream is = null;
    int capacityHint = 0;
    if (url == null) {
      File file = new File(path);
      capacityHint = (int) file.length();
      try {
        is = new FileInputStream(file);
      } catch (IOException ex) {
        Context.reportError(getMessage("msg.couldnt.open", path));
        throw ex;
      }
    } else {
      try {
        URLConnection uc = url.openConnection();
        is = uc.getInputStream();
        capacityHint = uc.getContentLength();
        // Ignore insane values for Content-Length
        if (capacityHint > (1 << 20)) {
          capacityHint = -1;
        }
      } catch (IOException ex) {
        Context.reportError(getMessage("msg.couldnt.open.url", url.toString(), ex.toString()));
        throw ex;
      }
    }
    if (capacityHint <= 0) {
      capacityHint = 4096;
    }

    byte[] data;
    try {
      try {
        is = new BufferedInputStream(is);
        data = Kit.readStream(is, capacityHint);
      } finally {
        is.close();
      }
    } catch (IOException ex) {
      Context.reportError(ex.toString());
      throw ex;
    }

    Object result;
    if (convertToString) {
      // Convert to String using the default encoding
      // TODO: Use 'charset=' argument of Content-Type if URL?
      result = new String(data);
    } else {
      result = data;
    }
    return result;
  }