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:at.tuwien.aic.Main.java

/**
 * Main entry point//from   w  ww  .  j  a v a2s. com
 *
 * @param args
 */
@SuppressWarnings("empty-statement")
public static void main(String[] args) throws IOException, InterruptedException {

    try {
        System.out.println(new java.io.File(".").getCanonicalPath());
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    TweetCrawler tc = null;

    try {
        tc = TweetCrawler.getInstance();
    } catch (UnknownHostException ex) {
        logger.severe("Could not connect to mongoDb");
        exitWithError(2);
        return;
    }

    int action;

    while (true) {
        action = getDecision("The following actions can be executed",
                new String[] { "Subscribe to topic", "Query topic", "Test preprocessing",
                        "Recreate the evaluation model", "Quit the application" },
                "What action do you want to execute?");

        switch (action) {
        case 1:
            tc.collectTweets(new DefaultTweetHandler() {
                @Override
                public boolean isMatch(String topic) {
                    return true;
                }
            }, getNonEmptyString(
                    "Which topic do you want to subscribe to (use spaces to specify more than one keyword)?")
                            .split(" "));

            System.out.println("Starting to collection tweets");
            System.out.println("Press enter to quit collecting");

            while (System.in.read() != 10)
                ;

            tc.stopCollecting();

            break;
        case 2:
            classifyTopic();
            break;
        case 3: {
            int subAction = getDecision("The following preprocessing steps are available",
                    new String[] { "Stop word removal", "Stemming", "Both" }, "What do you want to test?");

            switch (subAction) {
            case 1:
                stopWords();
                break;
            case 2:
                stem();
                break;
            case 3:
                stem(stopWords());
            default:
                break;
            }

            break;
        }
        case 4: {
            ClassifyTweet.saveModel("resources/traindata.arff", "resources/classifier.model");
            break;
        }
        case 5:
            exit();
        case 6: {
            ClassifyTweet.saveModel("resources/traindata.arff", "resources/classifier.model");
            Classifier c = ClassifyTweet.loadModel("resources/classifier.model");
            ClassifyTweet.classifyTweetArff(c, "resources/unlabeled.arff");
            //ClassifyTweet.evaluate(c, "resources/traindata.arff");
            break;
        }
        }
    }
}

From source file:edu.cmu.lti.oaqa.apps.Client.java

public static void main(String args[]) {
    BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));

    Options opt = new Options();

    Option o = new Option(PORT_SHORT_PARAM, PORT_LONG_PARAM, true, PORT_DESC);
    o.setRequired(true);//from   ww  w.  j  av a 2  s . c om
    opt.addOption(o);
    o = new Option(HOST_SHORT_PARAM, HOST_LONG_PARAM, true, HOST_DESC);
    o.setRequired(true);
    opt.addOption(o);
    opt.addOption(K_SHORT_PARAM, K_LONG_PARAM, true, K_DESC);
    opt.addOption(R_SHORT_PARAM, R_LONG_PARAM, true, R_DESC);
    opt.addOption(QUERY_TIME_SHORT_PARAM, QUERY_TIME_LONG_PARAM, true, QUERY_TIME_DESC);
    opt.addOption(RET_OBJ_SHORT_PARAM, RET_OBJ_LONG_PARAM, false, RET_OBJ_DESC);
    opt.addOption(RET_EXTERN_ID_SHORT_PARAM, RET_EXTERN_ID_LONG_PARAM, false, RET_EXTERN_ID_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {
        CommandLine cmd = parser.parse(opt, args);

        String host = cmd.getOptionValue(HOST_SHORT_PARAM);

        String tmp = null;

        tmp = cmd.getOptionValue(PORT_SHORT_PARAM);

        int port = -1;

        try {
            port = Integer.parseInt(tmp);
        } catch (NumberFormatException e) {
            Usage("Port should be integer!");
        }

        boolean retObj = cmd.hasOption(RET_OBJ_SHORT_PARAM);
        boolean retExternId = cmd.hasOption(RET_EXTERN_ID_SHORT_PARAM);

        String queryTimeParams = cmd.getOptionValue(QUERY_TIME_SHORT_PARAM);
        if (null == queryTimeParams)
            queryTimeParams = "";

        SearchType searchType = SearchType.kKNNSearch;
        int k = 0;
        double r = 0;

        if (cmd.hasOption(K_SHORT_PARAM)) {
            if (cmd.hasOption(R_SHORT_PARAM)) {
                Usage("Range search is not allowed if the KNN search is specified!");
            }
            tmp = cmd.getOptionValue(K_SHORT_PARAM);
            try {
                k = Integer.parseInt(tmp);
            } catch (NumberFormatException e) {
                Usage("K should be integer!");
            }
            searchType = SearchType.kKNNSearch;
        } else if (cmd.hasOption(R_SHORT_PARAM)) {
            if (cmd.hasOption(K_SHORT_PARAM)) {
                Usage("KNN search is not allowed if the range search is specified!");
            }
            searchType = SearchType.kRangeSearch;
            tmp = cmd.getOptionValue(R_SHORT_PARAM);
            try {
                r = Double.parseDouble(tmp);
            } catch (NumberFormatException e) {
                Usage("The range value should be numeric!");
            }
        } else {
            Usage("One has to specify either range or KNN-search parameter");
        }

        String separator = System.getProperty("line.separator");

        StringBuffer sb = new StringBuffer();
        String s;

        while ((s = inp.readLine()) != null) {
            sb.append(s);
            sb.append(separator);
        }

        String queryObj = sb.toString();

        try {
            TTransport transport = new TSocket(host, port);
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);
            QueryService.Client client = new QueryService.Client(protocol);

            if (!queryTimeParams.isEmpty())
                client.setQueryTimeParams(queryTimeParams);

            List<ReplyEntry> res = null;

            long t1 = System.nanoTime();

            if (searchType == SearchType.kKNNSearch) {
                System.out.println(String.format("Running a %d-NN search", k));
                res = client.knnQuery(k, queryObj, retExternId, retObj);
            } else {
                System.out.println(String.format("Running a range search (r=%g)", r));
                res = client.rangeQuery(r, queryObj, retExternId, retObj);
            }

            long t2 = System.nanoTime();

            System.out.println(String.format("Finished in %g ms", (t2 - t1) / 1e6));

            for (ReplyEntry e : res) {
                System.out.println(String.format("id=%d dist=%g %s", e.getId(), e.getDist(),
                        retExternId ? "externId=" + e.getExternId() : ""));
                if (retObj)
                    System.out.println(e.getObj());
            }

            transport.close(); // Close transport/socket !
        } catch (TException te) {
            System.err.println("Apache Thrift exception: " + te);
            te.printStackTrace();
        }

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:examples.unix.rlogin.java

public static void main(String[] args) {
    String server, localuser, remoteuser, terminal;
    RLoginClient client;/*from   w  ww  . j  a  v a 2  s  .c  o m*/

    if (args.length != 4) {
        System.err.println("Usage: rlogin <hostname> <localuser> <remoteuser> <terminal>");
        System.exit(1);
        return; // so compiler can do proper flow control analysis
    }

    client = new RLoginClient();

    server = args[0];
    localuser = args[1];
    remoteuser = args[2];
    terminal = args[3];

    try {
        client.connect(server);
    } catch (IOException e) {
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }

    try {
        client.rlogin(localuser, remoteuser, terminal);
    } catch (IOException e) {
        try {
            client.disconnect();
        } catch (IOException f) {
        }
        e.printStackTrace();
        System.err.println("rlogin authentication failed.");
        System.exit(1);
    }

    IOUtil.readWrite(client.getInputStream(), client.getOutputStream(), System.in, System.out);

    try {
        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }

    System.exit(0);
}

From source file:com.janrain.backplane.common.HmacHashUtils.java

public static void main(String[] args) throws IOException {
    String password;//from  www .ja va  2 s.  c  om
    if (args.length == 1) {
        password = args[0];
    } else {
        System.out.print("Password: ");
        password = new BufferedReader(new InputStreamReader(System.in)).readLine();
    }
    System.out.println("hmac hash: " + hmacHash(password));
}

From source file:edu.scripps.fl.pubchem.app.CIDDownloader.java

public static void main(String[] args) throws Exception {
    CIDDownloader fetcher = new CIDDownloader();

    CommandLineHandler clh = new CommandLineHandler() {
        public void configureOptions(Options options) {
            options.addOption(OptionBuilder.withLongOpt("input_file").withType("").withValueSeparator('=')
                    .hasArg().create());
            options.addOption(OptionBuilder.withLongOpt("output_file").withType("").withValueSeparator('=')
                    .hasArg().isRequired().create());
        }//from   ww  w  .java  2s. c o  m
    };
    args = clh.handle(args);
    String inputFile = clh.getCommandLine().getOptionValue("input_file");
    String outputFile = clh.getCommandLine().getOptionValue("output_file");

    fetcher.setOutputFile(outputFile);
    Iterator<?> iterator;
    if (null == inputFile) {
        if (args.length == 0) {
            log.info("Running query to find CIDs in PCAssayResult but not in PCCompound");
            SQLQuery query = PubChemDB.getSession().createSQLQuery(
                    "select distinct r.cid from pcassay_result r left join pccompound c on r.cid = c.cid where (r.cid is not null and r.cid > 0 ) and c.cid is null order by r.cid");
            ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
            iterator = new ScrollableResultsIterator<Integer>(Integer.class, scroll);
        } else {
            iterator = Arrays.asList(args).iterator();
        }
    } else if ("-".equals(inputFile)) {
        log.info("Reading CIDs (one per line) from STDIN");
        iterator = new LineIterator(new InputStreamReader(System.in));
    } else {
        log.info("Reading CIDs (one per line) from " + inputFile);
        iterator = new LineIterator(new FileReader(inputFile));
    }
    fetcher.process(iterator);
    System.exit(0);
}

From source file:com.ariatemplates.seleniumjavarobot.Main.java

public static void main(String[] args) throws Exception {
    SeleniumJavaRobot seleniumJavaRobot = new SeleniumJavaRobot();
    String browser;/*from w w w.  ja v  a  2  s  . co m*/
    seleniumJavaRobot.autoRestart = false;
    if (OS.isFamilyMac()) {
        browser = "safari";
    } else {
        browser = "firefox";
    }
    seleniumJavaRobot.url = "http://localhost:7777/__attester__/slave.html";
    String usageString = String.format(
            "Usage: selenium-java-robot [options]\nOptions:\n  --auto-restart\n  --url <url> [default: %s]\n  --browser <browser> [default: %s, accepted values: %s]\n  -DpropertyName=value",
            seleniumJavaRobot.url, browser, BROWSERS_LIST.toString());
    for (int i = 0, l = args.length; i < l; i++) {
        String curParam = args[i];
        if ("--browser".equalsIgnoreCase(curParam) && i + 1 < l) {
            browser = args[i + 1];
            i++;
        } else if ("--url".equalsIgnoreCase(curParam) && i + 1 < l) {
            seleniumJavaRobot.url = args[i + 1];
            i++;
        } else if ("--auto-restart".equalsIgnoreCase(curParam)) {
            seleniumJavaRobot.autoRestart = true;
        } else if ("--version".equalsIgnoreCase(curParam)) {
            System.out.println(Main.class.getPackage().getImplementationVersion());
            return;
        } else if ("--help".equalsIgnoreCase(curParam)) {
            System.out.println(usageString);
            return;
        } else {
            Matcher matcher = SET_SYSTEM_PROPERTY_REGEXP.matcher(curParam);
            if (matcher.matches()) {
                System.setProperty(matcher.group(1), matcher.group(2));
            } else {
                System.err.println("Unknown command line option: " + curParam);
                System.err.println(usageString);
                return;
            }
        }
    }
    seleniumJavaRobot.robotizedBrowserFactory = LocalRobotizedBrowserFactory
            .createRobotizedWebDriverFactory(browser);
    seleniumJavaRobot.start();
    closeOnStreamEnd(seleniumJavaRobot, System.in);
    closeOnProcessEnd(seleniumJavaRobot);
}

From source file:edu.msu.cme.rdp.graph.sandbox.BloomFilterInterrogator.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("USAGE: BloomFilterStats <bloom_filter>");
        System.exit(1);//w ww  .ja  va  2  s . c  o m
    }

    File bloomFile = new File(args[0]);

    ObjectInputStream ois = ois = new ObjectInputStream(
            new BufferedInputStream(new FileInputStream(bloomFile)));
    BloomFilter filter = (BloomFilter) ois.readObject();
    ois.close();

    printStats(filter, System.out);

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line;
    CodonWalker walker = null;
    while ((line = reader.readLine()) != null) {
        char[] kmer = line.toCharArray();
        System.out.print(line + "\t");
        try {
            walker = filter.new RightCodonFacade(kmer);
            walker.jumpTo(kmer);
            System.out.print("present");
        } catch (Exception e) {
            System.out.print("not present\t" + e.getMessage());
        }
        System.out.println();
    }
}

From source file:cloudlens.cli.Main.java

public static void main(String[] args) throws Exception {
    final CommandLineParser optionParser = new DefaultParser();
    final HelpFormatter formatter = new HelpFormatter();

    final Option lens = Option.builder("r").longOpt("run").hasArg().argName("lens file").desc("Lens file.")
            .required(true).build();/*from  w w w  .j  a  v a  2  s  .  c o  m*/
    final Option log = Option.builder("l").longOpt("log").hasArg().argName("log file").desc("Log file.")
            .build();
    final Option jsonpath = Option.builder().longOpt("jsonpath").hasArg().argName("path")
            .desc("Path to logs in a json object.").build();
    final Option js = Option.builder().longOpt("js").hasArg().argName("js file").desc("Load JS file.").build();
    final Option format = Option.builder("f").longOpt("format").hasArg()
            .desc("Choose log format (text or json).").build();
    final Option streaming = Option.builder().longOpt("stream").desc("Streaming mode.").build();
    final Option history = Option.builder().longOpt("history").desc("Store history.").build();

    final Options options = new Options();
    options.addOption(log);
    options.addOption(lens);
    options.addOption(format);
    options.addOption(jsonpath);
    options.addOption(js);
    options.addOption(streaming);
    options.addOption(history);

    try {
        final CommandLine cmd = optionParser.parse(options, args);

        final String jsonPath = cmd.getOptionValue("jsonpath");
        final String[] jsFiles = cmd.getOptionValues("js");
        final String[] lensFiles = cmd.getOptionValues("run");
        final String[] logFiles = cmd.getOptionValues("log");
        final String source = cmd.getOptionValue("format");

        final boolean stream = cmd.hasOption("stream") || !cmd.hasOption("log");
        final boolean withHistory = cmd.hasOption("history") || !stream;

        final CL cl = new CL(System.out, System.err, stream, withHistory);

        try {
            final InputStream input = (cmd.hasOption("log")) ? FileReader.readFiles(logFiles) : System.in;

            if (source == null) {
                cl.source(input);
            } else {
                switch (source) {
                case "text":
                    cl.source(input);
                    break;
                case "json":
                    cl.json(input, jsonPath);
                    break;
                default:
                    input.close();
                    throw new CLException("Unsupported format: " + source);
                }
            }

            for (final String jsFile : FileReader.fullPaths(jsFiles)) {
                cl.engine.eval("CL.loadjs('file://" + jsFile + "')");
            }

            final List<ASTElement> top = ASTBuilder.parseFiles(lensFiles);
            cl.launch(top);

        } catch (final CLException | ASTException e) {
            cl.errWriter.println(e.getMessage());
        } finally {
            cl.outWriter.flush();
            cl.errWriter.flush();
        }
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("cloudlens", options);
    }
}

From source file:TripleDES.java

/**
 * The program. The first argument must be -e, -d, or -g to encrypt,
 * decrypt, or generate a key. The second argument is the name of a file
 * from which the key is read or to which it is written for -g. The -e and
 * -d arguments cause the program to read from standard input and encrypt or
 * decrypt to standard output.//from   w w  w. j a va2s.c om
 */
public static void main(String[] args) {
    try {
        // Check to see whether there is a provider that can do TripleDES
        // encryption. If not, explicitly install the SunJCE provider.
        try {
            Cipher c = Cipher.getInstance("DESede");
        } catch (Exception e) {
            // An exception here probably means the JCE provider hasn't
            // been permanently installed on this system by listing it
            // in the $JAVA_HOME/jre/lib/security/java.security file.
            // Therefore, we have to install the JCE provider explicitly.
            System.err.println("Installing SunJCE provider.");
            Provider sunjce = new com.sun.crypto.provider.SunJCE();
            Security.addProvider(sunjce);
        }

        // This is where we'll read the key from or write it to
        File keyfile = new File(args[1]);

        // Now check the first arg to see what we're going to do
        if (args[0].equals("-g")) { // Generate a key
            System.out.print("Generating key. This may take some time...");
            System.out.flush();
            SecretKey key = generateKey();
            writeKey(key, keyfile);
            System.out.println("done.");
            System.out.println("Secret key written to " + args[1] + ". Protect that file carefully!");
        } else if (args[0].equals("-e")) { // Encrypt stdin to stdout
            SecretKey key = readKey(keyfile);
            encrypt(key, System.in, System.out);
        } else if (args[0].equals("-d")) { // Decrypt stdin to stdout
            SecretKey key = readKey(keyfile);
            decrypt(key, System.in, System.out);
        }
    } catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java " + TripleDES.class.getName() + " -d|-e|-g <keyfile>");
    }
}

From source file:au.edu.uws.eresearch.cr8it.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments//from   ww w .j a v a 2  s.  co  m
 */
public static void main(final String... args) {

    String contextFilePath = "spring-integration-context.xml";
    String configFilePath = "config/config-file.groovy";
    String environment = System.getProperty("environment");

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n          Welcome to C8it Integration!                 "
                + "\n                                                         "
                + "\n    For more information please visit:                   "
                + "\n    http://www.springsource.org/spring-integration       "
                + "\n                                                         "
                + "\n=========================================================");
    }

    ConfigObject config = Config.getConfig(environment, configFilePath);
    Map configMap = config.flatten();
    System.setProperty("environment", environment);
    System.setProperty("cr8it.client.config.file", (String) configMap.get("file.runtimePath"));

    //final AbstractApplicationContext context =
    //new ClassPathXmlApplicationContext("classpath:META-INF/spring/integration/*-context.xml");

    String absContextPath = "config/integration/" + contextFilePath;
    File contextFile = new File(absContextPath);
    final AbstractApplicationContext context;
    if (!contextFile.exists()) {
        absContextPath = "classpath:" + absContextPath;
        context = new ClassPathXmlApplicationContext(absContextPath);
    } else {
        absContextPath = "file:" + absContextPath;
        context = new FileSystemXmlApplicationContext(absContextPath);
    }

    context.registerShutdownHook();

    SpringIntegrationUtils.displayDirectories(context);

    final Scanner scanner = new Scanner(System.in);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n    Please press 'q + Enter' to quit the application.    "
                + "\n                                                         "
                + "\n=========================================================");
    }

    while (!scanner.hasNext("q")) {
        //Do nothing unless user presses 'q' to quit.
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Exiting application...bye.");
    }

    System.exit(0);

}