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.example.geomesa.kafka.KafkaLoadTester.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);
    String visibility = getVisibility(cmd);
    Integer delay = getDelay(cmd);

    if (visibility == null) {
        System.out.println("visibility: null");
    } else {/*  w ww .  java2 s  .  c  o  m*/
        System.out.println("visibility: '" + visibility + "'");
    }

    // create the producer and consumer KafkaDataStore objects
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    System.out.println("KDS config: " + dsConf);
    dsConf.put("kafka.consumer.count", "0");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("kafka.consumer.count", "1");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore objects properly
    if (producerDS == null) {
        throw new Exception("Null producer KafkaDataStore");
    }
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }

    try {
        // create the schema which creates a topic in Kafka
        // (only needs to be done once)
        final String sftName = "KafkaStressTest";
        final String sftSchema = "name:String,age:Int,step:Double,lat:Double,dtg:Date,*geom:Point:srid=4326";
        SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema);
        producerDS.createSchema(sft);

        System.out.println("Register KafkaDataStore in GeoServer (Press enter to continue)");
        System.in.read();

        // the live consumer must be created before the producer writes features
        // in order to read streaming data.
        // i.e. the live consumer will only read data written after its instantiation
        SimpleFeatureStore producerFS = (SimpleFeatureStore) producerDS.getFeatureSource(sftName);
        SimpleFeatureSource consumerFS = consumerDS.getFeatureSource(sftName);

        // creates and adds SimpleFeatures to the producer every 1/5th of a second
        System.out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes");

        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(sft);

        Integer numFeats = getLoad(cmd);

        System.out.println("Building a list of " + numFeats + " SimpleFeatures.");
        List<SimpleFeature> features = IntStream.range(1, numFeats)
                .mapToObj(i -> createFeature(builder, i, visibility)).collect(Collectors.toList());

        // set variables to estimate feature production rate
        Long startTime = null;
        Long featuresSinceStartTime = 0L;
        int cycle = 0;
        int cyclesToSkip = 50000 / numFeats; // collect enough features
                                             // to get an accurate rate estimate

        while (true) {
            // write features
            features.forEach(feat -> {
                try {
                    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
                    featureCollection.add(feat);
                    producerFS.addFeatures(featureCollection);
                } catch (Exception e) {
                    System.out.println("Caught an exception while writing features.");
                    e.printStackTrace();
                }
                updateFeature(feat);
            });

            // count features written
            Integer consumerSize = consumerFS.getFeatures().size();
            cycle++;
            featuresSinceStartTime += consumerSize;
            System.out.println("At " + new Date() + " wrote " + consumerSize + " features");

            // if we've collected enough features, calculate the rate
            if (cycle >= cyclesToSkip || startTime == null) {
                Long endTime = System.currentTimeMillis();
                if (startTime != null) {
                    Long diffTime = endTime - startTime;
                    Double rate = (featuresSinceStartTime.doubleValue() * 1000.0) / diffTime.doubleValue();
                    System.out.printf("%.1f feats/sec (%d/%d)\n", rate, featuresSinceStartTime, diffTime);
                }
                cycle = 0;
                startTime = endTime;
                featuresSinceStartTime = 0L;
            }

            // sleep before next write
            if (delay != null) {
                System.out.printf("Sleeping for %d ms\n", delay);
                Thread.sleep(delay);
            }
        }

    } finally {
        producerDS.dispose();
        consumerDS.dispose();
    }
}

From source file:eu.scape_project.tb.chutney.ChutneyDriver.java

/**
 * This main runs only on the local machine when the job is initiated
 * /*from   w ww . ja v  a 2 s.co m*/
 * @param args command line arguments
 * @throws ParseException command line parse issue
 */
@SuppressWarnings("unused")
public static void main(String[] args) throws ParseException {

    System.out.println(Settings.JOB_NAME + "v" + Settings.VERSION);

    //warning code
    if (true) {
        String yes = "YeS";
        System.out.println(
                "WARNING: this code has not been fully tested and it may delete/modify/alter your systems");
        System.out.println("You run this development code at your own risk, no liability is assumed");
        System.out.print("To continue, type \"" + yes + "\": ");
        try {
            String input = new BufferedReader(new InputStreamReader(System.in)).readLine();
            if (!input.equals(yes)) {
                return;
            }
        } catch (IOException e1) {
            return;
        }
    }
    //end of warning code

    try {
        ToolRunner.run(new Configuration(), new ChutneyDriver(), args);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.bluemarsh.jswat.console.Main.java

/**
 * Kicks off the application.//from  w w  w.j  ava2  s  .c om
 *
 * @param  args  the command line arguments.
 */
public static void main(String[] args) {
    //
    // An attempt was made early on to use the Console class in java.io,
    // but that is not designed to handle asynchronous output from
    // multiple threads, so we just use the usual System.out for output
    // and System.in for input. Note that automatic flushing is used to
    // ensure output is shown in a timely fashion.
    //

    //
    // Where console mode seems to work:
    // - bash
    // - emacs
    //
    // Where console mode does not seem to work:
    // - NetBeans: output from event listeners is never shown and the
    //   cursor sometimes lags behind the output
    //

    // Turn on flushing so printing the prompt will flush
    // all buffered output generated from other threads.
    PrintWriter output = new PrintWriter(System.out, true);

    // Make sure we have the JPDA classes.
    try {
        Bootstrap.virtualMachineManager();
    } catch (NoClassDefFoundError ncdfe) {
        output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA"));
        System.exit(1);
    }

    // Ensure we can create the user directory by requesting the
    // platform service. Simply asking for it has the desired effect.
    PlatformProvider.getPlatformService();

    // Define the logging configuration.
    LogManager manager = LogManager.getLogManager();
    InputStream is = Main.class.getResourceAsStream("logging.properties");
    try {
        manager.readConfiguration(is);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(1);
    }

    // Print out some useful debugging information.
    logSystemDetails();

    // Add a shutdown hook to make sure we exit cleanly.
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            // Save the command aliases.
            CommandParser parser = CommandProvider.getCommandParser();
            parser.saveSettings();
            // Save the runtimes to persistent storage.
            RuntimeManager rm = RuntimeProvider.getRuntimeManager();
            rm.saveRuntimes();
            // Save the sessions to persistent storage and have them
            // close down in preparation to exit.
            SessionManager sm = SessionProvider.getSessionManager();
            sm.saveSessions(true);
        }
    }));

    // Initialize the command parser and load the aliases.
    CommandParser parser = CommandProvider.getCommandParser();
    parser.loadSettings();
    parser.setOutput(output);

    // Create an OutputAdapter to display debuggee output.
    OutputAdapter adapter = new OutputAdapter(output);
    SessionManager sessionMgr = SessionProvider.getSessionManager();
    sessionMgr.addSessionManagerListener(adapter);
    // Create a SessionWatcher to monitor the session status.
    SessionWatcher swatcher = new SessionWatcher();
    sessionMgr.addSessionManagerListener(swatcher);
    // Create a BreakpointWatcher to monitor the breakpoints.
    BreakpointWatcher bwatcher = new BreakpointWatcher();
    sessionMgr.addSessionManagerListener(bwatcher);

    // Add the watchers and adapters to the open sessions.
    Iterator<Session> iter = sessionMgr.iterateSessions();
    while (iter.hasNext()) {
        Session s = iter.next();
        s.addSessionListener(adapter);
        s.addSessionListener(swatcher);
    }

    // Find and run the RC file.
    try {
        runStartupFile(parser, output);
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
    }

    // Process command line arguments.
    try {
        processArguments(args);
    } catch (ParseException pe) {
        // Report the problem and keep going.
        System.err.println("Option parsing failed: " + pe.getMessage());
        logger.log(Level.SEVERE, null, pe);
    }

    // Display a helpful greeting.
    output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome"));
    if (jdbEmulationMode) {
        output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation"));
    }

    // Enter the main loop of processing user input.
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        // Keep the prompt format identical to jdb for compatibility
        // with emacs and other possible wrappers.
        output.print("> ");
        output.flush();
        try {
            String command = input.readLine();
            // A null value indicates end of stream.
            if (command != null) {
                performCommand(output, parser, command);
            }
            // Sleep briefly to give the event processing threads,
            // and the automatic output flushing, a chance to catch
            // up before printing the input prompt again.
            Thread.sleep(250);
        } catch (InterruptedException ie) {
            logger.log(Level.WARNING, null, ie);
        } catch (IOException ioe) {
            logger.log(Level.SEVERE, null, ioe);
            output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe));
        } catch (Exception x) {
            // Don't ever let an internal bug (e.g. in the command parser)
            // hork the console, as it really irritates people.
            logger.log(Level.SEVERE, null, x);
            output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x));
        }
    }
}

From source file:it.unimi.di.big.mg4j.tool.URLMPHVirtualDocumentResolver.java

public static void main(final String[] arg) throws JSAPException, IOException {
    final SimpleJSAP jsap = new SimpleJSAP(URLMPHVirtualDocumentResolver.class.getName(),
            "Builds a URL document resolver from a sequence of URIs, extracted typically using ScanMetadata, using a suitable function. You can specify that the list is sorted, in which case it is possible to generate a resolver that occupies less space.",
            new Parameter[] {
                    new Switch("sorted", 's', "sorted",
                            "URIs are sorted: use a monotone minimal perfect hash function."),
                    new Switch("iso", 'i', "iso",
                            "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)."),
                    new FlaggedOption("bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b',
                            "buffer-size", "The size of the I/O buffer used to read terms."),
                    new FlaggedOption("class", MG4JClassParser.getParser(), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'c', "class",
                            "A class used to create the function from URIs to their ranks; defaults to it.unimi.dsi.sux4j.mph.MHWCFunction for non-sorted inputs, and to it.unimi.dsi.sux4j.mph.TwoStepsLcpMonotoneMinimalPerfectHashFunction for sorted inputs."),
                    new FlaggedOption("width", JSAP.INTEGER_PARSER, Integer.toString(Long.SIZE),
                            JSAP.NOT_REQUIRED, 'w', "width",
                            "The width, in bits, of the signatures used to sign the function from URIs to their rank."),
                    new FlaggedOption("termFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o',
                            "offline",
                            "Read terms from this file (without loading them into core memory) instead of standard input."),
                    new FlaggedOption("uniqueUris", JSAP.INTSIZE_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED,
                            'U', "unique-uris",
                            "Force URIs to be unique by adding random garbage at the end of duplicates; the argument is an upper bound for the number of URIs that will be read, and will be used to create a Bloom filter."),
                    new UnflaggedOption("resolver", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED,
                            JSAP.NOT_GREEDY, "The filename for the resolver.") });

    JSAPResult jsapResult = jsap.parse(arg);
    if (jsap.messagePrinted())
        return;// w  ww .  ja  v  a 2 s .co  m

    final int bufferSize = jsapResult.getInt("bufferSize");
    final String resolverName = jsapResult.getString("resolver");
    //final Class<?> tableClass = jsapResult.getClass( "class" );
    final boolean iso = jsapResult.getBoolean("iso");
    String termFile = jsapResult.getString("termFile");

    BloomFilter<Void> filter = null;
    final boolean uniqueURIs = jsapResult.userSpecified("uniqueUris");
    if (uniqueURIs)
        filter = BloomFilter.create(jsapResult.getInt("uniqueUris"));

    final Collection<? extends CharSequence> collection;
    if (termFile == null) {
        ArrayList<MutableString> termList = new ArrayList<MutableString>();
        final ProgressLogger pl = new ProgressLogger();
        pl.itemsName = "URIs";
        final LineIterator termIterator = new LineIterator(
                new FastBufferedReader(new InputStreamReader(System.in, "UTF-8"), bufferSize), pl);

        pl.start("Reading URIs...");
        MutableString uri;
        while (termIterator.hasNext()) {
            uri = termIterator.next();
            if (uniqueURIs)
                makeUnique(filter, uri);
            termList.add(uri.copy());
        }
        pl.done();

        collection = termList;
    } else {
        if (uniqueURIs) {
            // Create temporary file with unique URIs
            final ProgressLogger pl = new ProgressLogger();
            pl.itemsName = "URIs";
            pl.start("Copying URIs...");
            final LineIterator termIterator = new LineIterator(
                    new FastBufferedReader(new InputStreamReader(new FileInputStream(termFile)), bufferSize),
                    pl);
            File temp = File.createTempFile(URLMPHVirtualDocumentResolver.class.getName(), ".uniqueuris");
            temp.deleteOnExit();
            termFile = temp.toString();
            final FastBufferedOutputStream outputStream = new FastBufferedOutputStream(
                    new FileOutputStream(termFile), bufferSize);
            MutableString uri;
            while (termIterator.hasNext()) {
                uri = termIterator.next();
                makeUnique(filter, uri);
                uri.writeUTF8(outputStream);
                outputStream.write('\n');
            }
            pl.done();
            outputStream.close();
        }
        collection = new FileLinesCollection(termFile, "UTF-8");
    }
    LOGGER.debug("Building function...");
    final int width = jsapResult.getInt("width");
    if (jsapResult.getBoolean("sorted"))
        BinIO.storeObject(
                new URLMPHVirtualDocumentResolver(
                        new ShiftAddXorSignedStringMap(collection.iterator(),
                                new TwoStepsLcpMonotoneMinimalPerfectHashFunction<CharSequence>(collection,
                                        iso ? TransformationStrategies.prefixFreeIso()
                                                : TransformationStrategies.prefixFreeUtf16()),
                                width)),
                resolverName);
    else
        BinIO.storeObject(
                new URLMPHVirtualDocumentResolver(new ShiftAddXorSignedStringMap(collection.iterator(),
                        new MWHCFunction<CharSequence>(collection,
                                iso ? TransformationStrategies.iso() : TransformationStrategies.utf16()),
                        width)),
                resolverName);
    LOGGER.debug(" done.");
}

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

/**
 * @param args/*from w w  w  .java2 s . co  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 Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "Output filename.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_STARTTorsion, true,
            "The torsion in your inMol will be rotated by this value for the first job");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONIncrement, true, "Incremnt each subsequent conformation by this step size");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_NSTEPS, true, "Number of conformations to create");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_BONDFILE, true, "The file containing the bond atoms that define the torsion.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_MINIMIZE, false,
            "Minimize conformer at each step using MMFFs.  If maxConfsPerStep is > 1, "
                    + "all confs will be mimimized and the lowest E will be output.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_CONSTRIANT, true,
            "One of strong (90), medium (45), weak(20), none or a floating point number"
                    + " to specify the tethered constraint strength for -minimize (def=strong)");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_MAXCONFS_PER_STEP, true,
            "While holding the torsion fixed, maximum number of conformations of free atoms to generat.  default=1");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_COREFILE, true, "Outputfile to store guessed core.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_TORSIONS_ATOM_TAG, true,
            "Name of sdf tag which will contain the indices of atoms that define the torsion.");
    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 (args.length != 0) {
        System.err.println("Unknown arguments" + args);
        exitWithHelp(options);
    }

    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 bondFile = cmd.getOptionValue(OPT_BONDFILE);
    String coreFilename = cmd.getOptionValue(OPT_COREFILE);
    String torsionAtomsTag = cmd.getOptionValue(OPT_TORSIONS_ATOM_TAG);

    int nSteps = Integer.parseInt(cmd.getOptionValue(OPT_NSTEPS));
    int nStartTor = Integer.parseInt(cmd.getOptionValue(OPT_STARTTorsion));
    int nTorIncr = Integer.parseInt(cmd.getOptionValue(OPT_TORSIONIncrement));

    int nMaxConfsPerStep = 1;
    if (cmd.hasOption(OPT_MAXCONFS_PER_STEP)) {
        nMaxConfsPerStep = Integer.parseInt(cmd.getOptionValue(OPT_MAXCONFS_PER_STEP));
    }

    String constraintStrength = cmd.getOptionValue(OPT_CONSTRIANT);

    boolean doMinimize = cmd.hasOption(OPT_MINIMIZE);

    SDFTorsionScanner torGenerator = new SDFTorsionScanner(bondFile, coreFilename, torsionAtomsTag, nSteps,
            nStartTor, nTorIncr, nMaxConfsPerStep, doMinimize, constraintStrength);

    torGenerator.run(inFile, outFile, coreFilename);
}

From source file:com.genentech.retrival.SDFExport.SDFExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(true);//  ww  w. ja v a2s.co  m
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("molSqlName", true,
            "name of SQL element in xml file returning molfile for first column in sqlName");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("removeSalt", false, "remove any known salts from structure.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("o", "out", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("i", "in", true,
            "input file, tab separated, each line executes the query once. Use '.tab' to read from stdin");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("ignoreMismatches", false, "If not given each input must return at least one hit hits.");
    options.addOption(opt);

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

    String outFile = cmd.getOptionValue("o");
    String inFile = cmd.getOptionValue("i");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String molSqlName = cmd.getOptionValue("molSqlName");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");

    boolean removeSalt = cmd.hasOption("removeSalt");
    boolean ignoreMismatches = cmd.hasOption("ignoreMismatches");

    SDFExporter exporter = null;
    try {
        exporter = new SDFExporter(sqlFile, sqlName, molSqlName, outFile, newLineReplacement, removeSalt,
                ignoreMismatches);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println();
        exitWithHelp(options);
    }

    args = cmd.getArgs();

    if (inFile != null && args.length > 0) {
        System.err.println("inFile and arguments may not be mixed!\n");
        exitWithHelp(options);
    }

    if (inFile == null) {
        if (exporter.getParamTypes().length != args.length) {
            System.err.printf("sql statement (%s) needs %d parameters but got only %d.\n", sqlName,
                    exporter.getParamTypes().length, args.length);
            exitWithHelp(options);
        }

        exporter.export(args);
    } else {
        BufferedReader in;
        if (".tab".equalsIgnoreCase(inFile))
            in = new BufferedReader(new InputStreamReader(System.in));
        else
            in = new BufferedReader(new FileReader(inFile));

        exporter.export(in);
        in.close();
    }

    exporter.close();
}

From source file:it.nibbles.javacoin.BlockTool.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help");
    parser.accepts("import");
    parser.accepts("export");
    parser.accepts("testnet2");
    parser.accepts("testnet3");
    parser.accepts("prodnet");
    parser.accepts("first").withRequiredArg().ofType(Integer.class);
    parser.accepts("last").withRequiredArg().ofType(Integer.class);
    parser.accepts("hash").withRequiredArg();
    parser.accepts("port").withRequiredArg().ofType(Integer.class);
    optBdbPath = parser.accepts("bdbPath").withRequiredArg().defaultsTo("data");
    //optJdbcDriver = parser.accepts("driver").withRequiredArg().defaultsTo("com.mysql.jdbc.Driver");
    optJdbcUrl = parser.accepts("url").withRequiredArg().defaultsTo("jdbc:mysql://localhost/javacoin_testnet3");
    optJdbcUser = parser.accepts("dbuser").withRequiredArg().defaultsTo("javacoin");
    optJdbcPassword = parser.accepts("dbpass").withRequiredArg().defaultsTo("pw");
    inputfile = parser.accepts("inputfile").withRequiredArg();
    outputfile = parser.accepts("outputfile").withRequiredArg();
    //    String[] args = {
    //      "--inputfile", "blocks-0-100000.txt", "--prodnet", "--load", "--url", "jdbc:mysql://localhost/javacoin_test"
    //    };//w  ww.  ja v a2s . c om
    OptionSet options = parser.parse(args);
    if (args.length == 0 || options.hasArgument("help") || options.nonOptionArguments().size() > 0
            || (options.has("export") && options.has("import"))
            || (options.has("export") && !options.has("outputfile"))
            || (options.has("import") && !options.has("inputfile"))
            || (options.has("testnet2") && options.has("testnet3"))
            || (options.has("testnet2") && options.has("prodnet"))
            || (options.has("testnet3") && options.has("prodnet"))) {
        println(HELP_TEXT);
        return;
    }
    if (options.hasArgument("port")) {
        //listenPort = ((Integer) options.valueOf("port")).intValue();
    }
    cmdExportBlockchain = options.has("export");
    cmdImportBlockchain = options.has("import");
    isProdnet = options.has("prodnet");
    isTestNet2 = options.has("testnet2");
    isTestNet3 = options.has("testnet3");
    if (!isProdnet && !isTestNet2 && !isTestNet3)
        isTestNet3 = true;
    if (options.hasArgument("first")) {
        firstBlock = ((Integer) options.valueOf("first")).intValue();
        if (!options.hasArgument("last"))
            lastBlock = firstBlock;
    }
    if (options.hasArgument("last")) {
        lastBlock = ((Integer) options.valueOf("last")).intValue();
        if (!options.hasArgument("first"))
            firstBlock = lastBlock;
    }
    if (options.hasArgument("hash"))
        blockHash = (String) options.valueOf("hash");
    if (cmdExportBlockchain && blockHash == null && firstBlock == 0 && lastBlock == 0) {
        println("To save blocks you have to specify a range or an hash");
        return;
    }

    //println("save: " + cmdSaveBlockchain + " load: " + cmdLoadBlockchain + " prodnet: " + isProdnet + " testnet2: " + isTestNet2 + " testnet3: " + isTestNet3);
    //println("FirstBlock: " + firstBlock + " lastBlock: " + lastBlock + " inputfile: " + inputfile.value(options) + " outputfile: " + outputfile.value(options));
    BlockTool app = new BlockTool();
    app.init(options);
    if (cmdImportBlockchain) {
        //System.out.println("Press return to start import blocks to blockchain");
        //System.in.read();
        BufferedReader reader;
        if ("-".equals(inputfile.value(options)))
            reader = new BufferedReader(new InputStreamReader(System.in));
        else
            reader = new BufferedReader(new FileReader(inputfile.value(options)));
        int numBlocks = 0;
        Block block = app.readBlock(reader, false);
        while (block != null) {
            numBlocks++;
            long startTime = System.currentTimeMillis();
            blockChain.addBlock(block);
            long insertTime = System.currentTimeMillis() - startTime;
            System.out.printf(
                    "%6d Block " + BtcUtil.hexOut(block.getHash()) + " #txs: %4d insertTime(ms): %d%n",
                    block.getTransactions().size(), insertTime);
            block = app.readBlock(reader, false);
        }
        System.out.println("Numero blocchi letti: " + numBlocks);
    } else if (cmdExportBlockchain) {
        BlockChainLink blockLink;
        try (PrintWriter writer = new PrintWriter(new File(outputfile.value(options)))) {
            if (blockHash != null) {
                blockLink = storage.getLink(BtcUtil.hexIn(blockHash));
                app.writeBlock(writer, blockLink.getBlock());
            } else {
                for (int i = firstBlock; i <= lastBlock; i++) {
                    blockLink = storage.getLinkAtHeight(i);
                    app.writeBlock(writer, blockLink.getBlock());
                }
            }
        }
    }
    app.close();
}

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

/**
 * @param args//from   w ww  .  ja va 2  s  .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 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_REFFILE, true,
            "Reference file of molecules which define pre-existign exclusion spheres.");
    options.addOption(opt);

    opt = new Option(OPT_RADIUS, true, "Radius of exclusion spehre in A2.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_GROUPBY, true,
            "Group by fieldname, run sphere exclusion for consecutive groups of records with same value for this field.");
    options.addOption(opt);

    opt = new Option(OPT_DONotOpt, false,
            "If specified the RMSD is computed without trying to optimize the alignment.");
    options.addOption(opt);

    opt = new Option(OPT_PRINT_All, false, "print all molecule, check includeIdx tag");
    options.addOption(opt);

    opt = new Option(OPT_MIRROR, false, "For non-chiral molecules also try mirror image");
    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 refFile = cmd.getOptionValue(OPT_REFFILE);
    String groupBy = cmd.getOptionValue(OPT_GROUPBY);
    boolean doOptimize = !cmd.hasOption(OPT_DONotOpt);
    double radius = Double.parseDouble(cmd.getOptionValue(OPT_RADIUS));
    boolean printAll = cmd.hasOption(OPT_PRINT_All);
    boolean doMirror = cmd.hasOption(OPT_MIRROR);

    SdfRMSDSphereExclusion sphereExclusion = new SdfRMSDSphereExclusion(refFile, outFile, radius, printAll,
            doMirror, doOptimize, groupBy);

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

From source file:edu.asu.bscs.csiebler.waypointapplication.WaypointServerStub.java

/**
 *
 * @param args//from w  w w  . j ava2 s.  c  om
 */
public static void main(String args[]) {
    try {
        String url = "http://127.0.0.1:8080/";

        if (args.length > 0) {
            url = args[0];
        }

        WaypointServerStub cjc = new WaypointServerStub(url);
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print(
                "Enter end or {remove|get|getNames|getCategoryNames|getNamesInCategory|dist|bear} arg1 arg2 eg  remove Toreros >");
        String inStr = stdin.readLine();
        StringTokenizer st = new StringTokenizer(inStr);
        String opn = st.nextToken();

        while (!opn.equalsIgnoreCase("end")) {
            switch (opn) {
            case "remove": {
                boolean result = cjc.remove(st.nextToken());
                System.out.println("response: " + result);
                break;
            }
            case "get": {
                Waypoint result = cjc.get(st.nextToken());
                System.out.println("response: " + result.toJsonString());
                break;
            }
            case "getNames": {
                String[] result = cjc.getNames();
                for (int i = 0; i < result.length; i++) {
                    System.out.println("response[" + i + "] is " + result[i]);
                }
                break;
            }
            case "getCategoryNames": {
                String[] result = cjc.getCategoryNames();
                for (int i = 0; i < result.length; i++) {
                    System.out.println("response[" + i + "] is " + result[i]);
                }
                break;
            }
            case "getNamesInCategory": {
                String[] result = cjc.getNamesInCategory(st.nextToken());
                for (int i = 0; i < result.length; i++) {
                    System.out.println("response[" + i + "] is " + result[i]);
                }
                break;
            }
            case "dist": {
                double result = cjc.distanceGCTo(st.nextToken(), st.nextToken());
                System.out.println("response: " + result);
                break;
            }
            case "bear": {
                double result = cjc.bearingGCInitTo(st.nextToken(), st.nextToken());
                System.out.println("response: " + result);
                break;
            }
            default: {
                break;
            }
            }

            System.out.print(
                    "Enter end or {remove|get|getNames|getCategoryNames|getNamesInCategory|dist|bear} arg1 arg2 eg  remove Toreros >");
            inStr = stdin.readLine();
            st = new StringTokenizer(inStr);
            opn = st.nextToken();
        }
    } catch (Exception e) {
        System.out.println("Oops, you didn't enter the right stuff");
    }
}

From source file:com.ibm.cics.ca1y.Emit.java

/**
 * Format a request from the JVM standard in and command line arguments. Each line in standard in, or argument on
 * the command line should follow the conventions required to be loaded by the Java Properties class, eg. name=value
 * /*from  w w  w.j  a  v a 2 s . com*/
 * @param args
 *            - zero or more arguments specified on the command line
 * @return exit code - 0 if successfull, non-zero if there was at least one problem actioning the request
 */
public static void main(String[] args) {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine(messages.getString("EmitStart"));
    }

    EmitProperties props = new EmitProperties();

    addPropertiesFromInputStream(props, System.in);

    addPropertiesFromString(props, args);

    boolean returnCode = Emit.emit(props, null, false);

    if (logger.isLoggable(Level.FINE)) {
        logger.fine(messages.getString("EmitFinish"));
    }

    System.exit(returnCode ? 0 : 8);
}