/** Called from inside _logLock */
  private void flushTempStream() {
    TempStreamApi ts = _tempStream;
    _tempStream = null;
    _tempStreamSize = 0;

    try {
      if (ts != null) {
        if (_os == null) openLog();

        try {
          ReadStream is = ts.openRead();

          try {
            is.writeToStream(_os);
          } finally {
            is.close();
          }
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          ts.destroy();
        }
      }
    } finally {
      _logLock.notifyAll();
    }
  }
  /** Executes the JSP Page */
  public void service(ServletRequest request, ServletResponse response)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    _caucho_init(req, res);

    if (_hasSession) {
      req.getSession();
      res.setHeader("Cache-Control", "private");
    }

    // res.setContentLength(_contentLength);

    TempCharBuffer buf = TempCharBuffer.allocate();
    char[] cBuf = buf.getBuffer();
    int len;

    PrintWriter out = response.getWriter();

    ReadStream rs = _cacheEntry.openRead();
    rs.setEncoding("UTF-8");
    try {
      while ((len = rs.read(cBuf, 0, cBuf.length)) > 0) {
        out.write(cBuf, 0, len);
      }
    } finally {
      rs.close();
    }

    TempCharBuffer.free(buf);
  }
  /** Compile a schema. */
  public Schema compileSchema(Path path) throws SAXException, IOException {
    String nativePath = path.getNativePath();

    SoftReference<Schema> schemaRef = _schemaMap.get(path);
    Schema schema = null;

    if (schemaRef != null && (schema = schemaRef.get()) != null) {
      // XXX: probably eventually add an isModified
      return schema;
    }

    ReadStream is = path.openRead();

    try {
      InputSource source = new InputSource(is);

      source.setSystemId(path.getUserPath());

      schema = compileSchema(source);

      if (schema != null) _schemaMap.put(path, new SoftReference<Schema>(schema));
    } finally {
      is.close();
    }

    return schema;
  }
  /**
   * Convenience class to create a compiled stylesheet.
   *
   * @param systemId source path for the stylesheet.
   * @return a compiled stylesheet
   */
  public javax.xml.transform.Templates newTemplates(String systemId)
      throws TransformerConfigurationException {
    StylesheetImpl stylesheet = loadPrecompiledStylesheet(systemId, systemId);

    if (stylesheet != null) return stylesheet;
    else if (systemId == null) return generate(new QDocument(), null);

    Path path = getSearchPath().lookup(systemId);

    try {
      ReadStream is = path.openRead();
      Document doc;
      try {
        doc = parseXSL(is);
      } finally {
        is.close();
      }

      return generate(doc, path);
    } catch (TransformerConfigurationException e) {
      throw e;
    } catch (IOException e) {
      System.out.println("MP: " + ((MergePath) getSearchPath()).getMergePaths());
      throw new TransformerConfigurationExceptionWrapper(e);
    } catch (Exception e) {
      throw new TransformerConfigurationExceptionWrapper(e);
    }
  }
  private void parseSAX(Source source, ContentHandler handler)
      throws TransformerConfigurationException {
    try {
      if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;

        XMLReader reader = saxSource.getXMLReader();
        InputSource inputSource = saxSource.getInputSource();

        reader.setContentHandler(handler);

        reader.parse(inputSource);
      } else if (source instanceof StreamSource) {

        XmlParser parser = new Xml();

        parser.setContentHandler(handler);

        ReadStream rs = openPath(source);
        try {
          parser.parse(rs);
        } finally {
          rs.close();
        }
      } else if (source instanceof DOMSource) {
        DOMSource domSource = (DOMSource) source;

        Node node = domSource.getNode();

        XmlUtil.toSAX(node, handler);
      }
    } catch (Exception e) {
      throw new TransformerConfigurationException(e);
    }
  }
  public static void writeFile(OutputStream os, Path path) throws IOException {
    ReadStream stream = path.openRead();

    try {
      stream.writeToStream(os);
    } finally {
      stream.close();
    }
  }
  /**
   * Create a compiled stylesheet from an input stream.
   *
   * @param source the source stream
   * @return the compiled stylesheet
   */
  public Templates newTemplates(Source source) throws TransformerConfigurationException {
    String systemId = source.getSystemId();

    try {
      if (systemId != null) {
        StylesheetImpl stylesheet = loadPrecompiledStylesheet(systemId, systemId);

        if (stylesheet != null) return stylesheet;
      }

      if (source instanceof DOMSource) {
        Node node = ((DOMSource) source).getNode();

        return generateFromNode(node, systemId);
      } else if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        XMLReader reader = saxSource.getXMLReader();
        InputSource inputSource = saxSource.getInputSource();

        Document doc = new QDocument();
        DOMBuilder builder = new DOMBuilder();
        builder.init(doc);
        reader.setContentHandler(builder);

        reader.parse(inputSource);

        return generateFromNode(doc, systemId);
      }

      ReadStream rs = openPath(source);
      try {
        Path path = rs.getPath();

        Document doc = parseXSL(rs);

        if (systemId != null) {
          String mangledName = getMangledName(systemId);
          Path genPath = getWorkPath().lookup(mangledName);

          genPath.setUserPath(systemId);

          return generate(doc, genPath);
        } else return generateFromNode(doc, null);
      } finally {
        if (rs != null) rs.close();
      }
    } catch (TransformerConfigurationException e) {
      throw e;
    } catch (Exception e) {
      throw new XslParseException(e);
    }
  }
  /** Compile a schema. */
  public Schema compileSchema(String url) throws SAXException, IOException {
    Path path = Vfs.lookup(url);

    ReadStream is = path.openRead();
    try {
      InputSource source = new InputSource(is);
      source.setSystemId(url);

      return compileSchema(source);
    } finally {
      is.close();
    }
  }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
  /** Parses a stylesheet from the source. */
  protected Node parseStylesheet(Source source) throws TransformerConfigurationException {
    if (source instanceof DOMSource) return ((DOMSource) source).getNode();
    else if (source instanceof StreamSource) {
      InputStream is = ((StreamSource) source).getInputStream();
      ReadStream rs = null;

      try {
        rs = Vfs.openRead(is);
        return parseXSL(rs);
      } catch (Exception e) {
        throw new TransformerConfigurationException(e);
      } finally {
        if (rs != null) rs.close();
      }
    } else return null;
  }
Esempio n. 11
0
  private byte[] load(String className) throws IOException {
    Path path = getPostWorkPath().lookup(className.replace('.', '/') + ".class");
    int length = (int) path.getLength();

    if (length < 0)
      throw new FileNotFoundException(L.l("Can't find class file '{0}'", path.getNativePath()));

    byte[] buffer = new byte[length];

    ReadStream is = path.openRead();
    try {
      is.readAll(buffer, 0, buffer.length);
    } finally {
      is.close();
    }

    return buffer;
  }
  static ArrayList<Depend> parseDepend(Path dependPath) throws IOException {
    ReadStream is = dependPath.openRead();
    try {
      ArrayList<Depend> dependList = new ArrayList<Depend>();

      String name;

      while ((name = parseName(is)) != null) {
        long digest = Long.parseLong(parseName(is));

        Depend depend = new Depend(dependPath.lookup(name), digest);

        dependList.add(depend);
      }

      return dependList;
    } finally {
      is.close();
    }
  }
Esempio n. 13
0
  private static Node parse(
      Env env, Value data, int options, boolean dataIsUrl, String namespace, boolean isPrefix)
      throws IOException, ParserConfigurationException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document document = null;

    if (dataIsUrl) {
      Path path = env.lookup(data.toStringValue());

      // PHP throws an Exception instead
      if (path == null) {
        log.log(Level.FINE, L.l("Cannot read file/URL '{0}'", data));
        env.warning(L.l("Cannot read file/URL '{0}'", data));

        return null;
      }

      ReadStream is = path.openRead();

      try {
        document = builder.parse(is);
      } finally {
        is.close();
      }
    } else {
      StringReader reader = new java.io.StringReader(data.toString());

      document = builder.parse(new InputSource(reader));
    }

    NodeList childList = document.getChildNodes();

    // php/1x70
    for (int i = 0; i < childList.getLength(); i++) {
      if (childList.item(i).getNodeType() == Node.ELEMENT_NODE) return childList.item(i);
    }

    return childList.item(0);
  }
  /**
   * Loads a stylesheet from a named file
   *
   * @param systemId the URL of the file
   */
  public StylesheetImpl newStylesheet(String systemId) throws Exception {
    StylesheetImpl stylesheet = loadPrecompiledStylesheet(systemId, systemId);

    if (stylesheet != null) return stylesheet;

    synchronized (AbstractStylesheetFactory.class) {
      stylesheet = loadPrecompiledStylesheet(systemId, systemId);

      if (stylesheet != null) return stylesheet;

      ReadStream is;

      if (_stylePath != null) is = _stylePath.lookup(systemId).openRead();
      else is = Vfs.lookup(systemId).openRead();

      try {
        return newStylesheet(is);
      } finally {
        if (is != null) is.close();
      }
    }
  }
Esempio n. 15
0
  static void fillPost(
      Env env,
      ArrayValue postArray,
      ArrayValue files,
      InputStream is,
      String contentType,
      String encoding,
      int contentLength,
      boolean addSlashesToValues,
      boolean isAllowUploads) {
    long maxPostSize = env.getIniBytes("post_max_size", 0);

    try {
      if (encoding == null) encoding = env.getHttpInputEncoding();

      if (contentType != null && contentType.startsWith("multipart/form-data")) {

        String boundary = getBoundary(contentType);

        ReadStream rs = new ReadStream(new VfsStream(is, null));

        if (boundary == null) {
          env.warning(L.l("multipart/form-data POST is missing boundary"));

          return;
        }

        MultipartStream ms = new MultipartStream(rs, boundary);

        if (encoding != null) ms.setEncoding(encoding);

        readMultipartStream(env, ms, postArray, files, addSlashesToValues, isAllowUploads);

        rs.close();

        if (rs.getLength() > maxPostSize) {
          env.warning(
              L.l("POST length of {0} exceeds max size of {1}", rs.getLength(), maxPostSize));

          postArray.clear();
          files.clear();

          return;
        }
      } else {
        StringValue bb = env.createBinaryBuilder();

        bb.appendReadAll(is, Integer.MAX_VALUE);

        if (bb.length() > maxPostSize) {
          env.warning(L.l("POST length of {0} exceeds max size of {1}", bb.length(), maxPostSize));
          return;
        }

        env.setInputData(bb);

        if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded"))
          StringUtility.parseStr(env, bb, postArray, false, encoding);
      }

    } catch (IOException e) {
      env.warning(e);
    } finally {
    }
  }
Esempio n. 16
0
 void close() {
   if (_in != null) _in.close();
 }