Example usage for java.lang System setErr

List of usage examples for java.lang System setErr

Introduction

In this page you can find the example usage for java.lang System setErr.

Prototype

public static void setErr(PrintStream err) 

Source Link

Document

Reassigns the "standard" error output stream.

Usage

From source file:com.qawaa.gui.PointAnalysisGUI.java

/**
* Auto-generated main method to display this JFrame
*/// w w w  . j ava 2  s  . c  om
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            PointAnalysisGUI inst = new PointAnalysisGUI();
            inst.setLocationRelativeTo(null);
            inst.setVisible(true);
            inst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JFrame.setDefaultLookAndFeelDecorated(true);
            FlowLayout flowLayout = new FlowLayout();
            flowLayout.setAlignment(FlowLayout.LEFT);
            flowLayout.setAlignOnBaseline(true);
            inst.setTitle(PROGRAM_NAME + " [" + PROGRAM_VERSION + "] " + " - " + DefaultMessage.SOFT_NAME
                    + " - " + DefaultMessage.COMPANY_NAME);
            {
                consoleScrollPane = new JScrollPane();
                inst.getContentPane().add(consoleScrollPane, BorderLayout.CENTER);
                {
                    consolePane = new JEditorPane();
                    consoleScrollPane.setViewportView(consolePane);
                    consolePane.setText("");
                    setConsoleRight();
                    jConsole = new JConsole(System.out, consolePane);
                    System.setOut(jConsole);
                    System.setErr(jConsole);
                    consolePane.setEditable(false);
                    consolePane.addMouseListener(new MouseAdapter() {
                        /* (non-Javadoc)
                         * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent)
                         */
                        public void mouseReleased(MouseEvent e) {
                            if (e.getButton() == MouseEvent.BUTTON3) {
                                consolePane.add(consoleRight);
                                consoleRight.show(e.getComponent(), e.getX(), e.getY());
                            }
                        }
                    });
                }
            }
            {
                infoPanel = new JPanel();
                inst.getContentPane().add(infoPanel, BorderLayout.SOUTH);
                infoPanel.setBorder(new LineBorder(new Color(0, 0, 0), 1, false));
                infoPanel.setPreferredSize(new Dimension(784, 30));
                infoPanel.setLayout(flowLayout);
                {
                    {
                        statusbar_count = new JTextPane();
                        infoPanel.add(statusbar_count);
                        statusbar_count
                                .setText(CONTEXT.getMessage("point.statusbar.count", null, Locale.CHINA));
                        statusbar_count.setBackground(null);
                        statusbar_count.setEditable(false);
                    }
                    {
                        statusbar_count_value = new JTextPane();
                        infoPanel.add(statusbar_count_value);
                        statusbar_count_value.setText(String.valueOf(SCAN_COUNT));
                        statusbar_count_value.setBackground(null);
                        statusbar_count_value.setEditable(false);
                        statusbar_count_value.setEnabled(false);
                    }
                    {
                        programPID = new JTextPane();
                        infoPanel.add(programPID);
                        programPID.setText("PID:");
                        programPID.setBackground(null);
                        programPID.setEditable(false);
                    }
                    {
                        programPID_value = new JTextPane();
                        infoPanel.add(programPID_value);
                        programPID_value.setText(JvmPid.getPID());
                        programPID_value.setBackground(null);
                        programPID_value.setEditable(false);
                        programPID_value.setEnabled(false);
                    }
                    {
                        memory = new JTextPane();
                        infoPanel.add(memory);
                        memory.setText(CONTEXT.getMessage("gobal.gui.memory", null, Locale.CHINA));
                        memory.setBackground(null);
                        memory.setEditable(false);
                    }
                    {
                        memory_value = new JTextPane();
                        infoPanel.add(memory_value);
                        memory_value.setText("0KB");
                        memory_value.setBackground(null);
                        memory_value.setEditable(false);
                        memory_value.setEnabled(false);
                        MemoryListener memory = new MemoryListener(memory_value);
                        memory.start();
                    }
                    {
                        runtime = new JTextPane();
                        infoPanel.add(runtime);
                        runtime.setText(CONTEXT.getMessage("gobal.gui.runtime", null, Locale.CHINA));
                        runtime.setBackground(null);
                        runtime.setEditable(false);
                    }
                    {
                        runtime_value = new JTextPane();
                        infoPanel.add(runtime_value);
                        runtime_value.setText("NULL");
                        runtime_value.setBackground(null);
                        runtime_value.setEditable(false);
                        runtime_value.setEnabled(false);
                    }
                }
            }
            {
                shortcut = new JPanel();
                inst.getContentPane().add(shortcut, BorderLayout.NORTH);
                shortcut.setSize(784, 35);
                shortcut.setPreferredSize(new Dimension(784, 35));
                shortcut.setBorder(new LineBorder(new Color(0, 0, 0), 1, false));
                shortcut.setLayout(new BorderLayout());
                {
                    eventText = new JTextPane();
                    shortcut.add(eventText, BorderLayout.WEST);
                    eventText.setText(CONTEXT.getMessage("point.event.name", null, Locale.CHINA) + ": ");
                    eventText.setEditable(false);
                    eventText.setEnabled(true);
                    eventText.setBackground(null);
                    eventText.setCaretColor(new Color(0, 0, 0));
                }
                {
                    eventTextField = new JTextField();
                    shortcut.add(eventTextField, BorderLayout.CENTER);
                    eventTextField.setSize(500, 25);
                    eventTextField.setText("");
                    eventTextField.setPreferredSize(new Dimension(500, 25));
                    eventTextField.setEditable(false);
                }
                {
                    submit = new JButton();
                    shortcut.add(submit, BorderLayout.EAST);
                    submit.setText(CONTEXT.getMessage("gobal.gui.button.run", null, Locale.CHINA));
                    submit.setSize(new Dimension(75, 25));
                    submit.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                submitActionPerformed(evt);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    });

}

From source file:com.qawaa.gui.EventWebScanGUI.java

/**
* Auto-generated main method to display this JFrame
*//* w  ww. j  a v  a 2s.c om*/
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            EventWebScanGUI inst = new EventWebScanGUI();
            inst.setLocationRelativeTo(null);
            inst.setVisible(true);
            inst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JFrame.setDefaultLookAndFeelDecorated(true);
            FlowLayout flowLayout = new FlowLayout();
            flowLayout.setAlignment(FlowLayout.LEFT);
            flowLayout.setAlignOnBaseline(true);
            inst.setTitle(PROGRAM_NAME + " [" + PROGRAM_VERSION + "] " + " - " + DefaultMessage.SOFT_NAME
                    + " - " + DefaultMessage.COMPANY_NAME);
            {
                consoleScrollPane = new JScrollPane();
                inst.getContentPane().add(consoleScrollPane, BorderLayout.CENTER);
                {
                    consolePane = new JEditorPane();
                    consoleScrollPane.setViewportView(consolePane);
                    consolePane.setText("");
                    setConsoleRight();
                    jConsole = new JConsole(System.out, consolePane);
                    System.setOut(jConsole);
                    System.setErr(jConsole);
                    consolePane.setEditable(false);
                    consolePane.addMouseListener(new MouseAdapter() {
                        /* (non-Javadoc)
                         * @see java.awt.event.MouseAdapter#mouseReleased(java.awt.event.MouseEvent)
                         */
                        public void mouseReleased(MouseEvent e) {
                            if (e.getButton() == MouseEvent.BUTTON3) {
                                consolePane.add(consoleRight);
                                consoleRight.show(e.getComponent(), e.getX(), e.getY());
                            }
                        }
                    });
                }
            }
            {
                infoPanel = new JPanel();
                inst.getContentPane().add(infoPanel, BorderLayout.SOUTH);
                infoPanel.setBorder(new LineBorder(new Color(0, 0, 0), 1, false));
                infoPanel.setPreferredSize(new Dimension(784, 30));
                infoPanel.setLayout(flowLayout);
                {
                    {
                        statusbar_count = new JTextPane();
                        infoPanel.add(statusbar_count);
                        statusbar_count.setText(
                                CONTEXT.getMessage("event.web.scan.statusbar.count", null, Locale.CHINA));
                        statusbar_count.setBackground(null);
                        statusbar_count.setEditable(false);
                    }
                    {
                        statusbar_count_value = new JTextPane();
                        infoPanel.add(statusbar_count_value);
                        statusbar_count_value.setText(String.valueOf(SCAN_COUNT));
                        statusbar_count_value.setBackground(null);
                        statusbar_count_value.setEditable(false);
                        statusbar_count_value.setEnabled(false);
                    }
                    {
                        programPID = new JTextPane();
                        infoPanel.add(programPID);
                        programPID.setText("PID:");
                        programPID.setBackground(null);
                        programPID.setEditable(false);
                    }
                    {
                        programPID_value = new JTextPane();
                        infoPanel.add(programPID_value);
                        programPID_value.setText(JvmPid.getPID());
                        programPID_value.setBackground(null);
                        programPID_value.setEditable(false);
                        programPID_value.setEnabled(false);
                    }
                    {
                        memory = new JTextPane();
                        infoPanel.add(memory);
                        memory.setText(CONTEXT.getMessage("gobal.gui.memory", null, Locale.CHINA));
                        memory.setBackground(null);
                        memory.setEditable(false);
                    }
                    {
                        memory_value = new JTextPane();
                        infoPanel.add(memory_value);
                        memory_value.setText("0KB");
                        memory_value.setBackground(null);
                        memory_value.setEditable(false);
                        memory_value.setEnabled(false);
                        MemoryListener memory = new MemoryListener(memory_value);
                        memory.start();
                    }
                    {
                        runtime = new JTextPane();
                        infoPanel.add(runtime);
                        runtime.setText(CONTEXT.getMessage("gobal.gui.runtime", null, Locale.CHINA));
                        runtime.setBackground(null);
                        runtime.setEditable(false);
                    }
                    {
                        runtime_value = new JTextPane();
                        infoPanel.add(runtime_value);
                        runtime_value.setText("NULL");
                        runtime_value.setBackground(null);
                        runtime_value.setEditable(false);
                        runtime_value.setEnabled(false);
                    }
                }
            }
            {
                shortcut = new JPanel();
                inst.getContentPane().add(shortcut, BorderLayout.NORTH);
                shortcut.setSize(784, 35);
                shortcut.setPreferredSize(new Dimension(784, 35));
                shortcut.setBorder(new LineBorder(new Color(0, 0, 0), 1, false));
                shortcut.setLayout(new BorderLayout());
                {
                    eventText = new JTextPane();
                    shortcut.add(eventText, BorderLayout.WEST);
                    eventText.setText(CONTEXT.getMessage("event.web.scan.name", null, Locale.CHINA) + ": ");
                    eventText.setEditable(false);
                    eventText.setEnabled(true);
                    eventText.setBackground(null);
                    eventText.setCaretColor(new Color(0, 0, 0));
                }
                {
                    eventTextField = new JTextField();
                    shortcut.add(eventTextField, BorderLayout.CENTER);
                    eventTextField.setSize(500, 25);
                    eventTextField.setText("");
                    eventTextField.setPreferredSize(new Dimension(500, 25));
                    eventTextField.setEditable(false);
                }
                {
                    submit = new JButton();
                    shortcut.add(submit, BorderLayout.EAST);
                    submit.setText(CONTEXT.getMessage("gobal.gui.button.run", null, Locale.CHINA));
                    submit.setSize(new Dimension(75, 25));
                    submit.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                submitActionPerformed(evt);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    });

}

From source file:parquet.tools.Main.java

public static void main(String[] args) {
    Main.out = System.out;/*w w  w  . jav a 2 s.  c o m*/
    Main.err = System.err;

    System.setOut(new PrintStream(new OutputStream() {
        @Override
        public void write(int b) throws IOException {
        }

        @Override
        public void write(byte[] b) throws IOException {
        }

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

        @Override
        public void flush() throws IOException {
        }

        @Override
        public void close() throws IOException {
        }
    }));

    System.setErr(new PrintStream(new OutputStream() {
        @Override
        public void write(int b) throws IOException {
        }

        @Override
        public void write(byte[] b) throws IOException {
        }

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

        @Override
        public void flush() throws IOException {
        }

        @Override
        public void close() throws IOException {
        }
    }));

    if (args.length == 0) {
        die("No command specified", true, null, null);
    }

    String name = args[0];
    if ("-h".equals(name) || "--help".equals(name)) {
        showUsage();
        System.exit(0);
    }

    Command command = Registry.getCommandByName(name);
    if (command == null) {
        die("Unknown command: " + name, true, null, null);
    }

    boolean debug = false;
    Options options = mergeOptions(OPTIONS, command.getOptions());
    try {
        String[] cargs = Arrays.copyOfRange(args, 1, args.length);

        Options opts = mergeOptions(OPTIONS, command.getOptions());
        boolean extra = command.supportsExtraArgs();

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(opts == null ? new Options() : opts, cargs, extra);
        if (cmd.hasOption('h')) {
            showUsage(name, command);
            System.exit(0);
        }

        if (cmd.hasOption("no-color")) {
            System.setProperty("DISABLE_COLORS", "true");
        }

        debug = cmd.hasOption("debug");

        command.execute(cmd);
    } catch (ParseException ex) {
        if (debug)
            ex.printStackTrace(Main.err);
        die("Invalid arguments: " + ex.getMessage(), true, name, command);
    } catch (Throwable th) {
        if (debug)
            th.printStackTrace(Main.err);
        die(th, false, name, command);
    }
}

From source file:org.apache.parquet.tools.Main.java

public static void main(String[] args) {
    Main.out = System.out;//from   w  w  w.j a  v  a  2 s .  c  o  m
    Main.err = System.err;

    PrintStream VoidStream = new PrintStream(new OutputStream() {
        @Override
        public void write(int b) throws IOException {
        }

        @Override
        public void write(byte[] b) throws IOException {
        }

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

        @Override
        public void flush() throws IOException {
        }

        @Override
        public void close() throws IOException {
        }
    });
    System.setOut(VoidStream);
    System.setErr(VoidStream);

    if (args.length == 0) {
        die("No command specified", true, null, null);
    }

    String name = args[0];
    if ("-h".equals(name) || "--help".equals(name)) {
        showUsage();
        System.exit(0);
    }

    Command command = Registry.getCommandByName(name);
    if (command == null) {
        die("Unknown command: " + name, true, null, null);
    }

    boolean debug = false;
    try {
        String[] cargs = Arrays.copyOfRange(args, 1, args.length);

        Options opts = mergeOptions(OPTIONS, command.getOptions());
        boolean extra = command.supportsExtraArgs();

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(opts == null ? new Options() : opts, cargs, extra);
        if (cmd.hasOption('h')) {
            showUsage(name, command);
            System.exit(0);
        }

        if (cmd.hasOption("no-color")) {
            System.setProperty("DISABLE_COLORS", "true");
        }

        debug = cmd.hasOption("debug");

        command.execute(cmd);
    } catch (ParseException ex) {
        if (debug)
            ex.printStackTrace(Main.err);
        die("Invalid arguments: " + ex.getMessage(), true, name, command);
    } catch (Throwable th) {
        if (debug)
            th.printStackTrace(Main.err);
        die(th, false, name, command);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.win32.Service.java

public static void main(String[] arg) {
    String opt;//from  w ww  .ja  v a2  s .  c o  m
    opt = System.getProperty("SERVICE_OUT");
    if (opt != null) {
        try {
            PrintStream stdout = new PrintStream(new FileOutputStream(opt));
            System.setOut(stdout);
        } catch (Exception e) {
            log.warn(LogSupport.EXCEPTION, e);
        }
    }

    opt = System.getProperty("SERVICE_ERR");
    if (opt != null) {
        try {
            PrintStream stderr = new PrintStream(new FileOutputStream(opt));
            System.setErr(stderr);
        } catch (Exception e) {
            log.warn(LogSupport.EXCEPTION, e);
        }
    }

    if (arg.length == 0)
        arg = new String[] { "etc/jetty.xml" };

    try {
        _configs = new Vector();
        for (int i = 0; i < arg.length; i++)
            _configs.add(arg[i]);
        createAll();
        startAll();
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }
}

From source file:com.shoddytcg.server.GameServer.java

/**
 * If you don't know what this method does, you clearly don't know enough Java to be working on this.
 * @param args/*ww  w .j  av  a2 s . c om*/
 */
public static void main(String[] args) {
    /*
     * Pipe errors to a file
     */
    try {
        PrintStream p = new PrintStream(new File("./errors.txt"));
        System.setErr(p);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
     * Server settings
     */
    Options options = new Options();
    options.addOption("s", "settings", true, "Can be low, medium, or high.");
    options.addOption("p", "players", true, "Sets the max number of players.");
    options.addOption("ng", "nogui", false, "Starts server in headless mode.");
    options.addOption("ar", "autorun", false, "Runs without asking a single question.");
    options.addOption("h", "help", false, "Shows this menu.");

    if (args.length > 0) {

        CommandLineParser parser = new GnuParser();
        try {
            // parse the command line arguments
            CommandLine line = parser.parse(options, args);

            /*
             * The following sets the server's settings based on the
             * computing ability of the server specified by the server owner.
             */
            if (line.hasOption("settings")) {
                String settings = line.getOptionValue("settings");
                if (settings.equalsIgnoreCase("low")) {
                    m_movementThreads = 4;
                } else if (settings.equalsIgnoreCase("medium")) {
                    m_movementThreads = 8;
                } else if (settings.equalsIgnoreCase("high")) {
                    m_movementThreads = 12;
                } else {
                    System.err.println("Server requires a settings parameter");
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("java GameServer [param] <args>", options);
                    System.exit(0);
                }
            } else {
                System.err.println("Server requires a settings parameter");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("java GameServer [param] <args>", options);
                System.exit(0);
            }

            if (line.hasOption("players")) {
                m_maxPlayers = Integer.parseInt(line.getOptionValue("players"));
                if (m_maxPlayers == 0 || m_maxPlayers == -1)
                    m_maxPlayers = 99999;
            } else {
                System.err.println("WARNING: No maximum player count provided. Will default to 500 players.");
                m_maxPlayers = 500;
            }

            if (line.hasOption("help")) {
                HelpFormatter formatter = new HelpFormatter();
                System.err.println("Server requires a settings parameter");
                formatter.printHelp("java GameServer [param] <args>", options);
            }

            /*
             * Create the server gui
             */
            @SuppressWarnings("unused")
            GameServer gs;
            if (line.hasOption("nogui")) {
                if (line.hasOption("autorun"))
                    gs = new GameServer(true);
                else
                    gs = new GameServer(false);
            } else {
                if (line.hasOption("autorun"))
                    System.out.println("autorun doesn't work with GUI");
                gs = new GameServer(false);
            }
        } catch (ParseException exp) {
            // oops, something went wrong
            System.err.println("Parsing failed.  Reason: " + exp.getMessage());
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java GameServer [param] <args>", options);
        }

    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        System.err.println("Server requires a settings parameter");
        formatter.printHelp("java GameServer [param] <args>", options);
    }
}

From source file:net.k3rnel.arena.server.GameServer.java

/**
 * If you don't know what this method does, you clearly don't know enough Java to be working on this.
 * @param args/*from  ww w  . j  av  a 2s. c  o  m*/
 */
public static void main(String[] args) {
    /*
     * Pipe errors to a file
     */
    try {
        PrintStream p = new PrintStream(new File("./errors.txt"));
        System.setErr(p);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /*
     * Server settings
     */
    Options options = new Options();
    options.addOption("s", "settings", true, "Can be low, medium, or high.");
    options.addOption("p", "players", true, "Sets the max number of players.");
    options.addOption("ng", "nogui", false, "Starts server in headless mode.");
    options.addOption("ar", "autorun", false, "Runs without asking a single question.");
    options.addOption("h", "help", false, "Shows this menu.");

    if (args.length > 0) {
        CommandLineParser parser = new GnuParser();
        try {
            // parse the command line arguments
            CommandLine line = parser.parse(options, args);

            /*
             * The following sets the server's settings based on the
             * computing ability of the server specified by the server owner.
             */
            if (line.hasOption("settings")) {
                String settings = line.getOptionValue("settings");
                if (settings.equalsIgnoreCase("low")) {
                    m_movementThreads = 4;
                } else if (settings.equalsIgnoreCase("medium")) {
                    m_movementThreads = 8;
                } else if (settings.equalsIgnoreCase("high")) {
                    m_movementThreads = 12;
                } else {
                    System.err.println("Server requires a settings parameter");
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.printHelp("java GameServer [param] <args>", options);
                    System.exit(0);
                }
            } else {
                System.err.println("Server requires a settings parameter");
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("java GameServer [param] <args>", options);
                System.exit(0);
            }

            if (line.hasOption("players")) {
                m_maxPlayers = Integer.parseInt(line.getOptionValue("players"));
                if (m_maxPlayers == 0 || m_maxPlayers == -1)
                    m_maxPlayers = 99999;
            } else {
                System.err.println("WARNING: No maximum player count provided. Will default to 500 players.");
                m_maxPlayers = 500;
            }

            if (line.hasOption("help")) {
                HelpFormatter formatter = new HelpFormatter();
                System.err.println("Server requires a settings parameter");
                formatter.printHelp("java GameServer [param] <args>", options);
            }

            /*
             * Create the server gui
             */
            @SuppressWarnings("unused")
            GameServer gs;
            if (line.hasOption("nogui")) {
                if (line.hasOption("autorun"))
                    gs = new GameServer(true);
                else
                    gs = new GameServer(false);
            } else {
                if (line.hasOption("autorun"))
                    System.out.println("autorun doesn't work with GUI");
                gs = new GameServer(false);
            }
        } catch (ParseException exp) {
            // oops, something went wrong
            System.err.println("Parsing failed.  Reason: " + exp.getMessage());
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java GameServer [param] <args>", options);
        }

    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        System.err.println("Server requires a settings parameter");
        formatter.printHelp("java GameServer [param] <args>", options);
    }
}

From source file:pt.ua.tm.neji.web.cli.WebMain.java

public static void main(String[] args) {

    // Set JSP to use Standard JavaC always
    System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("h", "help", false, "Print this usage information.");
    options.addOption("v", "verbose", false, "Verbose mode.");
    options.addOption("d", "dictionaires", true, "Folder that contains the dictionaries.");
    options.addOption("m", "models", true, "Folder that contains the ML models.");

    options.addOption("port", "port", true, "Server port.");
    options.addOption("c", "configuration", true, "Configuration properties file.");

    options.addOption("t", "threads", true,
            "Number of threads. By default, if more than one core is available, it is the number of cores minus 1.");

    CommandLine commandLine;// w ww  .j av  a  2s .  co  m
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments.", ex);
        return;
    }

    // Show help text
    if (commandLine.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(150, "./nejiWeb.sh " + USAGE, HEADER, options, FOOTER);
        return;
    }

    // Get threads
    int numThreads = Runtime.getRuntime().availableProcessors() - 1;
    numThreads = numThreads > 0 ? numThreads : 1;
    if (commandLine.hasOption('t')) {
        String threadsText = commandLine.getOptionValue('t');
        numThreads = Integer.parseInt(threadsText);
        if (numThreads <= 0 || numThreads > 32) {
            logger.error("Illegal number of threads. Must be between 1 and 32.");
            return;
        }
    }

    // Get port
    int port = 8010;
    if (commandLine.hasOption("port")) {
        String portString = commandLine.getOptionValue("port");
        port = Integer.parseInt(portString);
    }

    // Get configuration
    String configurationFile = null;
    Properties configurationProperties = null;
    if (commandLine.hasOption("configuration")) {
        configurationFile = commandLine.getOptionValue("configuration");
        try {
            configurationProperties = new Properties();
            configurationProperties.load(new FileInputStream(configurationFile));
        } catch (IOException e) {
            configurationProperties = null;
        }
    }
    if (configurationProperties != null && !configurationProperties.isEmpty()) {
        ServerConfiguration.initialize(configurationProperties);
    } else {
        ServerConfiguration.initialize();
    }

    // Set system proxy
    if (!ServerConfiguration.getInstance().getProxyURL().isEmpty()
            && !ServerConfiguration.getInstance().getProxyPort().isEmpty()) {
        System.setProperty("https.proxyHost", ServerConfiguration.getInstance().getProxyURL());
        System.setProperty("https.proxyPort", ServerConfiguration.getInstance().getProxyPort());
        System.setProperty("http.proxyHost", ServerConfiguration.getInstance().getProxyURL());
        System.setProperty("http.proxyPort", ServerConfiguration.getInstance().getProxyPort());

        if (!ServerConfiguration.getInstance().getProxyUsername().isEmpty()) {
            final String proxyUser = ServerConfiguration.getInstance().getProxyUsername();
            final String proxyPassword = ServerConfiguration.getInstance().getProxyPassword();
            System.setProperty("https.proxyUser", proxyUser);
            System.setProperty("https.proxyPassword", proxyPassword);
            System.setProperty("http.proxyUser", proxyUser);
            System.setProperty("http.proxyPassword", proxyPassword);
            Authenticator.setDefault(new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray());
                }
            });
        }
    }

    // Get verbose mode
    boolean verbose = commandLine.hasOption('v');
    Constants.verbose = verbose;

    if (Constants.verbose) {
        MalletLogger.getGlobal().setLevel(Level.INFO);
        // Redirect sout
        LoggingOutputStream los = new LoggingOutputStream(LoggerFactory.getLogger("stdout"), false);
        System.setOut(new PrintStream(los, true));

        // Redirect serr
        los = new LoggingOutputStream(LoggerFactory.getLogger("sterr"), true);
        System.setErr(new PrintStream(los, true));
    } else {
        MalletLogger.getGlobal().setLevel(Level.OFF);
    }

    // Get dictionaries folder
    String dictionariesFolder = null;
    if (commandLine.hasOption('d')) {
        dictionariesFolder = commandLine.getOptionValue('d');

        File test = new File(dictionariesFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified dictionaries path is not a folder or is not readable.");
            return;
        }
        dictionariesFolder = test.getAbsolutePath();
        dictionariesFolder += File.separator;
    }

    // Get models folder
    String modelsFolder = null;
    if (commandLine.hasOption('m')) {
        modelsFolder = commandLine.getOptionValue('m');

        File test = new File(modelsFolder);
        if (!test.isDirectory() || !test.canRead()) {
            logger.error("The specified models path is not a folder or is not readable.");
            return;
        }
        modelsFolder = test.getAbsolutePath();
        modelsFolder += File.separator;
    }

    // Redirect JUL to SLF4
    SLF4JBridgeHandler.removeHandlersForRootLogger();
    SLF4JBridgeHandler.install();

    // Output formats (All)
    List<OutputFormat> outputFormats = new ArrayList<>();
    outputFormats.add(OutputFormat.A1);
    outputFormats.add(OutputFormat.B64);
    outputFormats.add(OutputFormat.BC2);
    outputFormats.add(OutputFormat.BIOC);
    outputFormats.add(OutputFormat.CONLL);
    outputFormats.add(OutputFormat.JSON);
    outputFormats.add(OutputFormat.NEJI);
    outputFormats.add(OutputFormat.PIPE);
    outputFormats.add(OutputFormat.PIPEXT);
    outputFormats.add(OutputFormat.XML);

    // Context is built through a descriptor first, so that the pipeline can be validated before any processing
    ContextConfiguration descriptor = null;
    try {
        descriptor = new ContextConfiguration.Builder().withInputFormat(InputFormat.RAW) // HARDCODED
                .withOutputFormats(outputFormats).withParserTool(ParserTool.GDEP)
                .withParserLanguage(ParserLanguage.ENGLISH).withParserLevel(ParserLevel.CHUNKING).build();

    } catch (NejiException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    // Create resources dirs if they don't exist
    try {
        File dictionariesDir = new File(DICTIONARIES_PATH);
        File modelsDir = new File(MODELS_PATH);
        if (!dictionariesDir.exists()) {
            dictionariesDir.mkdirs();
            (new File(dictionariesDir, "_priority")).createNewFile();
        }
        if (!modelsDir.exists()) {
            modelsDir.mkdirs();
            (new File(modelsDir, "_priority")).createNewFile();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    // Contenxt
    Context context = new Context(descriptor, MODELS_PATH, DICTIONARIES_PATH);

    // Start server
    try {
        Server server = Server.getInstance();
        server.initialize(context, port, numThreads);

        server.start();
        logger.info("Server started at localhost:{}", port);
        logger.info("Press Cmd-C / Ctrl+C to shutdown the server...");

        server.join();

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.info("Shutting down the server...");
    }
}

From source file:ch.epfl.leb.sass.commandline.CommandLineInterface.java

/**
 * Shows help, launches the interpreter and executes scripts according to input args.
 * @param args input arguments/*w  ww  .j a  v  a2s.  c  o  m*/
 */
public static void main(String args[]) {
    // parse input arguments
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("Parsing of arguments failed. Reason: " + ex.getMessage());
        System.err.println("Use -help for usage.");
        System.exit(1);
    }

    // decide how do we make the interpreter available based on options
    Interpreter interpreter = null;
    // show help and exit
    if (line.hasOption("help")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar <jar-name>", options, true);
        System.exit(0);
        // launch interpreter inside current terminal
    } else if (line.hasOption("interpreter")) {
        // assign in, out and err streams to the interpreter
        interpreter = new Interpreter(new InputStreamReader(System.in), System.out, System.err, true);
        interpreter.setShowResults(true);
        // if a script was given, execute it before giving access to user
        if (line.hasOption("script")) {
            try {
                interpreter.source(line.getOptionValue("script"));
            } catch (IOException ex) {
                Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                        "IOException while executing shell script.", ex);
            } catch (EvalError ex) {
                Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                        "EvalError while executing shell script.", ex);
            }
        }
        // give access to user
        new Thread(interpreter).start();
        // only execute script and exit
    } else if (line.hasOption("script")) {
        interpreter = new Interpreter();
        try {
            interpreter.source(line.getOptionValue("script"));
            System.exit(0);
        } catch (IOException ex) {
            Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                    "IOException while executing shell script.", ex);
            System.exit(1);
        } catch (EvalError ex) {
            Logger.getLogger(BeanShellConsole.class.getName()).log(Level.SEVERE,
                    "EvalError while executing shell script.", ex);
            System.exit(1);
        }

        // Launches the RPC server with the model contained in the file whose
        // filename was passed by argument.
    } else if (line.hasOption("rpc_server")) {

        IJPluginModel model = new IJPluginModel();
        File file = new File(line.getOptionValue("rpc_server"));
        try {
            FileInputStream stream = new FileInputStream(file);
            model = IJPluginModel.read(stream);
        } catch (FileNotFoundException ex) {
            System.out.println("Error: " + file.getName() + " not found.");
            System.exit(1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // Check whether a port number was specified.
        if (line.hasOption("port")) {
            try {
                port = Integer.valueOf(line.getOptionValue("port"));
                System.out.println("Using port: " + String.valueOf(port));
            } catch (java.lang.NumberFormatException ex) {
                System.out.println("Error: the port number argument is not a number.");
                System.exit(1);
            }
        } else {
            System.out.println("No port number provided. Using default port: " + String.valueOf(port));
        }

        RPCServer server = new RPCServer(model, port);

        System.out.println("Starting RPC server...");
        server.serve();

    } else if (line.hasOption("port") & !line.hasOption("rpc_server")) {
        System.out.println("Error: Port number provided without requesting the RPC server. Exiting...");
        System.exit(1);

        // if System.console() returns null, it means we were launched by
        // double-clicking the .jar, so launch own BeanShellConsole
        // if System.console() returns null, it means we were launched by
        // double-clicking the .jar, so launch own ConsoleFrame
    } else if (System.console() == null) {
        BeanShellConsole cframe = new BeanShellConsole("SASS BeanShell Prompt");
        interpreter = cframe.getInterpreter();
        cframe.setVisible(true);
        System.setOut(cframe.getInterpreter().getOut());
        System.setErr(cframe.getInterpreter().getErr());
        new Thread(cframe.getInterpreter()).start();
        // otherwise, show help
    } else {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar <jar-name>", options, true);
        System.exit(0);
    }

    if (interpreter != null) {
        printWelcomeText(interpreter.getOut());
    }
}

From source file:eu.learnpad.simulator.mon.MainMonitoring.java

/**
 * Read the properties and init the connections to the enterprise service bus
 * //w  w  w. j  a  va  2 s  .com
 * @param is the systemSettings file
 */
public static void main(String[] args) {
    try {
        FileOutputStream fos = new FileOutputStream("glimpseLog.log");
        PrintStream ps = new PrintStream(fos);
        System.setErr(ps);

        if (MainMonitoring.initProps(args[0]) && MainMonitoring.init()) {

            System.out.println("Running ActiveMQ instance on "
                    + environmentParameters.getProperty("java.naming.provider.url"));

            ActiveMQRunner anActiveMQInstance = new ActiveMQRunner(
                    environmentParameters.getProperty("java.naming.provider.url"));
            new Thread(anActiveMQInstance).start();

            while (!anActiveMQInstance.isBrokerStarted()) {
                Thread.sleep(1000);
            }

            System.out.println("ActiveMQ is running");
            System.out.println("Running GLIMPSE");
            SplashScreen.Show();
            System.out.println("Please wait until setup is done...");

            //the buffer where the events are stored to be analyzed, in this version
            //the buffer object is not used because Drools has it's own eventStream object
            EventsBuffer<GlimpseBaseEvent<?>> buffer = new EventsBufferImpl<GlimpseBaseEvent<?>>();

            //The complex event engine that will be used (in this case drools)
            ComplexEventProcessor engineOne = new ComplexEventProcessorImpl(Manager.Read(MANAGERPARAMETERFILE),
                    buffer, connFact, initConn);

            engineOne.start();

            RestNotifier notifierEngine = new RestNotifier();
            notifierEngine.start();

            //using H2 database
            DBController databaseController = new H2Controller(Manager.Read(DATABASECONNECTIONSTRINGH2));

            //using MYSQL database
            //DBController databaseController = new MySqlController(Manager.Read(DATABASECONNECTIONSTRINGMYSQL));

            LearnerAssessmentManager lam = new LearnerAssessmentManagerImpl(databaseController);
            lam.start();

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            RuleTemplateManager templateManager = new RuleTemplateManager(DROOLSRULEREQUESTTEMPLATE1,
                    DROOLSRULEREQUESTTEMPLATE2, DROOLSRULEREQUESTTEMPLATE3_1, DROOLSRULEREQUESTTEMPLATE3_2);

            //the component in charge to locate services and load specific rules.
            ServiceLocatorFactory.getServiceLocatorParseViolationReceivedFromBSM(engineOne, templateManager,
                    REGEXPATTERNFILEPATH).start();

            //start MailNotifier component
            MailNotification mailer = new MailNotification(Manager.Read(MAILNOTIFICATIONSETTINGSFILEPATH));
            mailer.start();
            //the manager of all the architecture
            GlimpseManager manager = new GlimpseManager(Manager.Read(MANAGERPARAMETERFILE), connFact, initConn,
                    engineOne.getRuleManager(), lam);

            manager.start();
        }
    } catch (Exception e) {
        System.out.println("USAGE: java -jar MainMonitoring.jar \"systemSettings\"");
    }
}