/**
   * Logs a message to the error log.
   *
   * @param log the error log to write the message.
   * @param message the message to write
   * @param e the exception to write
   */
  public void log(
      String message,
      Throwable e,
      HttpServletRequest request,
      HttpServletResponse response,
      ServletContext application)
      throws IOException {
    WriteStream logStream = getLogStream();

    if (logStream == null) return;

    Throwable t = e;
    while (t != null) {
      e = t;

      if (e instanceof ServletException) t = ((ServletException) e).getRootCause();
      else if (e instanceof ExceptionWrapper) t = ((ExceptionWrapper) e).getRootCause();
      else t = null;
    }

    CharBuffer cb = CharBuffer.allocate();

    QDate.formatLocal(cb, CurrentTime.getCurrentTime(), "[%Y/%m/%d %H:%M:%S] ");

    cb.append(message);

    logStream.log(cb.close());

    if (e != null && !(e instanceof CompileException)) logStream.log(e);

    logStream.flush();
  }
  private Path writeTempFile(Node node) throws IOException {
    Path workDir = CauchoSystem.getWorkPath().lookup("_xsl");
    workDir.mkdirs();

    // Path temp = workDir.createTempFile("tmp", "xsl");

    WriteStream os = Vfs.lookup("null:").openWrite();
    Crc64Stream crcStream = new Crc64Stream(os.getSource());
    os.init(crcStream);
    try {
      XmlPrinter printer = new XmlPrinter(os);

      printer.printNode(node);
    } finally {
      os.close();
    }

    long crc = crcStream.getCRC();
    CharBuffer cb = new CharBuffer();
    Base64.encode(cb, crc);

    String crcValue = cb.toString().replace('/', '-');

    Path xslPath = workDir.lookup(crcValue + ".xsl");

    // temp.renameTo(xslPath);

    return xslPath;
  }
  protected void flushStream() throws IOException {
    synchronized (_logLock) {
      if (_os != null) _os.flush();

      if (_zipOut != null) _zipOut.flush();
    }
  }
Example #4
0
  public void execute(Path path) throws IOException {
    QuercusPage page = parse(path);

    WriteStream os = new WriteStream(StdoutStream.create());

    os.setNewlineString("\n");
    os.setEncoding("iso-8859-1");

    Env env = createEnv(page, os, null, null);
    env.start();

    try {
      env.execute();
    } catch (QuercusDieException e) {
      log.log(Level.FINER, e.toString(), e);
    } catch (QuercusExitException e) {
      log.log(Level.FINER, e.toString(), e);
    } catch (QuercusErrorException e) {
      log.log(Level.FINER, e.toString(), e);
    } finally {
      env.close();

      os.flush();
    }
  }
 /** Prints the code to create an LongLiteral. */
 @Override
 public void printCreate(WriteStream os) throws IOException {
   os.print("new com.caucho.el.EqExpr(");
   _left.printCreate(os);
   os.print(", ");
   _right.printCreate(os);
   os.print(")");
 }
Example #6
0
  public RepositoryTagMap(
      AbstractRepository repository,
      RepositoryTagMap parent,
      Map<String, RepositoryTagEntry> tagMap)
      throws IOException {
    _tagMap = Collections.unmodifiableMap(tagMap);

    long now = Alarm.getCurrentTime();

    if (parent.getSequence() < now) _sequence = now;
    else _sequence = parent.getSequence() + 1;

    TempStream os = new TempStream();
    WriteStream out = new WriteStream(os);

    writeTagMap(out);
    out.close();

    String tagHash;

    InputStream is = os.getInputStream();

    try {
      tagHash = repository.addBlob(is);
    } finally {
      is.close();
    }

    _tree = new GitTree();

    _tree.addBlob("tags", 0775, tagHash);

    for (String key : tagMap.keySet()) {
      RepositoryTagEntry entry = tagMap.get(key);

      String sha1 = entry.getTagEntryHash();
      String root = entry.getRoot();

      _tree.addBlob(sha1, 0644, sha1);

      GitType type = repository.getType(root);

      if (type == GitType.BLOB) _tree.addBlob(root, 0644, root);
      else if (type == GitType.TREE) _tree.addDir(root, root);
      else throw new IllegalStateException(L.l("'{0}' has an unknown type {1}", root, type));
    }

    String treeHash = repository.addTree(_tree);

    _commit = new GitCommit();
    _commit.setTree(treeHash);
    _commit.put("sequence", String.valueOf(_sequence));

    _commitHash = repository.addCommit(_commit);
  }
  private Class generateProxy() {
    try {
      JavaClassLoader jLoader = new JavaClassLoader(_cl.getClassLoader());

      JavaClass jClass = new JavaClass(jLoader);
      jClass.setAccessFlags(Modifier.PUBLIC);
      ConstantPool cp = jClass.getConstantPool();

      jClass.setWrite(true);

      jClass.setMajor(49);
      jClass.setMinor(0);

      String superClassName = _cl.getName().replace('.', '/');
      String thisClassName = superClassName + "$BeanProxy";

      jClass.setSuperClass(superClassName);
      jClass.setThisClass(thisClassName);

      jClass.addInterface("java/io/Serializable");
      jClass.addInterface("com/caucho/config/inject/HandleAware");

      generateConstructors(jClass, superClassName);

      generateWriteReplace(jClass);
      generateSetHandle(jClass);

      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      WriteStream out = Vfs.openWrite(bos);

      jClass.write(out);

      out.close();

      byte[] buffer = bos.toByteArray();

      if (false) {
        String userName = System.getProperty("user.name");

        out = Vfs.lookup("file:/tmp/" + userName + "/qa/temp.class").openWrite();
        out.write(buffer, 0, buffer.length);
        out.close();
      }

      String cleanName = thisClassName.replace('/', '.');
      _proxyClass = (Class<X>) new ProxyClassLoader().loadClass(cleanName, buffer);
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    return _proxyClass;
  }
  protected void writeResponse(OutputStream out, Object result) throws IOException, RestException {
    WriteStream ws = Vfs.openWrite(out);

    try {
      XMLStreamWriterImpl writer = new XMLStreamWriterImpl(ws);

      _marshaller.marshal(result, writer);
    } catch (JAXBException e) {
      throw new RuntimeException(e);
    } finally {
      ws.close();
    }
  }
Example #9
0
  @Override
  protected void printRImpl(
      Env env, WriteStream out, int depth, IdentityHashMap<Value, String> valueSet)
      throws IOException {
    if (_classDef.printRImpl(env, _object, out, depth, valueSet)) {
      return;
    }

    Set<? extends Map.Entry<Value, Value>> entrySet = entrySet();

    if (entrySet == null) {
      out.print("resource(" + toString(env) + ")"); // XXX:
      return;
    }

    out.print(_classDef.getSimpleName());
    out.println(" Object");
    printRDepth(out, depth);
    out.print("(");

    for (Map.Entry<Value, Value> entry : entrySet) {
      out.println();
      printRDepth(out, depth);
      out.print("    [" + entry.getKey() + "] => ");

      entry.getValue().printRImpl(env, out, depth + 1, valueSet);
    }

    out.println();
    printRDepth(out, depth);
    out.println(")");
  }
  /** Writes to the underlying log. */
  protected void write(byte[] buffer, int offset, int length) throws IOException {
    /*
    String s = new String(buffer, offset, length);
    if (s.startsWith("127")) {
      System.out.println("WRITE: " + s);
      Thread.dumpStack();

    }
    */

    synchronized (_logLock) {
      if (_isRollingOver && getTempStreamMax() < _tempStreamSize) {
        try {
          _logLock.wait();
        } catch (Exception e) {
        }
      }

      if (!_isRollingOver) {
        if (_os == null) openLog();

        if (_os != null) _os.write(buffer, offset, length);
      } else {
        if (_tempStream == null) {
          _tempStream = createTempStream();
          _tempStreamSize = 0;
        }

        _tempStreamSize += length;
        _tempStream.write(buffer, offset, length, false);
      }
    }
  }
  @Override
  public void close(int code, String msg) {
    if (_isWriteClosed.getAndSet(true)) return;

    try {
      WriteStream out = getWriteStream();

      out.write(0x88);
      out.write(0x00);
      out.flush();
    } catch (IOException e) {
      log.log(Level.WARNING, e.toString(), e);
    } finally {
      disconnect();
    }
  }
  /** Tries to close the log. */
  private void closeLogStream() {
    try {
      WriteStream os = _os;
      _os = null;

      if (os != null) os.close();
    } catch (Throwable e) {
      // can't log in log routines
    }

    try {
      WriteStream zipOut = _zipOut;
      _zipOut = null;

      if (zipOut != null) zipOut.close();
    } catch (Throwable e) {
      // can't log in log routines
    }
  }
  /**
   * Generates the XML text representation for the tag validation.
   *
   * @param os write stream to the generated XML.
   */
  public void printXml(WriteStream os) throws IOException {
    os.print("<" + getTagName());

    for (int i = 0; i < _attrNames.size(); i++) {
      QName name = _attrNames.get(i);
      String value = _attrValues.get(i);

      os.print(" " + name.getName() + "=\"");

      printXmlText(os, value);

      os.print("\"");
    }

    os.print(">");

    printXmlChildren(os);

    os.print("</" + getTagName() + ">");
  }
  /**
   * Logs an error.
   *
   * @param message the error message
   * @param request the servlet request
   * @param response the servlet response
   * @param application the servlet context
   */
  public void log(
      String message,
      HttpServletRequest request,
      HttpServletResponse response,
      ServletContext application)
      throws IOException {
    WriteStream logStream = getLogStream();

    if (logStream == null) return;

    CharBuffer cb = CharBuffer.allocate();

    QDate.formatLocal(cb, CurrentTime.getCurrentTime(), "[%Y/%m/%d %H:%M:%S] ");

    cb.append(message);

    logStream.log(cb.close());

    logStream.flush();
  }
Example #15
0
  private void writeHeader(WriteStream ws, int type, int length) throws IOException {
    int id = 1;
    int pad = 0;

    ws.write(FCGI_VERSION);
    ws.write(type);
    ws.write(id >> 8);
    ws.write(id);
    ws.write(length >> 8);
    ws.write(length);
    ws.write(pad);
    ws.write(0);
  }
Example #16
0
  @Override
  protected void varDumpImpl(
      Env env, WriteStream out, int depth, IdentityHashMap<Value, String> valueSet)
      throws IOException {
    Value oldThis = env.setThis(this);

    try {
      if (!_classDef.varDumpImpl(env, this, _object, out, depth, valueSet))
        out.print("resource(" + toString(env) + ")"); // XXX:
    } finally {
      env.setThis(oldThis);
    }
  }
  @Override
  public int doCommand(WatchdogArgs args, WatchdogClient client, WebAppDeployClient deployClient) {
    String fileName = args.getDefaultArg();

    if (fileName == null) {
      throw new ConfigException(L.l("Cannot find a filename in command line"));
    }

    CommitBuilder commit = createCommitBuilder(args);

    try {
      WriteStream out = Vfs.openWrite(System.out);

      deployClient.getFile(commit.getId(), fileName, out);

      out.flush();
    } catch (IOException e) {
      throw ConfigException.create(e);
    }

    return 0;
  }
  public static void writeStream(OutputStream os, Call call, int length) throws Throwable {
    if (length < 1) return;

    char[] buf = new char[256];
    int len;

    Object obj = call.getArgObject(0, length);
    if (obj instanceof ReadStream) {
      ReadStream is = (ReadStream) obj;
      is.writeToStream(os);
    } else if (obj instanceof ReadWritePair) {
      ((ReadWritePair) obj).getReadStream().writeToStream(os);
    } else if (obj instanceof InputStream) {
      if (os instanceof WriteStream) {
        ((WriteStream) os).writeStream((InputStream) obj);
      } else {
        int ch;
        InputStream is = (InputStream) obj;
        while ((ch = is.read()) >= 0) os.write(ch);
      }
    } else throw new IllegalArgumentException("expected stream at " + obj.getClass().getName());
  }
  /**
   * Generates the XML text representation for the tag validation.
   *
   * @param os write stream to the generated XML.
   */
  public void printXml(WriteStream os) throws IOException {
    os.print("<jsp:directive.page");
    printJspId(os);
    if (!_parseState.isELIgnored()) os.print(" el-ignored='false'");
    /*
    if (! _parseState.isScriptingEnabled())
      os.print(" scripting-enabled='false'");
    */
    if (_parseState.getContentType() != null)
      os.print(" content-type='" + _parseState.getContentType() + "'");

    ArrayList<String> imports = _parseState.getImportList();

    if (imports != null && imports.size() != 0) {
      os.print(" import='");
      for (int i = 0; i < imports.size(); i++) {
        if (i != 0) os.print(',');
        os.print(imports.get(i));
      }
      os.print("'");
    }

    os.print("/>");
  }
  public static void writeDepend(Path dependPath, ArrayList<PersistentDependency> dependList)
      throws IOException {
    WriteStream os = dependPath.openWrite();
    try {
      for (int i = 0; i < dependList.size(); i++) {
        PersistentDependency dependency = dependList.get(i);

        if (dependency instanceof Depend) {
          Depend depend = (Depend) dependency;

          os.print('"');
          os.print(depend.getPath().getNativePath());
          os.print("\" \"");
          os.print(depend.getDigest());
          os.println("\"");
        }
      }
    } finally {
      os.close();
    }
  }
Example #21
0
  /** var_dump() implementation */
  public void varDumpImpl(
      Env env, Value obj, WriteStream out, int depth, IdentityHashMap<Value, String> valueSet)
      throws IOException {
    String name = "SimpleXMLElement";

    if (obj != null) name = obj.getClassName();

    // php/1x33
    if (_text != null && _children == null && _attributes == null) {
      if (depth > 0) {
        _text.varDump(env, out, depth, valueSet);
        return;
      }

      out.println("object(" + name + ") (1) {");
      printDepth(out, 2 * (depth + 1));
      out.println("[0]=>");

      printDepth(out, 2 * (depth + 1));
      _text.varDump(env, out, depth, valueSet);
      out.println();

      printDepth(out, 2 * depth);
      out.print("}");

      return;
    }

    Set<Map.Entry<Value, Value>> entrySet = entrySet();
    out.println("object(" + name + ") (" + entrySet.size() + ") {");

    for (Map.Entry<Value, Value> entry : entrySet) {
      printDepth(out, 2 * (depth + 1));
      out.print("[");

      if (entry.getKey().isString()) out.print("\"" + entry.getKey() + "\"");
      else out.print(entry.getKey());

      out.println("]=>");

      printDepth(out, 2 * (depth + 1));
      entry.getValue().varDump(env, out, depth + 1, valueSet);
      out.println();
    }

    printDepth(out, 2 * depth);
    out.print('}');
  }
Example #22
0
 protected void printDepth(WriteStream out, int depth) throws IOException {
   for (int i = 0; i < depth; i++) out.print(' ');
 }
Example #23
0
  private void addHeader(ClientSocket stream, WriteStream ws, CharBuffer key, String value)
      throws IOException {
    int keyLen = key.getLength();
    int valLen = value.length();

    int len = keyLen + valLen;

    if (keyLen < 0x80) len += 1;
    else len += 4;

    if (valLen < 0x80) len += 1;
    else len += 4;

    writeHeader(ws, FCGI_PARAMS, len);

    if (keyLen < 0x80) ws.write(keyLen);
    else {
      ws.write(0x80 | (keyLen >> 24));
      ws.write(keyLen >> 16);
      ws.write(keyLen >> 8);
      ws.write(keyLen);
    }

    if (valLen < 0x80) ws.write(valLen);
    else {
      ws.write(0x80 | (valLen >> 24));
      ws.write(valLen >> 16);
      ws.write(valLen >> 8);
      ws.write(valLen);
    }

    ws.print(key.getBuffer(), 0, keyLen);
    ws.print(value);
  }
Example #24
0
  private boolean handleRequest(
      HttpServletRequest req,
      HttpServletResponse res,
      ClientSocket stream,
      OutputStream out,
      boolean keepalive)
      throws ServletException, IOException {
    ReadStream rs = stream.getInputStream();
    WriteStream ws = stream.getOutputStream();

    writeHeader(ws, FCGI_BEGIN_REQUEST, 8);

    int role = FCGI_RESPONDER;

    ws.write(role >> 8);
    ws.write(role);
    ws.write(keepalive ? FCGI_KEEP_CONN : 0); // flags
    for (int i = 0; i < 5; i++) ws.write(0);

    setEnvironment(stream, ws, req);

    InputStream in = req.getInputStream();
    TempBuffer tempBuf = TempBuffer.allocate();
    byte[] buf = tempBuf.getBuffer();
    int len = buf.length;
    int sublen;

    writeHeader(ws, FCGI_PARAMS, 0);

    boolean hasStdin = false;
    while ((sublen = in.read(buf, 0, len)) > 0) {
      hasStdin = true;
      writeHeader(ws, FCGI_STDIN, sublen);
      ws.write(buf, 0, sublen);
    }

    TempBuffer.free(tempBuf);
    tempBuf = null;

    /*
    if (hasStdin)
      writeHeader(fcgiSocket, ws, FCGI_STDIN, 0);
    */
    writeHeader(ws, FCGI_STDIN, 0);

    ws.flush();

    FastCGIInputStream is = new FastCGIInputStream(stream);

    int ch = parseHeaders(res, is);

    if (ch >= 0) out.write(ch);

    TempBuffer tb = TempBuffer.allocate();
    byte[] buffer = tb.getBuffer();

    while ((sublen = is.read(buffer, 0, buffer.length)) > 0) {
      out.write(buffer, 0, sublen);
    }

    TempBuffer.free(tb);

    return !is.isDead() && keepalive;
  }
  private void movePathToArchive(Path savedPath) {
    if (savedPath == null) return;

    synchronized (_logLock) {
      closeLogStream();
    }

    Path path = getPath();

    String savedName = savedPath.getTail();

    try {
      if (!savedPath.getParent().isDirectory()) savedPath.getParent().mkdirs();
    } catch (Exception e) {
      logWarning(L.l("Can't open archive directory {0}", savedPath.getParent()), e);
    }

    try {
      if (path.exists()) {
        WriteStream os = null;
        OutputStream out = null;

        // *.gz and *.zip are copied.  Others are just renamed
        if (savedName.endsWith(".gz")) {
          os = savedPath.openWrite();
          out = new GZIPOutputStream(os);
        } else if (savedName.endsWith(".zip")) {
          os = savedPath.openWrite();

          ZipOutputStream zip = new ZipOutputStream(os);
          String entryName = savedName.substring(0, savedName.length() - 4);
          ZipEntry entry = new ZipEntry(entryName);
          zip.putNextEntry(entry);

          out = zip;
        }

        if (out != null) {
          try {
            path.writeToStream(out);
          } finally {
            try {
              out.close();
            } catch (Exception e) {
              // can't log in log rotation routines
            }

            try {
              if (out != os) os.close();
            } catch (Exception e) {
              // can't log in log rotation routines
            }
          }
        } else {
          path.renameTo(savedPath);
        }
      }
    } catch (Exception e) {
      logWarning(L.l("Error rotating logs: {0}", e.toString()), e);
    }

    try {
      path.remove();
      /*
      try {
        if (! path.truncate())
          path.remove();
      } catch (IOException e) {
        path.remove();

        throw e;
      }
      */
    } catch (Exception e) {
      logWarning(L.l("Error truncating logs"), e);
    }

    if (_rolloverCount > 0) removeOldLogs();
  }
  @Override
  public void flush() throws IOException {
    WriteStream out = getWriteStream();

    out.flush();
  }
Example #27
0
 private static void printRDepth(WriteStream out, int depth) throws IOException {
   for (int i = 0; i < 8 * depth; i++) out.print(' ');
 }
Example #28
0
  private static void readMultipartStream(
      Env env,
      MultipartStream ms,
      ArrayValue postArray,
      ArrayValue files,
      boolean addSlashesToValues,
      boolean isAllowUploads)
      throws IOException {
    ReadStream is;

    while ((is = ms.openRead()) != null) {
      String attr = (String) ms.getAttribute("content-disposition");

      if (attr == null || !attr.startsWith("form-data")) {
        // XXX: is this an error?
        continue;
      }

      String name = getAttribute(attr, "name", addSlashesToValues);
      String filename = getAttribute(attr, "filename", addSlashesToValues);

      if (filename != null) {
        int slashIndex = filename.lastIndexOf('/');
        int slashIndex2 = filename.lastIndexOf('\\');

        slashIndex = Math.max(slashIndex, slashIndex2);

        if (slashIndex >= 0) filename = filename.substring(slashIndex + 1);
      }

      int bracketIndex = -1;

      if (name != null) bracketIndex = name.lastIndexOf(']');

      if (bracketIndex >= 0 && bracketIndex < name.length() - 1) {
        // php/085c
      } else if (filename == null) {
        StringValue value = env.createStringBuilder();

        value.appendReadAll(is, Integer.MAX_VALUE);

        if (name != null) {
          addFormValue(env, postArray, name, value, null, addSlashesToValues);
        } else {
          env.warning(L.l("file upload is missing name and filename"));
        }
      } else {
        if (!isAllowUploads) {
          continue;
        }

        String tmpName = "";
        long tmpLength = 0;

        // A POST file upload with an empty string as the filename does not
        // create a temp file in the upload directory.

        if (filename.length() > 0) {
          Path tmpPath = env.getUploadDirectory().createTempFile("php", ".tmp");

          env.addRemovePath(tmpPath);

          WriteStream os = tmpPath.openWrite();
          try {
            os.writeStream(is);
          } finally {
            os.close();
          }

          tmpName = tmpPath.getFullPath();
          tmpLength = tmpPath.getLength();
        }

        // php/0865
        //
        // A header like "Content-Type: image/gif" indicates the mime type
        // for an uploaded file.

        String mimeType = getAttribute(attr, "mime-type", addSlashesToValues);
        if (mimeType == null) {
          mimeType = (String) ms.getAttribute("content-type");

          // php/085f
          if (mimeType != null && mimeType.endsWith(";"))
            mimeType = mimeType.substring(0, mimeType.length() - 1);
        }

        // php/0864
        //
        // mime type is empty string when no file is uploaded.

        if (filename.length() == 0) {
          mimeType = "";
        }

        long maxFileSize = Long.MAX_VALUE;

        Value maxFileSizeV = postArray.get(MAX_FILE_SIZE);
        if (!maxFileSizeV.isNull()) maxFileSize = maxFileSizeV.toLong();

        if (name != null) {
          addFormFile(
              env,
              files,
              name,
              filename,
              tmpName,
              mimeType,
              tmpLength,
              addSlashesToValues,
              maxFileSize);
        } else {
          addFormFile(
              env, files, filename, tmpName, mimeType, tmpLength, addSlashesToValues, maxFileSize);
        }
      }
    }
  }
Example #29
0
  /** Prints the date to a stream. */
  public void printDate(WriteStream os) throws IOException {
    os.print(DAY_NAMES[(int) (_dayOfEpoch % 7 + 11) % 7]);
    os.write(',');
    os.write(' ');
    os.print((_dayOfMonth + 1) / 10);
    os.print((_dayOfMonth + 1) % 10);
    os.write(' ');
    os.print(MONTH_NAMES[(int) _month]);
    os.write(' ');
    os.print(_year);
    os.write(' ');
    os.print((_timeOfDay / 36000000) % 10);
    os.print((_timeOfDay / 3600000) % 10);
    os.write(':');
    os.print((_timeOfDay / 600000) % 6);
    os.print((_timeOfDay / 60000) % 10);
    os.write(':');
    os.print((_timeOfDay / 10000) % 6);
    os.print((_timeOfDay / 1000) % 10);

    if (_zoneName == null) {
      os.print(" GMT");
      return;
    }

    long offset = _zoneOffset;

    if (offset < 0) {
      os.write(' ');
      os.write('-');
      offset = -offset;
    } else {
      os.write(' ');
      os.write('+');
    }

    os.print((offset / 36000000) % 10);
    os.print((offset / 3600000) % 10);
    os.print((offset / 600000) % 6);
    os.print((offset / 60000) % 10);

    os.write(' ');
    os.write('(');
    os.print(_zoneName);
    os.write(')');
  }
Example #30
0
 private void writeTagMap(WriteStream out) throws IOException {
   for (Map.Entry<String, RepositoryTagEntry> entry : _tagMap.entrySet()) {
     out.println(entry.getKey());
     out.println(entry.getValue().getTagEntryHash());
   }
 }