Example usage for java.lang System in

List of usage examples for java.lang System in

Introduction

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

Prototype

InputStream in

To view the source code for java.lang System in.

Click Source Link

Document

The "standard" input stream.

Usage

From source file:markov.java

/**
 * @param args/*from w w w .j ava2 s .c o m*/
 */
public static void main(String[] args) {

    // hack: eclipse don't support IO redirection worth a shit
    // try {
    // System.setIn(new FileInputStream("./json"));
    // } catch (FileNotFoundException e1) {
    // // TODO Auto-generated catch block
    // e1.printStackTrace();
    // }

    boolean graphMode = false;
    boolean jsonMode = false;
    boolean jsonRecoverMode = false;
    boolean endNode = false;

    int count = -1;

    long n = 0;
    long sumOfSqr = 0;
    long sum = 0;

    for (String s : args) {

        if (!s.matches("^-[vegjJh]*(c[0-9]*)?$")) {
            System.out.println("invalid argument");
            return;
        }

        if (s.matches("^-.*h.*")) {
            System.out.println(HELP);
            return;
        }
        if (s.matches("^-.*v.*")) {
            verbose = true;
            log("verbose mode");
        }
        if (s.matches("^-.*g.*")) {
            graphMode = true;
            log("graph mode");
        }
        if (s.matches("^-.*j.*")) {
            jsonMode = true;
            log("json mode");
        }
        if (s.matches("^-.*J.*")) {
            jsonRecoverMode = true;
            log("json recover mode");
        }
        if (s.matches("^-.*e.*")) {
            endNode = true;
            log("include end node");
        }
        if (s.matches("^-.*c[0-9]*$")) {
            log("counted output mode");
            count = Integer.parseInt(s.replaceAll("^-.*c", ""));
        }

        boolean error = (graphMode == true && jsonMode == true);
        if (!error) {
            error = (count > -1) && (graphMode == true || jsonMode == true);
        }

        if (error) {
            System.err.println("[error] switches j, g and, c are mutualy exclusive.");
            return;
        }

    }

    StateTransitionDiagram<Character> std;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    try {
        if (!jsonRecoverMode) {
            Trainer<Character> trainer = new Trainer<Character>();
            String s = br.readLine();
            while (s != null) {
                trainer.train(string2List(s));
                n++;
                sumOfSqr += s.length() * s.length();
                sum += s.length();
                s = br.readLine();
            }
            if (n == 0) {
                System.err
                        .println("Invalid corpus: At least one sample is required, two to make it interesting");
                return;
            }
            std = trainer.getTransitionDiagram();
        } else {
            std = new StateTransitionDiagram<Character>();
            GsonStub gstub = new Gson().fromJson(br, GsonStub.class);
            n = gstub.meta.n;
            sum = gstub.meta.sum;
            sumOfSqr = gstub.meta.sumOfSqr;

            for (Entry<String, StateStub> entry : gstub.states.entrySet()) {
                State<Character> state;
                if (entry.getKey().equals("null")) {
                    state = std.getGuard();
                } else {
                    state = std.getState(Character.valueOf(entry.getKey().charAt(0)));
                }
                for (Entry<String, Integer> transitions : entry.getValue().transitions.entrySet()) {
                    State<Character> tranny;
                    if (transitions.getKey().equals("null")) {
                        tranny = std.getGuard();
                    } else {
                        tranny = std.getState(Character.valueOf(transitions.getKey().charAt(0)));
                    }

                    state.addTransition(tranny.getValue(), transitions.getValue());
                }
            }
        }
        if (graphMode) {
            if (endNode) {
                System.out.println(std.toString());
            } else {
                System.out.println(std.removeEndGuards().toString());
            }
            return;
        }
        if (jsonMode) {
            Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

            String partialJson;
            if (endNode) {
                partialJson = gson.toJson(std);
            } else {
                partialJson = gson.toJson(std.removeEndGuards());
            }
            GsonStub gstub = new Gson().fromJson(partialJson, GsonStub.class);
            gstub.meta = new Meta();
            gstub.meta.n = n;
            gstub.meta.sum = sum;
            gstub.meta.sumOfSqr = sumOfSqr;

            System.out.println(gson.toJson(gstub));
            return;
        }

        Generator<Character> generator;
        if (endNode) {
            generator = new EndTagGenerator<Character>(std);
        } else {
            double sd = ((double) sumOfSqr - (double) (sum * sum) / (double) n) / (double) (n - 1);
            double mean = (double) sum / (double) n;
            log(String.format("mean: %.4f sd: %.4f", mean, sd));
            NormalDistributionImpl dist = new NormalDistributionImpl(mean, sd);
            generator = new NormalizedGenerator<Character>(std.removeEndGuards(), dist);
        }
        if (count >= 0) {
            for (int c = 0; c < count; c++) {
                output(generator);
            }
        } else {
            while (true) {
                output(generator);
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:examples.TelnetClientExample.java

/***
 * Main for the TelnetClientExample./*  ww w. j  a va  2s . c o  m*/
 ***/
public static void main(String[] args) throws IOException {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (Exception e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (Exception e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++)
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                boolean initlocal = (new Boolean(st.nextToken())).booleanValue();
                                boolean initremote = (new Boolean(st.nextToken())).booleanValue();
                                boolean acceptlocal = (new Boolean(st.nextToken())).booleanValue();
                                boolean acceptremote = (new Boolean(st.nextToken())).booleanValue();
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            try {
                                tc.registerSpyStream(fout);
                            } catch (Exception e) {
                                System.err.println("Error registering the spy");
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (Exception e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (Exception e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (Exception e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:ch.unizh.ini.jaer.projects.gesture.vlccontrol.TelnetClientExample.java

/***
 * Main for the TelnetClientExample.// w ww.  ja va  2  s.  com
 ***/
public static void main(String[] args) throws IOException {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (Exception e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (Exception e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                boolean initlocal = (new Boolean(st.nextToken())).booleanValue();
                                boolean initremote = (new Boolean(st.nextToken())).booleanValue();
                                boolean acceptlocal = (new Boolean(st.nextToken())).booleanValue();
                                boolean acceptremote = (new Boolean(st.nextToken())).booleanValue();
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            try {
                                tc.registerSpyStream(fout);
                            } catch (Exception e) {
                                System.err.println("Error registering the spy");
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (Exception e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (Exception e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (Exception e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:com.zarkonnen.longan.Main.java

public static void main(String[] args) throws IOException {
    // Use Apache Commons CLI (packaged into the Jar) to parse command line options.
    Options options = new Options();
    Option helpO = OptionBuilder.withDescription("print help").create("h");
    Option versionO = OptionBuilder.withDescription("print version").create("v");
    Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg()
            .withArgName("file").create("o");
    Option formatO = OptionBuilder
            .withDescription("output format: one of plaintext (default) and visualize (debug output in png)")
            .hasArg().withArgName("format").withLongOpt("format").create();
    Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads "
            + "command line strings one per line exactly as above. If no output file is "
            + "specified, returns a line containing the number of output lines before the "
            + "output. If there is an error, returns a single line with the error message. "
            + "Shut down server by sending \"quit\".").withLongOpt("server").create();
    Option openCLO = OptionBuilder
            .withDescription(/*from   w  ww  .jav  a2 s .  c o m*/
                    "enables use of the graphics card to " + "support the OCR system. Defaults to true.")
            .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create();
    options.addOption(helpO);
    options.addOption(versionO);
    options.addOption(outputO);
    options.addOption(formatO);
    options.addOption(serverO);
    options.addOption(openCLO);
    CommandLineParser clp = new GnuParser();
    try {
        CommandLine line = clp.parse(options, args);
        if (line.hasOption("h")) {
            new HelpFormatter().printHelp(INVOCATION, options);
            System.exit(0);
        }
        if (line.hasOption("v")) {
            System.out.println(Longan.VERSION);
            System.exit(0);
        }
        boolean enableOpenCL = true;
        if (line.hasOption("enable-opencl")) {
            enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true")
                    || line.getOptionValue("enable-opencl").equals("1");
        }
        if (line.hasOption("server")) {
            Longan longan = Longan.getDefaultImplementation(enableOpenCL);
            BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String input = inputR.readLine();
                if (input.trim().equals("quit")) {
                    return;
                }
                String[] args2 = splitInput(input);
                Options o2 = new Options();
                o2.addOption(outputO);
                o2.addOption(formatO);
                try {
                    line = clp.parse(o2, args2);

                    File outFile = null;
                    if (line.hasOption("o")) {
                        outFile = new File(line.getOptionValue("o"));
                    }

                    ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
                    if (format != DEFAULT_FORMAT && outFile == null) {
                        System.out.println("You must specify an output file for non-plaintext output.");
                        continue;
                    }

                    if (line.getArgList().isEmpty()) {
                        System.out.println("Please specify an input image.");
                        continue;
                    }
                    if (line.getArgList().size() > 1) {
                        System.err.println("Please specify one input image at a time");
                        continue;
                    }

                    File inFile = new File((String) line.getArgList().get(0));

                    if (!inFile.exists()) {
                        System.out.println("The input image does not exist.");
                        continue;
                    }

                    try {
                        Result result = longan.process(ImageIO.read(inFile));
                        if (outFile == null) {
                            String txt = DEFAULT_FORMAT.convert(result);
                            System.out.println(numNewlines(txt) + 1);
                            System.out.print(txt);
                        } else {
                            if (outFile.getAbsoluteFile().getParentFile() != null
                                    && !outFile.getAbsoluteFile().getParentFile().exists()) {
                                outFile.getParentFile().mkdirs();
                            }
                            FileOutputStream fos = new FileOutputStream(outFile);
                            try {
                                format.write(result, fos);
                            } finally {
                                fos.close();
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("Processing error: " + exception(e));
                    }
                } catch (ParseException e) {
                    System.out.println("Input not recognized: " + exception(e));
                }
            } // End server loop
        } else {
            // Single invocation
            File outFile = null;
            if (line.hasOption("o")) {
                outFile = new File(line.getOptionValue("o"));
            }

            ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
            if (format != DEFAULT_FORMAT && outFile == null) {
                System.err.println("You must specify an output file for non-plaintext output.");
                System.exit(1);
            }

            if (line.getArgList().isEmpty()) {
                System.err.println("Please specify an input image.");
                new HelpFormatter().printHelp(INVOCATION, options);
                System.exit(1);
            }
            if (line.getArgList().size() > 1) {
                System.err.println("Please specify one input image only. To process multiple "
                        + "images, use server mode.");
                System.exit(1);
            }
            File inFile = new File((String) line.getArgList().get(0));

            if (!inFile.exists()) {
                System.err.println("The input image does not exist.");
                System.exit(1);
            }

            try {
                Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile));
                if (outFile == null) {
                    String txt = DEFAULT_FORMAT.convert(result);
                    System.out.print(txt);
                } else {
                    if (outFile.getAbsoluteFile().getParentFile() != null
                            && !outFile.getAbsoluteFile().getParentFile().exists()) {
                        outFile.getParentFile().mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(outFile);
                    try {
                        format.write(format.convert(result), fos);
                    } finally {
                        fos.close();
                    }
                }
            } catch (Exception e) {
                System.err.println("Processing error: " + exception(e));
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.println("Parsing command line input failed: " + exception(e));
        System.exit(1);
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFMolSeparator.java

/**
 * @param args//from  w w  w . ja v a  2  s . c om
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    SDFMolSeparator separator = new SDFMolSeparator(outFile);

    try {
        separator.run(inFile);

    } catch (IndexOutOfBoundsException iie) {
        System.err.println(iie.toString());
        exitWithHelp(options);
    } finally {
        separator.close();
    }

}

From source file:net.cliftonsnyder.svgchart.Main.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("c", "stylesheet", true, "CSS stylesheet (default: " + SVGChart.DEFAULT_STYLESHEET + ")");
    options.addOption("h", "height", true, "chart height");
    options.addOption("i", "input-file", true, "input file [default: stdin]");
    options.addOption("o", "output-file", true, "output file [default: stdout]");
    options.addOption("w", "width", true, "chart width");
    options.addOption("?", "help", false, "print a brief help message");

    Option type = new Option("t", "type", true, "chart type " + Arrays.toString(SVGChart.TYPES));
    type.setRequired(true);//w w w.ja  v a2s.co m
    options.addOption(type);

    CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            formatter.printHelp(USAGE, options);
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("unable to parse command line: " + exp.getMessage());
        formatter.printHelp(USAGE, options);
        System.exit(1);
    }

    SVGChart chart = null;
    String tmp = line.getOptionValue("type");
    Matcher m = null;
    for (Pattern p : SVGChart.TYPE_PATTERNS) {
        if ((m = p.matcher(tmp)).matches()) {
            switch (m.group().charAt(0)) {
            case 'l':
                // DEBUG
                System.err.println("line");
                break;
            case 'b':
                System.err.println("bar");
                chart = new BarChart();
                break;
            case 'p':
                System.err.println("pie");
                break;
            default:
                System.err.println("unknown or unimplemented chart type: '" + tmp + "'");
                System.exit(1);
            }
        }
    }

    try {
        chart.setWidth(Double.parseDouble(line.getOptionValue("width", "" + SVGChart.DEFAULT_WIDTH)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid width value '" + line.getOptionValue("width") + "'");
        System.exit(1);
    }

    try {
        chart.setHeight(Double.parseDouble(line.getOptionValue("height", "" + SVGChart.DEFAULT_HEIGHT)));
    } catch (NumberFormatException e) {
        System.err.println(
                "unable to parse command line: invalid height value '" + line.getOptionValue("height") + "'");
        System.exit(1);
    }

    InputStream in = System.in;
    tmp = line.getOptionValue("input-file", "-");
    if ("-".equals(tmp)) {
        in = System.in;
    } else {
        try {
            in = new FileInputStream(tmp);
        } catch (FileNotFoundException e) {
            System.err.println("input file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    PrintStream out = System.out;
    tmp = line.getOptionValue("output-file", "-");
    if ("-".equals(tmp)) {
        out = System.out;
    } else {
        try {
            out = new PrintStream(new FileOutputStream(tmp));
        } catch (FileNotFoundException e) {
            System.err.println("output file not found: '" + tmp + "'");
            System.exit(1);
        }
    }

    tmp = line.getOptionValue("stylesheet", SVGChart.DEFAULT_STYLESHEET);
    chart.setStyleSheet(tmp);

    try {
        chart.parseInput(in);
    } catch (IOException e) {
        System.err.println("I/O error while reading input");
        System.exit(1);
    } catch (net.cliftonsnyder.svgchart.parse.ParseException e) {
        System.err.println("error parsing input: " + e.getMessage());
    }

    chart.createChart();

    try {
        chart.printChart(out, true);
    } catch (IOException e) {
        System.err.println("error serializing output");
        System.exit(1);
    }
}

From source file:com.sm.store.server.grizzly.GZClusterServer.java

public static void main(String[] args) {
    String[] opts = new String[] { "-host", "-configPath", "-dataPath", "-port", "replicaPort", "-start",
            "-freq" };
    String[] defaults = new String[] { "", "", "", "0", "0", "true", "10" };
    String[] paras = getOpts(args, opts, defaults);

    String configPath = paras[1];
    if (configPath.length() == 0) {
        logger.error("missing config path");
        throw new RuntimeException("missing -configPath");
    }/*from  w w w .j a  va 2  s  .c  o  m*/
    System.setProperty("configPath", configPath);
    NodeConfig nodeConfig = getNodeConfig(configPath + "/node.properties");
    //int clusterNo = Integer.valueOf( paras[0]);
    String dataPath = paras[2];
    if (dataPath.length() == 0) {
        dataPath = "./data";
    }
    int port = Integer.valueOf(paras[3]);
    int replicaPort = Integer.valueOf(paras[4]);
    //get from command line, if not form nodeConfig
    if (port == 0)
        port = nodeConfig.getPort();
    if (port == 0) {
        throw new RuntimeException("port is 0");
    } else {
        if (replicaPort == 0)
            replicaPort = port + 1;
    }
    boolean start = Boolean.valueOf(paras[5]);
    String host = paras[0];
    //get from command line, if not form nodeConfig or from getHost
    if (host.length() == 0)
        host = nodeConfig.getHost();
    if (host.length() == 0)
        host = getLocalHost();
    int freq = Integer.valueOf(paras[6]);
    logger.info("read clusterNode and storeConfig from " + configPath);
    BuildClusterNodes bcn = new BuildClusterNodes(configPath + "/clusters.xml");
    //BuildStoreConfig bsc = new BuildStoreConfig(configPath+"/stores.xml");
    BuildRemoteConfig brc = new BuildRemoteConfig(configPath + "/stores.xml");
    List<ClusterNodes> clusterNodesList = bcn.build();
    short clusterNo = findClusterNo(host + ":" + port, clusterNodesList);
    logger.info("create cluster server config for cluster " + clusterNo + " host " + host + " port " + port
            + " replica port " + replicaPort);
    ClusterServerConfig serverConfig = new ClusterServerConfig(clusterNodesList, brc.build().getConfigList(),
            clusterNo, dataPath, configPath, port, replicaPort, host);
    serverConfig.setFreq(freq);
    logger.info("create cluster server");
    GZClusterStoreServer cs = new GZClusterStoreServer(serverConfig, new HessianSerializer());
    // start replica server
    cs.startReplicaServer();
    logger.info("hookup jvm shutdown process");
    cs.hookShutdown();
    if (start) {
        logger.info("server is starting " + cs.getServerConfig().toString());
        cs.start();
    } else
        logger.warn("server is staged and wait to be started");

    List list = new ArrayList();
    //add jmx metric
    List<String> stores = cs.getAllStoreNames();
    for (String store : stores) {
        list.add(cs.getStore(store));
    }
    list.add(cs);
    stores.add("ClusterServer");
    JmxService jms = new JmxService(list, stores);

    try {
        logger.info("Read from console and wait ....");
        int c = System.in.read();
    } catch (IOException e) {
        logger.warn("Error reading " + e.getMessage());
    }
    logger.warn("Exiting from System.in.read()");
}

From source file:com.genentech.chemistry.openEye.apps.SDFConformerSampler.java

/**
 * @param args//ww w. j a  v  a 2s . com
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MAX_CONFS, true, "Maximum number of conformations per input.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_TORSION_FILE, true, "Optional: to overwrite torsion definition file.");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String smartsFile = cmd.getOptionValue(OPT_TORSION_FILE);
    long maxConfs = Long.parseLong(cmd.getOptionValue(OPT_MAX_CONFS));

    SDFConformerSampler scanner = new SDFConformerSampler(smartsFile, outFile, maxConfs);

    scanner.run(inFile);
    scanner.close();
}

From source file:gis.proj.drivers.Snyder.java

public static void main(String... args) {
    Snyder snyder = new Snyder();
    JCommander jc = new JCommander(snyder);

    try {//from  w  w  w.j  a v a 2 s .c  o m
        jc.parse(args);
    } catch (Exception e) {
        jc.usage();
        System.exit(-10);
    }

    String fFormat = "(forward)   X: %18.9f,   Y: %18.9f%n";
    String iFormat = "(inverse) Lon: %18.9f, Lat: %18.9f%n%n";

    double[][] xy, ll = null;

    java.util.regex.Pattern pq = java.util.regex.Pattern.compile("quit",
            java.util.regex.Pattern.CASE_INSENSITIVE);
    java.util.Scanner s = new java.util.Scanner(System.in);

    Projection proj = null;

    printLicenseInformation("Snyder");

    try {
        System.out.println("Loading projection: " + snyder.projStr);
        Class<?> cls = Class.forName(snyder.projStr);
        proj = (Projection) cls.newInstance();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    double lon = 0.0, lat = 0.0, x = 0.0, y = 0.0;

    Datum d = new Datum();
    Ellipsoid e = EllipsoidFactory.getInstance().getEllipsoid(snyder.ellpStr);
    System.out.println("\nEllipsoid: " + snyder.ellpStr + ", " + e.getName() + ", " + e.getId() + ", "
            + e.getDescription());

    for (String prop : e.getPropertyNames()) {
        System.out.println("\t" + prop + "\t" + e.getProperty(prop));
    }

    String cmdEntryLine = (snyder.inverse ? "\nx y " : "\nlon lat") + ": ";

    for (String dProp : proj.getDatumProperties()) {
        d.setUserOverrideProperty(dProp, 0.0);
    }
    System.out.print(cmdEntryLine);

    while (s.hasNext(pq) == false) {
        if (snyder.inverse == false) {
            lon = parseDatumVal(s.next());
            lat = parseDatumVal(s.next());
        } else {
            x = parseDatumVal(s.next());
            y = parseDatumVal(s.next());
        }

        for (String dp : d.getPropertyNames()) {
            System.out.print(dp + ": ");
            d.setUserOverrideProperty(dp, parseDatumVal(s.next()));
        }

        System.out.println();

        if (snyder.inverse == false) {
            xy = proj.forward(new double[] { lon }, new double[] { lat }, e, d);

            System.out.printf(fFormat, xy[0][0], xy[1][0]);

            ll = proj.inverse(new double[] { xy[0][0] }, new double[] { xy[1][0] }, e, d);

            System.out.printf(iFormat, StrictMath.toDegrees(ll[0][0]), StrictMath.toDegrees(ll[1][0]));
        } else {
            ll = proj.inverse(new double[] { x }, new double[] { y }, e, d);

            System.out.printf(iFormat, StrictMath.toDegrees(ll[0][0]), StrictMath.toDegrees(ll[1][0]));

            xy = proj.forward(new double[] { ll[0][0] }, new double[] { ll[1][0] }, e, d);

            System.out.printf(fFormat, xy[0][0], xy[1][0]);
        }

        System.out.print(cmdEntryLine);
    }

    s.close();
}

From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java

/**
 * @param args/*  w w  w .  j a  va2s  .  com*/
 */
public static void main(String[] args) {
    // Setup parameters
    int verbosity = 1;
    String output_format = "xml", grammar_filename = null, filename_to_parse = null;

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("f")) {
        output_format = c_line.getOptionValue("f");
    }
    // Get grammar file
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no grammar file specified");
        System.exit(ERR_ARGUMENTS);
    }
    grammar_filename = remaining_args.get(0);
    // Get file to parse, if any
    if (remaining_args.size() >= 2) {
        filename_to_parse = remaining_args.get(1);
    }

    // Read grammar file
    BnfParser parser = null;
    try {
        parser = new BnfParser(new File(grammar_filename));
    } catch (InvalidGrammarException e) {
        System.err.println("ERROR: invalid grammar");
        System.exit(ERR_GRAMMAR);
    } catch (IOException e) {
        System.err.println("ERROR reading grammar " + grammar_filename);
        System.exit(ERR_IO);
    }
    assert parser != null;

    // Read input file
    BufferedReader bis = null;
    if (filename_to_parse == null) {
        // Read from stdin
        bis = new BufferedReader(new InputStreamReader(System.in));
    } else {
        // Read from file
        try {
            bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse))));
        } catch (FileNotFoundException e) {
            System.err.println("ERROR: file not found " + filename_to_parse);
            System.exit(ERR_IO);
        }
    }
    assert bis != null;
    String str;
    StringBuilder input_file = new StringBuilder();
    try {
        while ((str = bis.readLine()) != null) {
            input_file.append(str).append("\n");
        }
    } catch (IOException e) {
        System.err.println("ERROR reading input");
        System.exit(ERR_IO);
    }
    String file_contents = input_file.toString();

    // Parse contents of file
    ParseNode p_node = null;
    try {
        p_node = parser.parse(file_contents);
    } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) {
        System.err.println("ERROR parsing input\n");
        e.printStackTrace();
        System.exit(ERR_PARSE);
    }
    if (p_node == null) {
        System.err.println("ERROR parsing input\n");
        System.exit(ERR_PARSE);
    }
    assert p_node != null;

    // Output parse node to desired format
    PrintStream output = System.out;
    OutputFormatVisitor out_vis = null;
    if (output_format.compareToIgnoreCase("xml") == 0) {
        // Output to XML
        out_vis = new XmlVisitor();
    } else if (output_format.compareToIgnoreCase("dot") == 0) {
        // Output to DOT
        out_vis = new GraphvizVisitor();
    } else if (output_format.compareToIgnoreCase("txt") == 0) {
        // Output to indented plain text
        out_vis = new IndentedTextVisitor();
    } else if (output_format.compareToIgnoreCase("json") == 0) {
        // Output to JSON
    }
    if (out_vis == null) {
        System.err.println("ERROR: unknown output format " + output_format);
        System.exit(ERR_ARGUMENTS);
    }
    assert out_vis != null;
    p_node.prefixAccept(out_vis);
    output.print(out_vis.toOutputString());

    // Terminate without error
    System.exit(ERR_OK);
}