Exemplo n.º 1
1
  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());
      }
    }
  }
Exemplo n.º 2
0
  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();
  }
Exemplo n.º 3
0
 /** 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);
   }
 }
Exemplo n.º 4
0
 @SuppressWarnings("rawtypes")
 private void cleanup(GantResult result, GantBinding binding) {
   if (result != null) {
     Class cls = GantMetaClass.class;
     try {
       Field methodsInvoked = cls.getDeclaredField("methodsInvoked");
       methodsInvoked.setAccessible(true);
       Set methodsInvokedSet = (Set) methodsInvoked.get(cls);
       if (methodsInvokedSet != null) {
         methodsInvokedSet.clear();
       }
     } catch (NoSuchFieldException e) {
       // ignore
     } catch (IllegalAccessException e) {
       // ignore
     }
   }
   System.setIn(originalIn);
   System.setOut(originalOut);
   GrailsPluginUtils.clearCaches();
   Map variables = binding.getVariables();
   Object pluginsSettingsObject = variables.get("pluginsSettings");
   if (pluginsSettingsObject instanceof PluginBuildSettings) {
     ((PluginBuildSettings) pluginsSettingsObject).clearCache();
   }
   GroovySystem.getMetaClassRegistry().removeMetaClass(GantBinding.class);
   GroovySystem.getMetaClassRegistry().removeMetaClass(Gant.class);
 }
Exemplo n.º 5
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();
   }
 }
Exemplo n.º 6
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();
   }
 }
 public static void resetStream() {
   if (stdin != null && stdout != null) {
     in = null;
     out = null;
     System.setIn(stdin);
     System.setOut(stdout);
   }
 }
Exemplo n.º 8
0
Arquivo: vans.java Projeto: 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();
 }
 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();
   }
 }
 public Inference() {
   PrintStream out = null;
   try {
     out = new PrintStream(new FileOutputStream("output_1.txt"));
   } catch (FileNotFoundException e1) {
     e1.printStackTrace();
   }
   System.setOut(out);
 }
Exemplo n.º 11
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);
 }
Exemplo n.º 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());
 }
Exemplo n.º 13
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);
   }
 }
Exemplo n.º 14
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) {
    }
  }
Exemplo n.º 15
0
 public static void redirectStream() throws Exception {
   if (file != null) {
     stdin = System.in;
     stdout = System.out;
     if (!STDINPUT) {
       in = new FileInputStream(file + ".in");
       System.setIn(in);
     }
     if (!STDOUT) {
       out = new PrintStream(new FileOutputStream(file + ".out"));
       System.setOut(out);
     }
   }
 }
  private InterpreterResult interpret(String[] commands, InterpreterContext context) {
    boolean isSuccess = true;
    totalCommands = commands.length;
    completedCommands = 0;

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

    System.setOut(ps);

    for (String command : commands) {
      int commandResuld = 1;
      String[] args = splitAndRemoveEmpty(command, " ");
      if (args.length > 0 && args[0].equals("help")) {
        System.out.println(getCommandList());
      } else {
        commandResuld = tfs.run(args);
      }
      if (commandResuld != 0) {
        isSuccess = false;
        break;
      } else {
        completedCommands += 1;
      }
      System.out.println();
    }

    System.out.flush();
    System.setOut(old);

    if (isSuccess) {
      return new InterpreterResult(Code.SUCCESS, baos.toString());
    } else {
      return new InterpreterResult(Code.ERROR, baos.toString());
    }
  }
Exemplo n.º 17
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));
  }
Exemplo n.º 18
0
 public static void main(String[] args) {
   botsDirecotry.mkdir();
   pluginsDirecotry.mkdir();
   logger.info("Setting up");
   EventManager.addListener(new ChatListener());
   System.setOut(new PrintStream(new LoggingStream(LogManager.getLogger("STDOUT"), Level.INFO)));
   System.setErr(new PrintStream(new LoggingStream(LogManager.getLogger("STDERR"), Level.ERROR)));
   loadBots();
   startBots();
   if (BOTS.size() == 0) {
     logger.error("No bots started! Stopping...");
     return;
   }
   startPlugins();
   logger.info("Setup finished");
 }
Exemplo n.º 19
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();
  }
  public static void ChineseSegment(String fullName, String segName) throws Exception {

    System.setOut(new PrintStream(new FileOutputStream(new File(segName))));
    String filename = fullName;

    // setting property
    Properties props = new Properties();
    props.setProperty(
        "sighanCorporaDict", "C:/Users/Xin/Documents/NetBeansProjects/BleuTranslator/data");
    props.setProperty(
        "serDictionary",
        "C:/Users/Xin/Documents/NetBeansProjects/BleuTranslator/data/dict-chris6.ser.gz");
    props.setProperty("testFile", filename);
    props.setProperty("inputEncoding", "UTF-8");
    props.setProperty("sighanPostProcessing", "true");

    CRFClassifier<CoreLabel> segmenter = new CRFClassifier<CoreLabel>(props);
    segmenter.loadClassifierNoExceptions(
        "C:/Users/Xin/Documents/NetBeansProjects/BleuTranslator/data/ctb.gz", props);
    segmenter.classifyAndWriteAnswers(filename);
  }
Exemplo n.º 21
0
  // Static method that returns sorted map
  static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> sortByVal(
      Map<K, V> map) // SortedSet provides total ordering on its elements
      {
    SortedSet<Map.Entry<K, V>> sortedEntries =
        new TreeSet<
            Map.Entry<
                K,
                V>> // TreeSet is a NavigableSet based on TreeMap; ordered by following Comparator
        (
            new Comparator<
                Map.Entry<K, V>>() // Implement new Comparator to compare values of the map
            {
              @Override
              public int compare(
                  Map.Entry<K, V> element1,
                  Map.Entry<K, V>
                      element2) // Override to compare element in Map to other mapped elements
                  {
                int val = element1.getValue().compareTo(element2.getValue());
                return val != 0 ? val : 1; // If elements are not equal; 0 else; 1
              }
            });
    sortedEntries.addAll(map.entrySet()); // Add all sorted elements to sortedEntries

    try // Where we write the sorted Entries to a file
    {
      PrintStream output =
          new PrintStream(new File("/Users/Smatlock/output.txt")); // Arbitrary file name
      System.setOut(output);
      output.print(sortedEntries);
    } catch (FileNotFoundException fx) {
      System.out.println(fx);
    }

    return sortedEntries;
  }
Exemplo n.º 22
0
  public static void main(String[] args) {
    // 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(defaultSliderPosition);
          }
        });
    // 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+r or Cmd+r -> compile/run
    bind(KeyEvent.VK_R);

    // Ctrl+k or Cmd+k -> kill JVM
    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); // Rebound to options menu for now
    bind(KeyEvent.VK_P);

    // Ctrl+h or Cmd+h -> help menu
    bind(KeyEvent.VK_SLASH);

    // 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;

    // Options initial values
    defaultSliderPosition = .8;

    // 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);
  }
  public InterpreterResult interpret(String[] lines, InterpreterContext context) {
    final IMain imain = flinkIloop.intp();

    String[] linesToRun = new String[lines.length + 1];
    for (int i = 0; i < lines.length; i++) {
      linesToRun[i] = lines[i];
    }
    linesToRun[lines.length] = "print(\"\")";

    System.setOut(new PrintStream(out));
    out.reset();
    Code r = null;

    String incomplete = "";
    boolean inComment = false;

    for (int l = 0; l < linesToRun.length; l++) {
      final String s = linesToRun[l];
      // check if next line starts with "." (but not ".." or "./") it is treated as an invocation
      if (l + 1 < linesToRun.length) {
        String nextLine = linesToRun[l + 1].trim();
        boolean continuation = false;
        if (nextLine.isEmpty()
            || nextLine.startsWith("//") // skip empty line or comment
            || nextLine.startsWith("}")
            || nextLine.startsWith("object")) { // include "} object" for Scala companion object
          continuation = true;
        } else if (!inComment && nextLine.startsWith("/*")) {
          inComment = true;
          continuation = true;
        } else if (inComment && nextLine.lastIndexOf("*/") >= 0) {
          inComment = false;
          continuation = true;
        } else if (nextLine.length() > 1
            && nextLine.charAt(0) == '.'
            && nextLine.charAt(1) != '.' // ".."
            && nextLine.charAt(1) != '/') { // "./"
          continuation = true;
        } else if (inComment) {
          continuation = true;
        }
        if (continuation) {
          incomplete += s + "\n";
          continue;
        }
      }

      final String currentCommand = incomplete;

      scala.tools.nsc.interpreter.Results.Result res = null;
      try {
        res =
            Console.withOut(
                System.out,
                new AbstractFunction0<Results.Result>() {
                  @Override
                  public Results.Result apply() {
                    return imain.interpret(currentCommand + s);
                  }
                });
      } catch (Exception e) {
        logger.info("Interpreter exception", e);
        return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e));
      }

      r = getResultCode(res);

      if (r == Code.ERROR) {
        return new InterpreterResult(r, out.toString());
      } else if (r == Code.INCOMPLETE) {
        incomplete += s + "\n";
      } else {
        incomplete = "";
      }
    }

    if (r == Code.INCOMPLETE) {
      return new InterpreterResult(r, "Incomplete expression");
    } else {
      return new InterpreterResult(r, out.toString());
    }
  }
Exemplo n.º 24
0
  void run() throws Exception {
    System.setOut(new PrintStream(new FileOutputStream("tmp.out")));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 1 << 13);
    int N = Integer.parseInt(br.readLine());
    int[] len =
        new int[] {
          64, 32, 16, 8, 4, 2, 1, 96, 48, 24, 12, 6, 3, 112, 56, 28, 14, 7, 120, 60, 30, 15, 124,
          62, 31, 126, 63, 127
        };
    String[] onpu =
        new String[] {
          "R1",
          "R2",
          "R4",
          "R8",
          "R16",
          "R32",
          "R64",
          "R1.",
          "R2.",
          "R4.",
          "R8.",
          "R16.",
          "R32.",
          "R1..",
          "R2..",
          "R4..",
          "R8..",
          "R16..",
          "R1...",
          "R2...",
          "R4...",
          "R8...",
          "R1....",
          "R2....",
          "R4....",
          "R1.....",
          "R2.....",
          "R1......"
        };
    String[] dp = new String[max];
    dp[0] = "R1.A";
    //        debug(dp[0]);
    for (int i = 1; i < max; i++) {
      String ns = null;
      for (int j = 0; j < onpu.length; j++) {
        int ni = i - len[j];
        if (ni >= 0) {
          String s1 = dp[ni] + onpu[j];
          if (ns == null || isleast(s1, ns)) {
            ns = s1;
          }
        }
      }
      for (int j = 0; j < onpu.length; j++) {
        int ni = i - len[j];
        if (ni >= 0) {
          String s1 = onpu[j] + dp[ni];
          if (isleast(s1, ns)) {
            ns = s1;
          }
        }
      }
      dp[i] = ns;
    }

    //        debug(dp);

    for (int n = 0; n < N; n++) {
      String[] rests = br.readLine().split("R");
      int[] dots = new int[rests.length - 1];
      for (int i = 1; i < rests.length; i++)
        for (int j = rests[i].length() - 1; j >= 0 && rests[i].charAt(j) == '.'; j--) dots[i - 1]++;
      //            debug(rests, dots);
      int[] nums = new int[rests.length - 1];
      for (int i = 1; i < rests.length; i++)
        nums[i - 1] = Integer.parseInt((rests[i].split("\\."))[0]);
      int sum = 0;
      for (int i = 0; i < nums.length; i++) {
        sum += 64 / nums[i];
        sum += (64 / nums[i]) - ((64 / nums[i]) >> dots[i]);
      }
      //            debug(sum);
      int mod = sum;

      StringBuffer f = new StringBuffer("");
      for (; mod >= max; mod -= 192) {
        f.append("R1.R1.");
      }
      //            debug(rests, sum, mod, max);
      String res = dp[mod].replace("R1.A", f.toString());
      System.out.println(res);
    }
  }
Exemplo n.º 25
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());
  }
Exemplo n.º 26
0
    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;
      }
    }
Exemplo n.º 27
0
 public UServerManager() {
   try {
     ULogoWindow logow = new ULogoWindow();
     logow.setVisible(true);
     Thread.sleep(2500);
     logow.dispose();
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   fParam.setConnectionType(UParameters.CONNECTION_TYPE_NETWORK);
   fParamDialog = new UServerManagerParamDialog();
   fParamDialog.setLocationRelativeTo((Frame) null);
   fParamDialog.setVisible(true);
   if (!fParamDialog.getStatus()) {
     System.exit(0);
     // 以下の部分はサーバの初期化による出力を拾えないための方策.
     // 非常にまずいが仕方ない.標準出力タブは必ず入れる.
   }
   System.setOut(UParameters.fPrintStream);
   fUpdateTimer = new javax.swing.Timer(fInterval * 1000, this);
   fUpdateTimer.setInitialDelay(0);
   fServer =
       new UMartNetwork(
           fParam.getMemberLog(),
           fParam.getPriceInfoDB(),
           fParam.getStartPoint(),
           fParam.getSeed(),
           fParam.getDays(),
           fParam.getBoardPerDay(),
           fParamNet.getPort());
   if (fParam.isLogCreate()) {
     try {
       fServer.initLog();
     } catch (IOException ioex) {
       JOptionPane.showMessageDialog(
           null,
           fRb.getString("ERROR_CANNOT_CREATE_LOGS"),
           fRb.getString("ERROR_DIALOG_TITLE"),
           JOptionPane.ERROR_MESSAGE);
       System.exit(5);
     } catch (Exception ex) {
       StringWriter sw = new StringWriter();
       PrintWriter pw = new PrintWriter(sw);
       ex.printStackTrace(pw);
       JOptionPane.showMessageDialog(
           null,
           fRb.getString("ERROR_FATAL") + "\n" + sw.toString(),
           fRb.getString("ERROR_DIALOG_TITLE"),
           JOptionPane.ERROR_MESSAGE);
       System.exit(5);
     }
   }
   fServer.startLoginManager();
   initAgents(fParam.getMachineAgentArray());
   fGui = new UServerManagerMainWindow(this, fParam.getTabs());
   fParam.setMainComponet(fGui);
   fGui.setTimer(fUpdateTimer);
   fGui.mainImpl();
   ActionListener guiUpdater =
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           fGui.gUpdate();
         }
       };
   fGuiUpdateTimer = new javax.swing.Timer(TIMER_INTERVAL * 1000, guiUpdater);
   fGuiUpdateTimer.start();
   // 1日目の1回目の注文期間に進めておく
   fUpdateTimer.setRepeats(false);
   fUpdateTimer.start();
 }
Exemplo n.º 28
0
 @After
 public void cleanUpStreams() {
   System.setOut(null);
   System.setErr(null);
 }
Exemplo n.º 29
0
  /**
   * Executes the requested Grails target. The "targetName" must match a known Grails script
   * provided by grails-scripts.
   *
   * @param targetName The name of the Grails target to execute.
   * @param args String of arguments to be passed to the executed Grails target.
   * @throws MojoExecutionException if an error occurs while attempting to execute the target.
   */
  protected void runGrails(final String targetName, String args) throws MojoExecutionException {
    if (((lastArgs != null && lastArgs.equals(args)) || (lastArgs == null && args == null))
        && lastTargetName != null
        && lastTargetName.equals(targetName)) return;

    lastArgs = args;
    lastTargetName = targetName;

    if (!alreadyLoaderClasspathForArtifact()) doOncePerArtifact();
    else if (targetName.equals("War")) resolveClasspath(); // we have to get rid of the test rubbish

    getLog()
        .info(
            "Grails target: "
                + targetName
                + " raw args:"
                + args
                + " (pom says Grails Version is "
                + grailsVersion
                + ")");

    InputStream currentIn = System.in;
    PrintStream currentOutput = System.out;

    try {
      RootLoader rootLoader = new RootLoader(addBinaryPluginWorkaround(classpath));

      // see if log4j is there and if so, initialize it
      try {
        Class cls = rootLoader.loadClass("org.springframework.util.Log4jConfigurer");
        invokeStaticMethod(
            cls, "initLogging", new Object[] {"classpath:grails-maven/log4j.properties"});
      } catch (Exception ex) {
        getLog().info("No log4j available, good!");
      }

      try {
        final DecentGrailsLauncher launcher =
            new DecentGrailsLauncher(rootLoader, grailsHomePath, basedir.getAbsolutePath());
        launcher.setPlainOutput(true);

        /**
         * this collects the different dependency levels (compile, runtime, test) and puts them into
         * the correct arrays to pass through to the Grails script launcher. If using Maven, you
         * should *never* see an Ivy message and if you do, immediately stop your build, figure out
         * the incorrect dependency, delete the ~/.ivy2 directory and try again.
         */
        Field settingsField = launcher.getClass().getDeclaredField("settings");
        settingsField.setAccessible(true);

        configureBuildSettings(
            launcher,
            resolvedArtifacts,
            settingsField,
            rootLoader.loadClass("grails.util.BuildSettings"),
            args);

        syncAppVersion();

        installGrailsPlugins(
            pluginDirectories,
            launcher,
            settingsField,
            rootLoader.loadClass("grails.util.AbstractBuildSettings"));

        // If the command is running in non-interactive mode, we
        // need to pass on the relevant argument.
        if (this.nonInteractive) {
          args = (args != null) ? "--non-interactive " + args : "--non-interactive ";
        }

        // consuming the standard output after execution via Maven.
        args = (args != null) ? "--plain-output " + args : "--plain-output";
        args = (args != null) ? "--stacktrace " + args : "--stacktrace";
        args = (args != null) ? "--verboseCompile " + args : "--verboseCompile";

        if (env == null) System.clearProperty("grails.env");
        else System.setProperty("grails.env", env);

        getLog()
            .info(
                "grails -Dgrails.env="
                    + (env == null ? "dev" : env)
                    + " "
                    + targetName.toLowerCase()
                    + " "
                    + args);
        int retval;

        if ("true".equals(System.getProperty("print.grails.settings"))
            || "ideaprintprojectsettings".equalsIgnoreCase(targetName)) {
          printIntellijIDEASettings(launcher, settingsField, pluginArtifacts);
        } else {

          if ("interactive".equals(targetName)) retval = launcher.launch("", "", env);
          else retval = launcher.launch(targetName, args, env);

          if (retval != 0) {
            throw new MojoExecutionException("Grails returned non-zero value: " + retval);
          }
        }
      } catch (final MojoExecutionException ex) {
        // Simply rethrow it.
        throw ex;
      } catch (final Exception ex) {
        getLog().error(ex);

        throw new MojoExecutionException("Unable to start Grails", ex);
      }

      rootLoader = null;
    } catch (MalformedURLException mfe) {
      throw new MojoExecutionException("Unable to start Grails", mfe);
    } finally {
      System.setIn(currentIn);
      System.setOut(currentOutput);
    }

    System.gc(); // try and help with memory issues
  }
Exemplo n.º 30
0
 private void initSysOutRecorder() {
   out = new ByteArrayOutputStream();
   System.setOut(new PrintStream(out));
 }