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:com.linkedin.databus2.core.schema.tools.AvroConvertMain.java

/**
 * @param args//from  www. j a  v a2s .  c  o m
 */
public static void main(String[] args) throws Exception {

    ConsoleAppender app = new ConsoleAppender(new SimpleLayout());
    Logger.getRootLogger().removeAllAppenders();
    Logger.getRootLogger().addAppender(app);

    AvroConvertCli cli = new AvroConvertCli();

    try {
        cli.parseCommandLine(args);
    } catch (ParseException pe) {
        System.err.println(pe.getMessage());
        cli.printUsage();
        System.exit(1);
    }

    if (!cli.hasOptions() || cli.hasHelpOption()) {
        cli.printUsage();
        System.exit(0);
    }

    int verbosity = cli.getVerbosity();
    switch (verbosity) {
    case 0:
        Logger.getRootLogger().setLevel(Level.ERROR);
        break;
    case 1:
        Logger.getRootLogger().setLevel(Level.INFO);
        break;
    case 2:
        Logger.getRootLogger().setLevel(Level.DEBUG);
        break;
    default:
        Logger.getRootLogger().setLevel(Level.ALL);
        break;
    }

    AvroFormat inputFormat = cli.getInputFormat(AvroFormat.JSON);
    LOG.info("Using input format: " + inputFormat);

    AvroFormat outputFormat = cli.getOutputFormat(AvroFormat.JSON);
    LOG.info("Using output format: " + outputFormat);

    String inputSchemaName = cli.getInputSchema(null);
    if (null == inputSchemaName) {
        System.err.println("Input schema expected");
        cli.printUsage();
        System.exit(4);
    }

    Schema inputSchema = null;
    try {
        inputSchema = openSchema(inputSchemaName);
    } catch (IOException ioe) {
        System.err.println("Unable to open input schema: " + ioe);
        System.exit(2);
    }
    LOG.info("Using input schema:" + inputSchemaName);

    String outputSchemaName = cli.getOutputSchema(inputSchemaName);
    Schema outputSchema = null;
    try {
        outputSchema = outputSchemaName.equals(inputSchemaName) ? inputSchema : openSchema(outputSchemaName);
    } catch (IOException ioe) {
        System.err.println("Unable to open output schema: " + ioe);
        System.exit(3);
    }
    LOG.info("Using output schema:" + outputSchemaName);

    String inputFileName = cli.getInputFileName("-");
    InputStream input = inputFileName.equals("-") ? System.in : new FileInputStream(inputFileName);
    LOG.info("Using input: " + inputFileName);

    String outputFileName = cli.getOutputFileName("-");
    OutputStream output = outputFileName.equals("-") ? System.out : new FileOutputStream(outputFileName);
    LOG.info("Using output: " + outputFileName);

    AvroConverter avroConverter = new AvroConverter(inputFormat, outputFormat, inputSchema, outputSchema);
    avroConverter.convert(input, output);
    if (!inputFileName.equals("-"))
        input.close();
    if (!outputFileName.equals("-"))
        output.close();
}

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/*from   ww w  . j  av a  2  s  . co  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:com.seanmadden.net.fast.SerialInterface.java

public static void main(String[] args) {
    SerialInterface inter = new SerialInterface(new JSONObject());
    inter.open();//from www  .j a va 2  s.c o  m

    System.out.println("Welcome.  Commands with 'help'");
    String cmd = "";
    Scanner scan = new Scanner(System.in);
    do {
        System.out.print("> ");
        cmd = scan.nextLine();
        if (cmd.toLowerCase().equals("help")) {
            System.out.println("Commands:");
            System.out.println("help : prints this message");
            System.out.println("send <message> : sends <message> to interpretype.");
            System.out.println("quit : exits this program");
        } else if (cmd.toLowerCase().startsWith("send")) {
            String message = cmd.substring(cmd.toLowerCase().indexOf(' ') + 1);
            inter.sendDataToPort(message);
        }
    } while (!cmd.toLowerCase().equals("quit"));

    inter.close();
}

From source file:com.ibm.jaql.MiniCluster.java

/**
 * @param args/*w w  w  . j  a v a 2  s.c o  m*/
 */
public static void main(String[] args) throws IOException {
    String clusterHome = System.getProperty("hadoop.minicluster.dir");
    if (clusterHome == null) {
        clusterHome = "./minicluster";
        System.setProperty("hadoop.minicluster.dir", clusterHome);
    }
    LOG.info("hadoop.minicluster.dir=" + clusterHome);
    File clusterFile = new File(clusterHome);
    if (!clusterFile.exists()) {
        clusterFile.mkdirs();
    }
    if (!clusterFile.isDirectory()) {
        throw new IOException("minicluster home directory must be a directory: " + clusterHome);
    }
    if (!clusterFile.canRead() || !clusterFile.canWrite()) {
        throw new IOException("minicluster home directory must be readable and writable: " + clusterHome);
    }

    String logDir = System.getProperty("hadoop.log.dir");
    if (logDir == null) {
        logDir = clusterHome + File.separator + "logs";
        System.setProperty("hadoop.log.dir", logDir);
    }
    File logFile = new File(logDir);
    if (!logFile.exists()) {
        logFile.mkdirs();
    }

    String confDir = System.getProperty("hadoop.conf.override");
    if (confDir == null) {
        confDir = clusterHome + File.separator + "conf";
        System.setProperty("hadoop.conf.override", confDir);
    }
    File confFile = new File(confDir);
    if (!confFile.exists()) {
        confFile.mkdirs();
    }

    System.out.println("starting minicluster in " + clusterHome);
    MiniCluster mc = new MiniCluster(args);
    // To find the ports in the 
    // hdfs: search for: Web-server up at: localhost:####
    // mapred: search for: mapred.JobTracker: JobTracker webserver: ####
    Configuration conf = mc.getConf();
    System.out.println("fs.default.name: " + conf.get("fs.default.name"));
    System.out.println("dfs.http.address: " + conf.get("dfs.http.address"));
    System.out.println("mapred.job.tracker.http.address: " + conf.get("mapred.job.tracker.http.address"));

    boolean waitForInterrupt;
    try {
        System.out.println("press enter to end minicluster (or eof to run forever)...");
        waitForInterrupt = System.in.read() < 0; // wait for any input or eof
    } catch (Exception e) {
        // something odd happened.  Just shutdown. 
        LOG.error("error reading from stdin", e);
        waitForInterrupt = false;
    }

    // eof means that we will wait for a kill signal
    while (waitForInterrupt) {
        System.out.println("minicluster is running until interrupted...");
        try {
            Thread.sleep(60 * 60 * 1000);
        } catch (InterruptedException e) {
            waitForInterrupt = false;
        }
    }

    System.out.println("shutting down minicluster...");
    try {
        mc.tearDown();
    } catch (Exception e) {
        LOG.error("error while shutting down minicluster", e);
    }
}

From source file:com.dlmu.heipacker.crawler.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {// w w w  .  j  av  a 2s . co m
        // Create local execution context
        HttpContext localContext = new BasicHttpContext();

        HttpGet httpget = new HttpGet("http://localhost/test");

        boolean trying = true;
        while (trying) {
            System.out.println("executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget, localContext);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Consume response content
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);

            int sc = response.getStatusLine().getStatusCode();

            AuthState authState = null;
            HttpHost authhost = null;
            if (sc == HttpStatus.SC_UNAUTHORIZED) {
                // Target host authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            }
            if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // Proxy authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
            }

            if (authState != null) {
                System.out.println("----------------------------------------");
                AuthScheme authscheme = authState.getAuthScheme();
                System.out.println("Please provide credentials for " + authscheme.getRealm() + "@"
                        + authhost.toHostString());

                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter username: ");
                String user = console.readLine();
                System.out.print("Enter password: ");
                String password = console.readLine();

                if (user != null && user.length() > 0) {
                    Credentials creds = new UsernamePasswordCredentials(user, password);
                    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
                    trying = true;
                } else {
                    trying = false;
                }
            } else {
                trying = false;
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:test.mandelbrot.MandelbrotApp.java

public static void main(String[] args) {

    try {/*from w  ww .  j  a  v a 2 s . co m*/

        log.info("GridNode Starting...");
        StopWatch sw = new StopWatch();
        sw.start();

        GridNode node = Grid.startLightGridNode();

        log.info("GridNode ID : " + node.getId());

        sw.stop();

        log.info("GridNode Started Up. [" + sw.getLastTaskTimeMillis() + " ms]");

        // Create App Instance
        final MandelbrotApp app = new MandelbrotApp(node);

        app.requestFocus();

        // Create Mandelbrot Job
        MandelbrotJob mandelbrotJob = new MandelbrotJob(app.getWidth(), app.getHeight());

        // Start Job Submission
        sw.start();

        GridJobFuture future = node.getJobSubmissionService().submitJob(mandelbrotJob, new ResultCallback() {

            public void onResult(Serializable result) {

                MandelbrotResult mResult = (MandelbrotResult) result;
                app.displayResult(mResult);
                app.setProgress(app.getProgress() + mResult.getLines());
            }

        });

        app.setFuture(future);
        // Block till job finishes
        future.getResult();
        app.setDone(true);

        sw.stop();

        log.info("GridJob Finished. Duration " + sw.getLastTaskTimeMillis() + " ms");

        log.debug("Press any key to unregister GridNode and terminate");
        System.in.read();
        node.getNodeRegistrationService().unregister();

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

}

From source file:com.aestel.chemistry.openEye.fp.apps.SDFFPNNFinder.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from w  w w .j a  va2 s.c om
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp();
    }

    args = cmd.getArgs();
    if (args.length > 0) {
        exitWithHelp("Unknown param: " + args[0]);
    }

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

    int nCpu = 1;
    int maxNeighbors = 1;
    double minSim = 0D;

    String fpTag = cmd.getOptionValue("fpTag");
    String idTag = cmd.getOptionValue("idTag");
    boolean doMaxTanimoto = cmd.hasOption("maxTanimoto");
    boolean printAll = cmd.hasOption("printAll");

    String d = cmd.getOptionValue("nCpu");
    if (d != null)
        nCpu = Integer.parseInt(d);

    d = cmd.getOptionValue("maxNeighbors");
    if (d != null)
        maxNeighbors = Integer.parseInt(d);

    d = cmd.getOptionValue("minSimilarity");
    if (d != null)
        minSim = Double.parseDouble(d);

    String countAboveSimilarityStr = cmd.getOptionValue("countSimilarAbove");

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String refFile = cmd.getOptionValue("ref");

    String tabOutput = cmd.getOptionValue("tabOutput");
    boolean outputDuplicates = cmd.hasOption("outputDuplicates");

    if (outputDuplicates && tabOutput != null)
        exitWithHelp("-outputDuplicates will not work with tabOutput");

    if (outputDuplicates && refFile == null)
        exitWithHelp("-outputDuplicates requires -ref ");

    if ("tab".equalsIgnoreCase(tabOutput) && refFile != null)
        exitWithHelp("-tabOutput tab: does not work with reference file");

    if ("tab".equalsIgnoreCase(tabOutput) && maxNeighbors == 1)
        exitWithHelp("-tabOutput tab: does not make sense with -maxNeighbors = 1");

    if (cmd.hasOption("countSimilarAbove") && tabOutput != null)
        exitWithHelp("-countSimilarAbove not supported for tab or vTab output");

    if (printAll && !(maxNeighbors > 1 || minSim > 0))
        exitWithHelp("printAll only supported if: maxNeighbors > 1 or minSim > 0");

    if (printAll && tabOutput != null)
        System.err.println("WARNING: printAll ignored tor tab output!\n");

    SimComparatorFactory<OEMolBase, FPComparator, FPComparator> compFact = new FPComparatorFact(doMaxTanimoto,
            fpTag);

    if (refFile == null) {
        perfromMatrixNNSearch(inFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu,
                countAboveSimilarityStr, printAll);

    } else {
        performReferenceSearch(inFile, refFile, outFile, tabOutput, compFact, minSim, maxNeighbors, idTag, nCpu,
                countAboveSimilarityStr, outputDuplicates, printAll);
    }

}

From source file:edu.wisc.doit.tcrypt.cli.TokenCrypt.java

public static void main(String[] args) throws IOException {
    // create Options object
    final Options options = new Options();

    // operation opt group
    final OptionGroup cryptTypeGroup = new OptionGroup();
    cryptTypeGroup.addOption(new Option("e", "encrypt", false, "Encrypt a token"));
    cryptTypeGroup.addOption(new Option("d", "decrypt", false, "Decrypt a token"));
    cryptTypeGroup//from w  ww .  ja v  a  2s  .  co m
            .addOption(new Option("c", "check", false, "Check if the string looks like an encrypted token"));
    cryptTypeGroup.setRequired(true);
    options.addOptionGroup(cryptTypeGroup);

    // token source opt group
    final OptionGroup tokenGroup = new OptionGroup();
    final Option tokenOpt = new Option("t", "token", true, "The token(s) to operate on");
    tokenOpt.setArgs(Option.UNLIMITED_VALUES);
    tokenGroup.addOption(tokenOpt);
    final Option tokenFileOpt = new Option("f", "file", true,
            "A file with one token per line to operate on, if - is specified stdin is used");
    tokenGroup.addOption(tokenFileOpt);
    tokenGroup.setRequired(true);
    options.addOptionGroup(tokenGroup);

    final Option keyOpt = new Option("k", "keyFile", true,
            "Key file to use. Must be a private key for decryption and a public key for encryption");
    keyOpt.setRequired(true);
    options.addOption(keyOpt);

    // create the parser
    final CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // automatically generate the help statement
        System.err.println(exp.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + TokenCrypt.class.getName(), options, true);
        System.exit(1);
    }

    final Reader keyReader = createKeyReader(line);

    final TokenHandler tokenHandler = createTokenHandler(line, keyReader);

    if (line.hasOption("t")) {
        //tokens on cli
        final String[] tokens = line.getOptionValues("t");
        for (final String token : tokens) {
            handleToken(tokenHandler, token);
        }
    } else {
        //tokens from a file
        final String tokenFile = line.getOptionValue("f");
        final BufferedReader fileReader;
        if ("-".equals(tokenFile)) {
            fileReader = new BufferedReader(new InputStreamReader(System.in));
        } else {
            fileReader = new BufferedReader(new FileReader(tokenFile));
        }

        while (true) {
            final String token = fileReader.readLine();
            if (token == null) {
                break;
            }

            handleToken(tokenHandler, token);
        }
    }
}

From source file:Strings.java

/**
 * This simple main program looks after filenames and opening files and such
 * like for you.//from  w ww .  ja  v a 2 s .c o  m
 */
public static void main(String[] av) {
    Strings o = new Strings();
    if (av.length == 0) {
        o.process("standard input", System.in);
    } else {
        for (int i = 0; i < av.length; i++)
            try {
                o.process(av[i], new FileInputStream(av[i]));
            } catch (FileNotFoundException e) {
                System.err.println(e);
            }
    }
}

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

/**
 * @param args/* ww w. j av  a2s.  c o  m*/
 */
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");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported");
    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);
    SDFRingSystemExtractor extractor = new SDFRingSystemExtractor(outFile);
    extractor.run(inFile);
    extractor.close();
}