private static void testSysOut(String fs, String exp, Object... args) {
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
      PrintStream saveOut = System.out;
      fos = new FileOutputStream("testSysOut");
      System.setOut(new PrintStream(fos));
      System.out.format(Locale.US, fs, args);
      fos.close();

      fis = new FileInputStream("testSysOut");
      byte[] ba = new byte[exp.length()];
      int len = fis.read(ba);
      String got = new String(ba);
      if (len != ba.length) fail(fs, exp, got);
      ck(fs, exp, got);

      System.setOut(saveOut);
    } catch (FileNotFoundException ex) {
      fail(fs, ex.getClass());
    } catch (IOException ex) {
      fail(fs, ex.getClass());
    } finally {
      try {
        if (fos != null) fos.close();
        if (fis != null) fis.close();
      } catch (IOException ex) {
        fail(fs, ex.getClass());
      }
    }
  }
Example #2
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));
  }
Example #3
0
  public static void main(String[] args) {

    PrintStream out = System.out;

    try {
      File file = new File("game.txt");
      PrintStream printStream = new PrintStream(new FileOutputStream(file));
      System.setOut(printStream);
    } catch (Exception e) {
      System.out.println("Cannot open game.txt for writing");
      return;
    }

    for (int i = 0; i < 100; i++) {
      PlayFakeGame();
    }

    System.setOut(out);

    System.out.println("Wrote output of 100 games to game.txt");
    File expectedFile = new File("expected.txt");
    if (expectedFile.exists()) {
      String expected = readFile("expected.txt");
      String actual = readFile("game.txt");

      System.out.println();
      System.out.println(
          "Diff with expected.txt: " + (actual.equals(expected) ? "OK!" : "Failure!!!"));
    } else {
      System.out.println("expected.txt missing. Rename game.txt to expected.txt and try again");
    }
  }
  /**
   * One round of test for max_retries and timeout.
   *
   * @param expected the expected kdc# timeout kdc# timeout...
   */
  private static void test0(ByteArrayOutputStream bo, String expected) throws Exception {
    PrintStream oldout = System.out;
    boolean failed = false;
    System.setOut(new PrintStream(bo));
    try {
      Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
    } catch (Exception e) {
      failed = true;
    } finally {
      System.setOut(oldout);
    }

    String[] lines = new String(bo.toByteArray()).split("\n");
    StringBuilder sb = new StringBuilder();
    for (String line : lines) {
      Matcher m = re.matcher(line);
      if (m.find()) {
        System.out.println(line);
        sb.append(m.group(1)).append(toSymbolicSec(Integer.parseInt(m.group(2))));
      }
    }
    if (failed) sb.append('-');

    String output = sb.toString();
    System.out.println("Expected: " + expected + ", actual " + output);
    if (!output.matches(expected)) {
      throw new Exception("Does not match");
    }
  }
Example #5
0
 @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 int test(int n) throws Exception {
    PrintStream oldOut = System.out;
    int sum = 0;
    for (int i = 0; i < 10; i++) {
      ByteArrayOutputStream ba = new ByteArrayOutputStream(n * 10);
      PrintStream newOut = new PrintStream(ba);
      System.setOut(newOut);
      doPrint(n);
      sum += ba.size();
    }

    System.setOut(oldOut);
    return sum;
  }
  public static void createFileFromTwoFiles(
      String inputFileName1, String inputFileName2, String outputFileName) throws IOException {
    /*
     * Won't work with multithreads as there is the posibility someone will
     * try to write to the screen or two different executions of this
     * function.
     */

    PrintStream oldSystemOut = System.out;
    PrintStream ps = new PrintStream(outputFileName);
    System.setOut(ps);
    copyFileToTheStandardOutput(inputFileName1);
    copyFileToTheStandardOutput(inputFileName2);
    System.setOut(oldSystemOut);
    ps.close();
  }
Example #8
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)));
 }
Example #9
0
 public static void main(String[] args) throws IOException {
   PrintStream consoleStream = System.out;
   ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
   PrintStream stream = new PrintStream(outputStream);
   System.setOut(stream);
   testString.printSomething();
   String result = outputStream.toString();
   System.setOut(consoleStream);
   BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
   String file = reader.readLine();
   reader.close();
   BufferedWriter bw = new BufferedWriter(new FileWriter(file));
   bw.write(result);
   bw.close();
   System.out.println(result);
 }
Example #10
0
 public static void main(String[] args) throws Exception {
   Scanner sc = new Scanner(new File("B.in"));
   System.setOut(new PrintStream("B.out"));
   //		sc = new Scanner(System.in);
   List<Integer> pr = new ArrayList<Integer>();
   boolean[] comp = new boolean[300000];
   for (int i = 2; i < 550; i++) {
     if (p(i) && !comp[i]) {
       for (int j = 2; i * j < 300000; j++) {
         comp[i * j] = true;
       }
       pr.add(i);
     }
   }
   for (int i = 550; i < 300000; i++) {
     if (p(i) && !comp[i]) pr.add(i);
   }
   // System.out.println(pr);
   for (int n = sc.nextInt(); n != 1; n = sc.nextInt()) {
     System.out.print(n + ":");
     for (int i = 0; i < pr.size(); i++) {
       if (n % pr.get(i) == 0) System.out.print(" " + pr.get(i));
     }
     System.out.println();
   }
 }
 /** 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);
   }
 }
Example #12
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));
      }
    }
  }
  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();
  }
Example #14
0
 private static void setStream(String in, String out) {
   try {
     System.setIn(new BufferedInputStream(new FileInputStream(in)));
     System.setOut(new PrintStream(out));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #15
0
File: vans.java Project: were/progs
 public static void main(String args[]) {
   try {
     System.setIn(new FileInputStream("vans.in"));
     System.setOut(new PrintStream("vans.out"));
   } catch (Throwable T_T) {
   }
   new vans().run();
 }
  public static void main(String[] args) {
    TreeMap<String, ArrayList<String>> topicToQuestionMap = Utility.getTopicToQuestionMap();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    PrintStream old = System.out;
    System.setOut(ps);

    JsonObject info = new JsonObject();
    Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    for (Map.Entry<String, ArrayList<String>> entry : topicToQuestionMap.entrySet()) {
      String topic = entry.getKey();
      ArrayList<String> questions = entry.getValue();
      JsonObject quesToSol = new JsonObject();
      for (String question : questions) {
        baos.reset();
        question = question.split("\\.")[0];
        Class cls = null;
        try {
          cls = Class.forName(topic + "." + question);
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }
        try {
          Method method = cls.getMethod("main", String[].class);
          method.invoke(null, new Object[] {new String[] {}});
        } catch (Exception e) {
          System.out.println("This is a helper class to be used by other programs.");
        }
        System.out.flush();
        String solution = baos.toString();
        quesToSol.addProperty(question, solution);
      }
      info.addProperty(topic, gson.toJson(quesToSol));
    }

    System.setOut(old);

    System.out.println(info);

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(OUTPUT_FILE))) {
      writer.write(info.toString());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 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();
   }
 }
Example #18
0
 private static void redirectOutMessage() {
   PrintStream ps = null;
   try {
     ps = new PrintStream(new BufferedOutputStream(new FileOutputStream("jdb.out.txt")), true);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
   System.setOut(ps);
 }
 public Inference() {
   PrintStream out = null;
   try {
     out = new PrintStream(new FileOutputStream("output_1.txt"));
   } catch (FileNotFoundException e1) {
     e1.printStackTrace();
   }
   System.setOut(out);
 }
Example #20
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());
 }
 public String runApp(String[] args, String input) throws Exception {
   // Save normal System.in and System.out
   InputStream sysin = System.in;
   PrintStream sysout = System.out;
   // Replace System.in with input text
   if (input == null) {
     input = "";
   }
   System.setIn(new ByteArrayInputStream(input.getBytes("UTF-8")));
   // Replace System.out with OutputStream we can capture
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   System.setOut(new PrintStream(out));
   // Run the app with the List of arguments
   App.main(args);
   // Replace normal System.in and System.out
   System.setIn(sysin);
   System.setOut(sysout);
   // Return the captured output
   return out.toString("UTF-8").trim();
 }
  /**
   * Acquires output stream for logging tests.
   *
   * @return Junit out print stream.
   */
  public static synchronized GridTestPrintStream acquireOut() {
    // Lazy initialization is required here to ensure that parent
    // thread group is picked off correctly by implementation.
    if (testOut == null) testOut = new GridTestPrintStream(sysOut);

    if (outCnt == 0) System.setOut(testOut);

    outCnt++;

    return testOut;
  }
Example #23
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();
    }
  }
Example #24
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;
  }
Example #25
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) {
    }
  }
Example #26
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);
   }
 }
Example #27
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;
     }
   }
 }
  @Test
  public void testSomething() throws FileNotFoundException, UnsupportedEncodingException {
    DefaultResultFormater defaultResultFormater = new DefaultResultFormater();
    defaultResultFormater.AddSuiteResult(suiteResult);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String expectedString =
        "[anonymous]\r\n"
            + "Tests executed:3\r\n"
            + "Tests failed:1\r\n"
            + "\r\n"
            + "{anonymous}\r\n"
            + "0: <open> url='http://google.com'\r\n"
            + "1: <open> url='http://google.com'\r\n\r\n\r\n\n";

    PrintStream out = new PrintStream(output);
    PrintStream backUp = System.out;
    System.setOut(out);
    defaultResultFormater.Process();
    System.setOut(backUp);

    String outputString = output.toString("UTF8");
    assertEquals(expectedString, outputString);
  }
Example #29
0
 Quest() {
   @SuppressWarnings({"UnusedDeclaration"})
   String id = getClass().getName().toLowerCase();
   //noinspection EmptyTryBlock
   try {
     System.setIn(new FileInputStream(id + ".in"));
     System.setOut(new PrintStream(new FileOutputStream(id + ".out")));
     //			System.setIn(new FileInputStream("input.txt"));
     //			System.setOut(new PrintStream(new FileOutputStream("output.txt")));
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   in = new InputReader(System.in);
   out = new PrintWriter(System.out);
 }
Example #30
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));
  }