Beispiel #1
1
  public ConsoleManager(GlowServer server) {
    this.server = server;

    // install Ansi code handler, which makes colors work on Windows
    AnsiConsole.systemInstall();

    for (Handler h : logger.getHandlers()) {
      logger.removeHandler(h);
    }

    // used until/unless gui is created
    consoleHandler = new FancyConsoleHandler();
    // consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE));
    logger.addHandler(consoleHandler);

    // todo: why is this here?
    Runtime.getRuntime().addShutdownHook(new ServerShutdownThread());

    // reader must be initialized before standard streams are changed
    try {
      reader = new ConsoleReader();
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Exception initializing console reader", ex);
    }
    reader.addCompleter(new CommandCompleter());

    // set system output streams
    System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true));
    System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true));
  }
Beispiel #2
0
  void run() throws Exception {
    File classesDir = new File("classes");
    classesDir.mkdirs();
    writeFile(baseFile, baseText);
    String[] javacArgs = {"-d", classesDir.getPath(), baseFile.getPath()};
    com.sun.tools.javac.Main.compile(javacArgs);

    writeFile(srcFile, srcText);
    String[] args = {
      "-d", "api", "-classpath", classesDir.getPath(), "-package", "p", srcFile.getPath()
    };

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    PrintStream prev = System.err;
    System.setErr(ps);
    try {
      int rc = com.sun.tools.javadoc.Main.execute(args);
    } finally {
      System.err.flush();
      System.setErr(prev);
    }
    String out = baos.toString();
    System.out.println(out);

    String errorMessage = "java.lang.IllegalArgumentException: <clinit>";
    if (out.contains(errorMessage)) throw new Exception("error message found: " + errorMessage);
  }
 @Override
 protected String run(final String... args) throws IOException {
   try {
     final ArrayOutput ao = new ArrayOutput();
     System.setOut(new PrintStream(ao));
     System.setErr(NULL);
     new BaseX(args);
     return ao.toString();
   } finally {
     System.setOut(OUT);
     System.setErr(ERR);
   }
 }
  public static void initApplicationDirs() throws IOException {
    createTrustStoreFileIfNotExists();
    File appDataRoot = new File(applicationDataDir());
    if (!appDataRoot.exists()) {
      appDataRoot.mkdirs();
    }
    if (!appDataRoot.canWrite()) {
      SEAGridDialogHelper.showExceptionDialogAndWait(
          new Exception("Cannot Write to Application Data Dir"),
          "Cannot Write to Application Data Dir",
          null,
          "Cannot Write to Application Data Dir " + applicationDataDir());
    }

    // Legacy editors use stdout and stderr instead of loggers. This is a workaround to append them
    // to a file
    System.setProperty("app.data.dir", applicationDataDir() + "logs");
    logger = LoggerFactory.getLogger(SEAGridDesktop.class);
    File logParent = new File(applicationDataDir() + "logs");
    if (!logParent.exists()) logParent.mkdirs();
    PrintStream outPs = new PrintStream(applicationDataDir() + "logs/seagrid.std.out");
    PrintStream errPs = new PrintStream(applicationDataDir() + "logs/seagrid.std.err");
    System.setOut(outPs);
    System.setErr(errPs);
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              public void run() {
                outPs.close();
                errPs.close();
              }
            });

    extractLegacyEditorResources();
  }
Beispiel #5
0
 /** Initializes logging facility, called once by VisEditor. */
 public static void init() {
   if (initialized) throw new IllegalStateException("Log cannot be initialized twice!");
   initialized = true;
   prepareLogFile();
   System.setOut(new PrintStream(new TeeOutputStream(System.out, logFileStream)));
   System.setErr(new PrintStream(new TeeOutputStream(System.err, logFileStream)));
 }
Beispiel #6
0
  /**
   * Runs a request with the specified arguments and server arguments.
   *
   * @param args command-line arguments
   * @param sargs server arguments
   * @return result
   * @throws IOException I/O exception
   */
  private static String run(final String[] args, final String[] sargs) throws IOException {
    final BaseXServer server = createServer(sargs);
    final ArrayOutput ao = new ArrayOutput();
    System.setOut(new PrintStream(ao));
    System.setErr(NULL);

    final StringList sl = new StringList();
    sl.add("-p9999").add("-U" + Text.S_ADMIN).add("-P" + Text.S_ADMIN).add(args);
    try {
      new BaseXClient(sl.finish());
      return ao.toString();
    } finally {
      System.setErr(ERR);
      stopServer(server);
    }
  }
 /** Try the given mail server, writing output to the given PrintStream */
 public static void process(String suspect_relay, PrintStream pw) {
   pw.println("processs: trying: " + suspect_relay);
   try {
     // Redirect all output from mail API to the given stream.
     System.setOut(pw);
     System.setErr(pw);
     Sender2 sm = new Sender2(suspect_relay);
     sm.addRecipient("*****@*****.**");
     sm.setFrom(MY_TARGET);
     sm.setSubject("Testing for open mail relay, see " + RSS_SITE);
     sm.setBody(
         "This mail is an attempt to confirm that site "
             + suspect_relay
             + "\n"
             + "is in fact an open mail relay site.\n"
             + "For more information on the problem of open mail relays,\n"
             + "please visit site "
             + RSS_SITE
             + "\n"
             + "Please join the fight against spam by closing all open mail relays!\n"
             + "If this open relay has been closed, please accept our thanks.\n");
     sm.sendFile();
   } catch (MessagingException e) {
     pw.println(e);
   } catch (Exception e) {
     pw.println(e);
   }
 }
Beispiel #8
0
  /**
   * When installed, System.out and System.err are redirected to Syslog.log. System.out produces
   * info events, and System.err produces error events.
   */
  public static void install() {
    synchronized (log()) {
      if (!cInstalled) {
        cInstalled = true;
        cOriginalOut = System.out;
        cOriginalErr = System.err;

        cSystemOut =
            new LogEventParsingOutputStream(log(), LogEvent.INFO_TYPE) {
              public boolean isEnabled() {
                return log().isInfoEnabled();
              }
            };
        cSystemOut.addLogListener(log());
        System.setOut(new PrintStream(cSystemOut, true));

        cSystemErr =
            new LogEventParsingOutputStream(log(), LogEvent.ERROR_TYPE) {
              public boolean isEnabled() {
                return log().isErrorEnabled();
              }
            };
        cSystemErr.addLogListener(log());
        System.setErr(new PrintStream(cSystemErr, true));
      }
    }
  }
Beispiel #9
0
  public EntityImpl() throws Exception {
    factory = Outside.service(this, "gus.io.printstream.factory.multi.hist");

    p1 = (PrintStream) factory.g();
    ((P) p1).p(System.err);
    System.setErr(p1);
  }
 @Test
 public void shouldWriteToSystemErrByDefault() {
   PrintStream originalErrStream = System.err;
   try {
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     System.setErr(new PrintStream(out));
     enricher.printStackTrace(exception);
     String output = new String(out.toByteArray());
     assertTrue(
         "JUnit jar "
             + JUNIT_JAR_PATTERN
             + " not found in stack trace written to default System.err stream",
         output.contains(JUNIT_JAR_PATTERN));
   } finally {
     System.setErr(originalErrStream);
   }
 }
 protected static int run(String message, String[] commandArray, File outputFile) {
   PrintStream out = System.out;
   PrintStream err = System.err;
   PrintStream fileStream = null;
   try {
     outputFile.getParentFile().mkdirs();
     fileStream = new PrintStream(new FileOutputStream(outputFile));
     System.setErr(fileStream);
     System.setOut(fileStream);
     return run(message, commandArray);
   } catch (FileNotFoundException e) {
     return -1;
   } finally {
     System.setOut(out);
     System.setErr(err);
     if (fileStream != null) fileStream.close();
   }
 }
Beispiel #12
0
 private void redirectIO() {
   // redirect std I/O to console and problems:
   // > System.out => console
   // > System.err => problems
   // > console => System.in
   System.setOut(consoleView.getOutputStream());
   System.setErr(problemsView.getOutputStream());
   // redirect input from console to System.in
   System.setIn(consoleView.getInputStream());
 }
  /**
   * Acquires output stream for logging errors in tests.
   *
   * @return Junit error print stream.
   */
  public static synchronized GridTestPrintStream acquireErr() {
    // Lazy initialization is required here to ensure that parent
    // thread group is picked off correctly by implementation.
    if (testErr == null) testErr = new GridTestPrintStream(sysErr);

    if (errCnt == 0) System.setErr(testErr);

    errCnt++;

    return testErr;
  }
Beispiel #14
0
  public Application(String configurationFile) {
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutDownListener()));
    Properties props = getPropertiesFromFile(configurationFile);

    try {
      init(props);
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (isErrorFileOutput) {
      try {
        err =
            new BufferedOutputStream(
                new FileOutputStream(
                    ApplicationRegistry.getOutputDirectory()
                        + configurationFile
                        + "."
                        + DateUtils.ts()
                        + ".err.txt"));
        System.setErr(new PrintStream(err));
      } catch (FileNotFoundException e1) {
        e1.printStackTrace();
      }
    }

    if (isOutputFileOutput) {
      try {
        oput =
            new BufferedOutputStream(
                new FileOutputStream(
                    ApplicationRegistry.getOutputDirectory()
                        + configurationFile
                        + "."
                        + DateUtils.ts()
                        + ".txt"));
        System.setOut(new PrintStream(oput));
      } catch (FileNotFoundException e1) {
        e1.printStackTrace();
      }
    }

    try {
      runApplication();
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      finish();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #15
0
  Object evalScript(
      String script,
      StringBuffer scriptOutput,
      boolean captureOutErr,
      HttpServletRequest request,
      HttpServletResponse response)
      throws EvalError {
    // Create a PrintStream to capture output
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream pout = new PrintStream(baos);

    // Create an interpreter instance with a null inputstream,
    // the capture out/err stream, non-interactive
    Interpreter bsh = new Interpreter(null, pout, pout, false);

    // set up interpreter
    bsh.set("bsh.httpServletRequest", request);
    bsh.set("bsh.httpServletResponse", response);

    // Eval the text, gathering the return value or any error.
    Object result = null;
    String error = null;
    PrintStream sout = System.out;
    PrintStream serr = System.err;
    if (captureOutErr) {
      System.setOut(pout);
      System.setErr(pout);
    }
    try {
      // Eval the user text
      result = bsh.eval(script);
    } finally {
      if (captureOutErr) {
        System.setOut(sout);
        System.setErr(serr);
      }
    }
    pout.flush();
    scriptOutput.append(baos.toString());
    return result;
  }
Beispiel #16
0
 /** Invoked after all test classes in this test have been run */
 public void onFinish(ITestContext context) {
   try {
     for (DataOutputStream out : tests.values()) Util.close(out);
     tests.clear();
     generateReports();
   } catch (IOException e) {
     error(e.toString());
   } finally {
     System.setOut(old_stdout);
     System.setErr(old_stderr);
   }
 }
Beispiel #17
0
  /** Invoked at the start of the test, before any of the classes in the test are run */
  public void onStart(ITestContext context) {
    output_dir = context.getOutputDirectory();
    // Uncomment to delete dir created by previous run of this testsuite
    File dir = new File(output_dir);
    if (dir.exists()) deleteContents(dir);

    try {
      System.setOut(new MyOutput(1));
      System.setErr(new MyOutput(2));
    } catch (FileNotFoundException e) {
    }
  }
Beispiel #18
0
 /** Uninstalls by restoring System.out and System.err. */
 public static void uninstall() {
   synchronized (log()) {
     if (cInstalled) {
       cInstalled = false;
       System.setOut(cOriginalOut);
       System.setErr(cOriginalErr);
       cOriginalOut = null;
       cOriginalErr = null;
       cSystemOut = null;
       cSystemErr = null;
     }
   }
 }
Beispiel #19
0
  private static void writeLogRecords(PrintStream logps) throws Exception {
    PrintStream err = System.err;
    try {
      System.setErr(logps);

      Object[] params = new Object[] {new Long(1), "string"};
      PlatformLogger plog = PlatformLogger.getLogger("test.log.foo");
      plog.severe("Log message {0} {1}", (Object[]) params);

      // create a java.util.logging.Logger
      // now java.util.logging.Logger should be created for each platform
      // logger
      Logger logger = Logger.getLogger("test.log.bar");
      logger.log(Level.SEVERE, "Log message {0} {1}", params);

      plog.severe("Log message {0} {1}", (Object[]) params);
    } finally {
      logps.flush();
      logps.close();
      System.setErr(err);
    }
  }
  @Override
  protected void setUp() throws Exception {
    final Document document = new SAXBuilder().build(new File(getTestDataRoot(), "/RETest.xml"));
    final List<Element> list = XPath.selectNodes(document.getRootElement(), "//test");
    new File(getTestDataPath()).mkdirs();

    int i = 0;
    for (Element element : list) {
      final String name;
      final Element parent = (Element) element.getParent();
      final String s = parent.getName();
      final String t =
          parent.getAttribute("id") == null ? "" : parent.getAttribute("id").getValue() + "-";
      if (!"tests".equals(s)) {
        name = s + "/test-" + t + ++i + ".regexp";
      } else {
        name = "test-" + t + ++i + ".regexp";
      }
      final Result result =
          Result.valueOf((String) XPath.selectSingleNode(element, "string(expected)"));
      final boolean warn = !"false".equals(element.getAttributeValue("warning"));
      final boolean info = "true".equals(element.getAttributeValue("info"));
      myMap.put(name, new Test(result, warn, info));

      final File file = new File(getTestDataPath(), name);
      file.getParentFile().mkdirs();

      final FileWriter stream = new FileWriter(file);
      final String pattern = (String) XPath.selectSingleNode(element, "string(pattern)");
      if (!"false".equals(element.getAttributeValue("verify")))
        try {
          Pattern.compile(pattern);
          if (result == Result.ERR) {
            System.out.println("Incorrect FAIL value for " + pattern);
          }
        } catch (PatternSyntaxException e) {
          if (result == Result.OK) {
            System.out.println("Incorrect OK value for " + pattern);
          }
        }
      stream.write(pattern);
      stream.close();
    }

    super.setUp();

    myOut = new ByteArrayOutputStream();
    System.setErr(new PrintStream(myOut));
  }
Beispiel #21
0
  @Before
  public void init() {
    alist.add(a1);
    alist.add(a2);
    alist.add(a3);
    alist.add(a4);
    alist.add(a5);
    alist.add(a6);
    alist.add(a7);
    alist.add(a8);
    alist.add(a9);

    System.setOut(new PrintStream(outContent));
    System.setErr(new PrintStream(errContent));
  }
 /**
  * Assigns the error PrintStream to a temporary text file. This is to allow a log file
  * (creativityGAResults.log) to be created which holds log data from running the program, for
  * later analysis.
  *
  * @return a copy of the original System.err PrintStream, for later re-assignment
  */
 static PrintStream divertStandardError() {
   // Save the current standard input, output, and error streams
   // for later restoration.
   PrintStream origErr = System.err;
   try {
     File error = new File("creativityGAResults.log");
     error.createNewFile();
   } catch (Exception e) {
     e.printStackTrace(origErr);
   }
   try {
     System.setErr(new PrintStream(new FileOutputStream("creativityGAResults.log")));
   } catch (Exception e) {
     e.printStackTrace(origErr);
   }
   return origErr;
 }
Beispiel #23
0
  public static void main(final String[] args) {

    File logdir = new File(LOG_DIR);
    if (!logdir.exists()) logdir.mkdirs();
    File log = new File(logdir, "client.log");
    // redirect all console output to the file
    try {
      PrintStream out = new PrintStream(new FileOutputStream(log, true), true);
      out.format("[%s] ===== Client started =====%n", timestampf.format(new Date()));
      System.setOut(out);
      System.setErr(out);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    /* Set up the error handler as early as humanly possible. */
    ThreadGroup g = new ThreadGroup("Haven main group");
    String ed;
    if (!(ed = Utils.getprop("haven.errorurl", "")).equals("")) {
      try {
        final haven.error.ErrorHandler hg = new haven.error.ErrorHandler(new java.net.URL(ed));
        hg.sethandler(
            new haven.error.ErrorGui(null) {
              public void errorsent() {
                hg.interrupt();
              }
            });
        g = hg;
      } catch (java.net.MalformedURLException e) {
      }
    }
    Thread main =
        new HackThread(
            g,
            new Runnable() {
              public void run() {
                main2(args);
              }
            },
            "Haven main thread");
    main.start();
  }
  private void redirectSystemStreams() {
    OutputStream out =
        new OutputStream() {
          @Override
          public void write(int b) throws IOException {
            updateTextArea(String.valueOf((char) b));
          }

          @Override
          public void write(byte[] b, int off, int len) throws IOException {
            updateTextArea(new String(b, off, len));
          }

          @Override
          public void write(byte[] b) throws IOException {
            write(b, 0, b.length);
          }
        };

    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(out, true));
  }
  /**
   * preprocesses a pde file and writes out a java file
   *
   * @return the class name of the exported Java
   */
  private String write(final String program, final PrintWriter stream)
      throws SketchException, RecognitionException, TokenStreamException {

    // Match on the uncommented version, otherwise code inside comments used
    // http://code.google.com/p/processing/issues/detail?id=1404
    String uncomment = scrubComments(program);
    PdeRecognizer parser = createParser(program);
    if (PUBLIC_CLASS.matcher(uncomment).find()) {
      try {
        final PrintStream saved = System.err;
        try {
          // throw away stderr for this tentative parse
          System.setErr(new PrintStream(new ByteArrayOutputStream()));
          parser.javaProgram();
        } finally {
          System.setErr(saved);
        }
        setMode(Mode.JAVA);
      } catch (Exception e) {
        // I can't figure out any other way of resetting the parser.
        parser = createParser(program);
        parser.pdeProgram();
      }
    } else if (FUNCTION_DECL.matcher(uncomment).find()) {
      setMode(Mode.ACTIVE);
      parser.activeProgram();
    } else {
      parser.pdeProgram();
    }

    // set up the AST for traversal by PdeEmitter
    //
    ASTFactory factory = new ASTFactory();
    AST parserAST = parser.getAST();
    AST rootNode = factory.create(ROOT_ID, "AST ROOT");
    rootNode.setFirstChild(parserAST);

    makeSimpleMethodsPublic(rootNode);

    // unclear if this actually works, but it's worth a shot
    //
    // ((CommonAST)parserAST).setVerboseStringConversion(
    //  true, parser.getTokenNames());
    // (made to use the static version because of jikes 1.22 warning)
    BaseAST.setVerboseStringConversion(true, parser.getTokenNames());

    final String className;
    if (mode == Mode.JAVA) {
      // if this is an advanced program, the classname is already defined.
      className = getFirstClassName(parserAST);
    } else {
      className = this.name;
    }

    // if 'null' was passed in for the name, but this isn't
    // a 'java' mode class, then there's a problem, so punt.
    //
    if (className == null) return null;

    // debug
    if (false) {
      final StringWriter buf = new StringWriter();
      final PrintWriter bufout = new PrintWriter(buf);
      writeDeclaration(bufout, className);
      new PdeEmitter(this, bufout).print(rootNode);
      writeFooter(bufout, className);
      debugAST(rootNode, true);
      System.err.println(buf.toString());
    }

    writeDeclaration(stream, className);
    new PdeEmitter(this, stream).print(rootNode);
    writeFooter(stream, className);

    // if desired, serialize the parse tree to an XML file.  can
    // be viewed usefully with Mozilla or IE
    if (Preferences.getBoolean("preproc.output_parse_tree")) {
      writeParseTree("parseTree.xml", parserAST);
    }

    return className;
  }
  public static void main() {
    // Main
    frame = new JFrame("Java Playground");
    frame.setSize(640, 480);
    // Make sure the divider is properly resized
    frame.addComponentListener(
        new ComponentAdapter() {
          public void componentResized(ComponentEvent c) {
            splitter.setDividerLocation(.8);
          }
        });
    // Make sure the JVM is reset on close
    frame.addWindowListener(
        new WindowAdapter() {
          public void windowClosed(WindowEvent w) {
            new FrameAction().kill();
          }
        });

    // Setting up the keybinding
    // Ctrl+k or Cmd+k -> compile
    bind(KeyEvent.VK_K);

    // Ctrl+e or Cmd+e -> console
    bind(KeyEvent.VK_E);

    // Save, New file, Open file, Print.
    // Currently UNUSED until I figure out how normal java files and playground files will
    // interface.
    bind(KeyEvent.VK_S);
    bind(KeyEvent.VK_N);
    bind(KeyEvent.VK_O);
    bind(KeyEvent.VK_P);

    // Binds the keys to the action defined in the FrameAction class.
    frame.getRootPane().getActionMap().put("console", new FrameAction());

    // The main panel for typing code in.
    text = new JTextPane();
    textScroll = new JScrollPane(text);
    textScroll.setBorder(null);
    textScroll.setPreferredSize(new Dimension(640, 480));

    // Document with syntax highlighting. Currently unfinished.
    doc = text.getStyledDocument();
    doc.addDocumentListener(
        new DocumentListener() {
          public void changedUpdate(DocumentEvent d) {}

          public void insertUpdate(DocumentEvent d) {}

          public void removeUpdate(DocumentEvent d) {}
        });

    ((AbstractDocument) doc).setDocumentFilter(new NewLineFilter());

    // The output log; a combination compiler warning/error/runtime error/output log.
    outputText = new JTextPane();
    outputScroll = new JScrollPane(outputText);
    outputScroll.setBorder(null);

    // "Constant" for the error font
    error = new SimpleAttributeSet();
    error.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE);
    error.addAttribute(StyleConstants.Foreground, Color.RED);

    // "Constant" for the warning message font
    warning = new SimpleAttributeSet();
    warning.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE);
    warning.addAttribute(StyleConstants.Foreground, Color.PINK);

    // "Constant" for the debugger error font
    progErr = new SimpleAttributeSet();
    progErr.addAttribute(StyleConstants.Foreground, Color.BLUE);

    // Print streams to redirect System.out and System.err.
    out = new TextOutputStream(outputText, null);
    err = new TextOutputStream(outputText, error);
    System.setOut(new PrintStream(out));
    System.setErr(new PrintStream(err));

    // Sets up the output log
    outputText.setEditable(false);
    outputScroll.setVisible(true);

    // File input/output setup
    chooser = new JFileChooser();

    // Setting up miscellaneous stuff
    compiler = ToolProvider.getSystemJavaCompiler();
    JVMrunning = false;
    redirectErr = null;
    redirectOut = null;
    redirectIn = null;

    // Sets up the splitter pane and opens the program up
    splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT, textScroll, outputScroll);
    consoleDisplayed = false;
    splitter.remove(outputScroll); // Initially hides terminal until it is needed
    splitter.setOneTouchExpandable(true);
    frame.add(splitter);
    frame.setVisible(true);

    // Sets the divider to the proper one, for debugging
    // splitter.setDividerLocation(.8);
  }
    private int runEclipseCompiler(String[] output, List<String> cmdline) {
      try {
        List<String> final_cmdline = new LinkedList<String>(cmdline);

        // remove compiler name from argument list
        final_cmdline.remove(0);

        Class eclipseCompiler = Class.forName(ECLIPSE_COMPILER_CLASS);

        Method compileMethod = eclipseCompiler.getMethod("main", new Class[] {String[].class});

        final_cmdline.add(0, "-noExit");
        final_cmdline.add(0, "-progress");
        final_cmdline.add(0, "-verbose");

        File _logfile = new File(this.idata.getInstallPath(), "compile-" + getName() + ".log");

        if (Debug.isTRACE()) {
          final_cmdline.add(0, _logfile.getPath());
          final_cmdline.add(0, "-log");
        }

        // get log files / determine results...
        try {
          // capture stdout and stderr
          PrintStream _orgStdout = System.out;
          PrintStream _orgStderr = System.err;
          int error_count = 0;

          try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            EclipseStdOutHandler ownStdout = new EclipseStdOutHandler(outStream, this.listener);
            System.setOut(ownStdout);
            ByteArrayOutputStream errStream = new ByteArrayOutputStream();
            EclipseStdErrHandler ownStderr = new EclipseStdErrHandler(errStream, this.listener);
            System.setErr(ownStderr);

            compileMethod.invoke(
                null, new Object[] {final_cmdline.toArray(new String[final_cmdline.size()])});

            // TODO: launch thread which updates the progress
            output[0] = outStream.toString();
            output[1] = errStream.toString();
            error_count = ownStderr.getErrorCount();
            // for debugging: write output to log files
            if (error_count > 0 || Debug.isTRACE()) {
              File _out = new File(_logfile.getPath() + ".stdout");
              FileOutputStream _fout = new FileOutputStream(_out);
              _fout.write(outStream.toByteArray());
              _fout.close();
              _out = new File(_logfile.getPath() + ".stderr");
              _fout = new FileOutputStream(_out);
              _fout.write(errStream.toByteArray());
              _fout.close();
            }

          } finally {
            System.setOut(_orgStdout);
            System.setErr(_orgStderr);
          }

          if (error_count == 0) {
            return 0;
          }

          // TODO: construct human readable error message from log
          this.listener.emitNotification("Compiler reported " + error_count + " errors");

          return 1;
        } catch (FileNotFoundException fnfe) {
          this.listener.emitError("error compiling", fnfe.getMessage());
          return -1;
        } catch (IOException ioe) {
          this.listener.emitError("error compiling", ioe.getMessage());
          return -1;
        }

      } catch (ClassNotFoundException cnfe) {
        output[0] = "error getting eclipse compiler";
        output[1] = cnfe.getMessage();
        return -1;
      } catch (NoSuchMethodException nsme) {
        output[0] = "error getting eclipse compiler method";
        output[1] = nsme.getMessage();
        return -1;
      } catch (IllegalAccessException iae) {
        output[0] = "error calling eclipse compiler";
        output[1] = iae.getMessage();
        return -1;
      } catch (InvocationTargetException ite) {
        output[0] = "error calling eclipse compiler";
        output[1] = ite.getMessage();
        return -1;
      }
    }
  /*
   * Accepts a new request from the HTTP server and creates
   * a conventional execution environment for the request.
   * If the application was invoked as a FastCGI server,
   * the first call to FCGIaccept indicates that the application
   * has completed its initialization and is ready to accept
   * a request.  Subsequent calls to FCGI_accept indicate that
   * the application has completed its processing of the
   * current request and is ready to accept a new request.
   * If the application was invoked as a CGI program, the first
   * call to FCGIaccept is essentially a no-op and the second
   * call returns EOF (-1) as does an error. Application should exit.
   *
   * If the application was invoked as a FastCGI server,
   * and this is not the first call to this procedure,
   * FCGIaccept first flushes any buffered output to the HTTP server.
   *
   * On every call, FCGIaccept accepts the new request and
   * reads the FCGI_PARAMS stream into System.props. It also creates
   * streams that understand FastCGI protocol and take input from
   * the HTTP server send output and error output to the HTTP server,
   * and assigns these new streams to System.in, System.out and
   * System.err respectively.
   *
   * For now, we will just return an int to the caller, which is why
   * this method catches, but doen't throw Exceptions.
   *
   */
  public int FCGIaccept() {
    int acceptResult = 0;

    /*
     * If first call, mark it and if fcgi save original system properties,
     * If not first call, and  we are cgi, we should be gone.
     */
    if (!acceptCalled) {
      isFCGI = System.getenv("FCGI_PORT") != null;
      acceptCalled = true;
      if (isFCGI) {
        /*
         * save original system properties (nonrequest)
         * and get a server socket
         */
        startupProps = new Properties(System.getProperties());
        String str = new String(System.getenv("FCGI_PORT"));
        if (str.length() <= 0) {
          return -1;
        }
        int portNum = Integer.parseInt(str);

        try {
          srvSocket = new ServerSocket(portNum);
        } catch (IOException e) {
          if (request != null) {
            request.socket = null;
          }
          srvSocket = null;
          request = null;
          return -1;
        }
      }
    } else {
      if (!isFCGI) {
        return -1;
      }
    }
    /*
     * If we are cgi, just leave everything as is, otherwise set up env
     */
    if (isFCGI) {
      try {
        acceptResult = FCGIAccept();
      } catch (IOException e) {
        return -1;
      }
      if (acceptResult < 0) {
        return -1;
      }

      /*
       * redirect stdin, stdout and stderr to fcgi socket
       */
      System.setIn(new BufferedInputStream(request.inStream, 8192));
      System.setOut(new PrintStream(new BufferedOutputStream(request.outStream, 8192)));
      System.setErr(new PrintStream(new BufferedOutputStream(request.errStream, 512)));
      System.setProperties(request.params);
    }
    return 0;
  }
Beispiel #29
0
  public ConsoleManager(GlowServer server) {
    this.server = server;

    // install Ansi code handler, which makes colors work on Windows
    AnsiConsole.systemInstall();

    for (Handler h : logger.getHandlers()) {
      logger.removeHandler(h);
    }

    // add log handler which writes to console
    logger.addHandler(new FancyConsoleHandler());

    // reader must be initialized before standard streams are changed
    try {
      reader = new ConsoleReader();
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Exception initializing console reader", ex);
    }
    reader.addCompleter(new CommandCompleter());

    // set system output streams
    System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true));
    System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true));

    // set up colorization replacements
    replacements.put(
        ChatColor.BLACK,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString());
    replacements.put(
        ChatColor.DARK_BLUE,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString());
    replacements.put(
        ChatColor.DARK_GREEN,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString());
    replacements.put(
        ChatColor.DARK_AQUA,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString());
    replacements.put(
        ChatColor.DARK_RED,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString());
    replacements.put(
        ChatColor.DARK_PURPLE,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString());
    replacements.put(
        ChatColor.GOLD,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString());
    replacements.put(
        ChatColor.GRAY,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString());
    replacements.put(
        ChatColor.DARK_GRAY,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString());
    replacements.put(
        ChatColor.BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString());
    replacements.put(
        ChatColor.GREEN,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString());
    replacements.put(
        ChatColor.AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString());
    replacements.put(
        ChatColor.RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).bold().toString());
    replacements.put(
        ChatColor.LIGHT_PURPLE,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString());
    replacements.put(
        ChatColor.YELLOW,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString());
    replacements.put(
        ChatColor.WHITE,
        Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString());
    replacements.put(ChatColor.MAGIC, Ansi.ansi().a(Ansi.Attribute.BLINK_SLOW).toString());
    replacements.put(ChatColor.BOLD, Ansi.ansi().a(Ansi.Attribute.UNDERLINE_DOUBLE).toString());
    replacements.put(
        ChatColor.STRIKETHROUGH, Ansi.ansi().a(Ansi.Attribute.STRIKETHROUGH_ON).toString());
    replacements.put(ChatColor.UNDERLINE, Ansi.ansi().a(Ansi.Attribute.UNDERLINE).toString());
    replacements.put(ChatColor.ITALIC, Ansi.ansi().a(Ansi.Attribute.ITALIC).toString());
    replacements.put(ChatColor.RESET, Ansi.ansi().a(Ansi.Attribute.RESET).toString());
  }
Beispiel #30
0
  @Override
  public void run() {
    try {
      Thread.currentThread().setName("ServerEngine");
      System.setOut(new Misc.TimestampLogger(System.out));
      System.setErr(new Misc.TimestampLogger(System.err, "./data/err.log"));

      address = new InetSocketAddress(host, port);
      System.out.println("Starting " + Constants.SERVER_NAME + " on " + address + "...");

      // load shutdown hook
      Thread shutdownhook = new ShutDownHook();
      Runtime.getRuntime().addShutdownHook(shutdownhook);

      PacketManager.loadPackets();

      Cache.load();

      // load scripts
      Misc.loadScripts(new File("./data/ruby/"));

      GlobalVariables.patchNotes = Misc.loadPatchNotes();
      GlobalVariables.info = Misc.loadInfo();
      GlobalVariables.npcDump = Misc.getNpcDump();
      GlobalVariables.itemDump = Misc.getItemDump();

      // load all xstream related files.
      XStreamUtil.loadAllFiles();

      // item weights
      ItemDefinition.loadWeight();

      // interfaces
      RSInterface.load();

      // Load plugins
      PluginManager.loadPlugins();

      // Load regions
      ObjectDef.loadConfig();
      Region.load();
      Rangable.load();

      // Load objects
      ObjectLoader objectLoader = new ObjectLoader();
      objectLoader.load();

      GameObjectData.init();

      // load combat manager
      CombatManager.init();

      // Load minute timer
      startMinutesCounter();

      // global drops
      GlobalGroundItem.initialize();

      // load npc ls
      Npc.loadNpcDrops();

      // mage arena timers
      AlchemistPlayground.loadAlchemistPlayGround();
      EnchantingChamber.loadEnchantingChamber();
      CreatureGraveyard.loadCreatureGraveyard();

      // spawning world fishing spots
      FishingSpots.spawnFishingSpots();

      QuestHandler.init();

      NpcLoader.loadAutoSpawn("./data/npcs/spawn-config.cfg");

      HighscoresManager.load();

      // Start up and get a'rollin!
      startup();
      System.out.println("Online!");
      while (!Thread.interrupted()) {
        try {
          cycle();
          sleep();
        } catch (Exception ex) {
          PlayerSave.saveAllPlayers();
          ex.printStackTrace();
        }
      }
      scheduler.schedule(
          new Task() {
            @Override
            protected void execute() {
              if (Thread.interrupted()) {
                PlayerSave.saveAllPlayers();
                stop();
                return;
              }
              try {
                cycle();
              } catch (Exception ex) {
                PlayerSave.saveAllPlayers();
                ex.printStackTrace();
                stop();
              }
            }
          });
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    PluginManager.close();
  }