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:calendarevent.CalendarEvent.java

/**
 * @param args the command line arguments
 *//*from w  w  w. j ava 2  s  . c o  m*/
public static void main(String[] args) {
    // TODO code application logic here

    /*       
                
        This has to be replaced with the json data coming from the getJsonData() method
        Expecting the Json will be in the format from the above methid.
                
    */
    String jsonString = "{\n" + " \"kind\": \"calendar#events\",\n"
            + " \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/QElT1PHkP9d3G5VSndpdEMlSzKE\\\"\",\n"
            + " \"summary\": \"PushEvents\",\n" + " \"description\": \"Hackathon\",\n"
            + " \"updated\": \"2014-03-29T22:35:18.495Z\",\n" + " \"timeZone\": \"Asia/Calcutta\",\n"
            + " \"accessRole\": \"reader\",\n" + " \"items\": [\n" + "  {\n"
            + "   \"kind\": \"calendar#event\",\n"
            + "   \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEyNTQwNzcxMTAwMA\\\"\",\n"
            + "   \"id\": \"q28lprjb8ad3m17955lf1p9d48\",\n" + "   \"status\": \"confirmed\",\n"
            + "   \"htmlLink\": \"https://www.google.com/calendar/event?eid=cTI4bHByamI4YWQzbTE3OTU1bGYxcDlkNDggM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n"
            + "   \"created\": \"2014-03-29T20:36:47.000Z\",\n"
            + "   \"updated\": \"2014-03-29T20:36:47.711Z\",\n" + "   \"summary\": \"Test API\",\n"
            + "   \"creator\": {\n" + "    \"email\": \"vrohitrao@gmail.com\",\n"
            + "    \"displayName\": \"Rohith Vallu\"\n" + "   },\n" + "   \"organizer\": {\n"
            + "    \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n"
            + "    \"displayName\": \"PushEvents\",\n" + "    \"self\": true\n" + "   },\n"
            + "   \"start\": {\n" + "    \"dateTime\": \"2014-03-30T02:30:00+05:30\"\n" + "   },\n"
            + "   \"end\": {\n" + "    \"dateTime\": \"2014-03-30T03:30:00+05:30\"\n" + "   },\n"
            + "   \"iCalUID\": \"q28lprjb8ad3m17955lf1p9d48@google.com\",\n" + "   \"sequence\": 0\n" + "  },\n"
            + "  {\n" + "   \"kind\": \"calendar#event\",\n"
            + "   \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEzMjUzMjQxNzAwMA\\\"\",\n"
            + "   \"id\": \"jgpue3stuo3js5qlsodob84voo\",\n" + "   \"status\": \"confirmed\",\n"
            + "   \"htmlLink\": \"https://www.google.com/calendar/event?eid=amdwdWUzc3R1bzNqczVxbHNvZG9iODR2b28gM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n"
            + "   \"created\": \"2014-03-29T22:35:32.000Z\",\n"
            + "   \"updated\": \"2014-03-29T22:35:32.417Z\",\n" + "   \"summary\": \"Test Events\",\n"
            + "   \"description\": \"Hack!!\",\n"
            + "   \"location\": \"Northeastern University, Huntington Avenue, Boston, MA, United States\",\n"
            + "   \"creator\": {\n" + "    \"email\": \"vrohitrao@gmail.com\",\n"
            + "    \"displayName\": \"Rohith Vallu\"\n" + "   },\n" + "   \"organizer\": {\n"
            + "    \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n"
            + "    \"displayName\": \"PushEvents\",\n" + "    \"self\": true\n" + "   },\n"
            + "   \"start\": {\n" + "    \"dateTime\": \"2014-03-30T04:30:00+05:30\"\n" + "   },\n"
            + "   \"end\": {\n" + "    \"dateTime\": \"2014-03-30T19:30:00+05:30\"\n" + "   },\n"
            + "   \"visibility\": \"public\",\n"
            + "   \"iCalUID\": \"jgpue3stuo3js5qlsodob84voo@google.com\",\n" + "   \"sequence\": 0\n" + "  }\n"
            + " ]\n" + "}";

    Gson gson = new Gson();
    try {
        JSONObject jsonData = new JSONObject(jsonString);
        JSONArray jsonArray = jsonData.getJSONArray("items");
        JSONObject eventData;
        Event event = new Event();
        for (int i = 0; i < jsonArray.length(); i++) {

            System.out.println(jsonArray.get(i).toString());
            Items item = gson.fromJson(jsonArray.get(i).toString(), Items.class);

            event.setSummary(item.getSummary());
            event.setLocation(item.getLocation());

            /* Will be adding the attendees here
             ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>();
             attendees.add(new EventAttendee().setEmail("attendeeEmail"));
             // ...
             event.setAttendees(attendees);
             */
            Date startDate = new Date();
            Date endDate = new Date(startDate.getTime() + 3600000);
            DateTime start = new DateTime(startDate, TimeZone.getDefault().getDefault().getTimeZone("UTC"));
            event.setStart(new EventDateTime().setDateTime(start));
            DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
            event.setEnd(new EventDateTime().setDateTime(end));
            HttpTransport transport = new NetHttpTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            Calendar.Builder builder = new Calendar.Builder(transport, jsonFactory, null);
            String clientID = "937140966210.apps.googleusercontent.com";
            String redirectURL = "urn:ietf:wg:oauth:2.0:oob";
            String clientSecret = "qMFSb_cadYDG7uh3IDXWiMQY";
            ArrayList<String> scope = new ArrayList<String>();
            scope.add("https://www.googleapis.com/auth/calendar");

            String url = new GoogleAuthorizationCodeRequestUrl(clientID, redirectURL, scope).build();

            System.out.println("Go to the following link in your browser:");
            System.out.println(url);

            // Read the authorization code from the standard input stream.
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What is the authorization code?");
            String code = in.readLine();

            GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory,
                    clientID, clientSecret, redirectURL, code, redirectURL).execute();

            GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

            Calendar service = new Calendar.Builder(transport, jsonFactory, credential).build();

            Event createdEvent = service.events().insert(item.getSummary(), event).execute();

            System.out.println(createdEvent.getId());

        }

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

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

/**
 * @param args//  w  w w .  j  a v a2s. 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);
    opt.setArgName("fn");
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    opt.setArgName("fn");
    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();
    }

    if (args.length == 0) {
        System.err.println("Specify at least one index type");
        exitWithHelp(options);
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    Set<String> selectedIndexes = new HashSet<String>(args.length);
    if (args.length == 1 && "all".equalsIgnoreCase(args[0]))
        selectedIndexes = AVAILIndexes;
    else
        selectedIndexes.addAll(Arrays.asList(args));

    if (!AVAILIndexes.containsAll(selectedIndexes)) {
        selectedIndexes.removeAll(AVAILIndexes);
        StringBuilder err = new StringBuilder("Unknown Index types: ");
        for (String it : selectedIndexes)
            err.append(it).append(" ");
        System.err.println(err);
        exitWithHelp(options);
    }

    SDFTopologicalIndexer sdfIndexer = new SDFTopologicalIndexer(outFile, selectedIndexes);

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

From source file:fr.ippon.pamelaChu.test.support.LdapTestServer.java

/**
 * Main class. We just do a lookup on the server to check that it's available.
 * <p/>/* w ww.  j a  v a 2  s. c o m*/
 * FIXME : in Eclipse : when running this classes as "Java Application", target/test-classes is not added in the classpath
 * resulting in a java.lang.ClassNotFoundException ...
 *
 * @param args Not used.
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    FileUtils.deleteDirectory(workingDir);

    LdapTestServer ads = null;
    try {
        // Create the server
        ads = new LdapTestServer();
        ads.start();

        // Read an entry
        Entry result = ads.service.getAdminSession().lookup(new LdapDN("dc=ippon,dc=fr"));

        // And print it if available
        System.out.println("Found entry : " + result);

    } catch (Exception e) {
        // Ok, we have something wrong going on ...
        e.printStackTrace();
    }
    System.out.println("Press enter");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    ads.stop();
}

From source file:com.example.geomesa.kafka08.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);

    if (visibility == null) {
        System.out.println("visibility: null");
    } else {//from  www  .j  a v a  2s  .  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("isProducer", "true");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("isProducer", "false");
    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");
    }

    // 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);
    // set zkPath to default if not specified
    String zkPath = (dsConf.get(ZK_PATH) == null) ? "/geomesa/ds/kafka" : dsConf.get(ZK_PATH);
    SimpleFeatureType preppedOutputSft = KafkaDataStoreHelper.createStreamingSFT(sft, zkPath);
    // only create the schema if it hasn't been created already
    if (!Arrays.asList(producerDS.getTypeNames()).contains(sftName))
        producerDS.createSchema(preppedOutputSft);

    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;
        }
    }
}

From source file:com.act.biointerpretation.BiointerpretationDriver.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());// w ww. j  a v  a2s . c om
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    if (cl.hasOption(OPTION_CONFIGURATION_FILE)) {
        List<BiointerpretationStep> steps;
        File configFile = new File(cl.getOptionValue(OPTION_CONFIGURATION_FILE));
        if (!configFile.exists()) {
            String msg = String.format("Cannot find configuration file at %s", configFile.getAbsolutePath());
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        // Read the whole config file.
        try (InputStream is = new FileInputStream(configFile)) {
            steps = OBJECT_MAPPER.readValue(is, new TypeReference<List<BiointerpretationStep>>() {
            });
        } catch (IOException e) {
            LOGGER.error("Caught IO exception when attempting to read configuration file: %s", e.getMessage());
            throw e; // Crash after logging if the config file can't be read.
        }

        // Ask for explicit confirmation before dropping databases.
        LOGGER.info("Biointerpretation plan:");
        for (BiointerpretationStep step : steps) {
            crashIfInvalidDBName(step.getReadDBName());
            crashIfInvalidDBName(step.getWriteDBName());
            LOGGER.info("%s: %s -> %s", step.getOperation(), step.getReadDBName(), step.getWriteDBName());
        }
        LOGGER.warn("WARNING: each DB to be written will be dropped before the writing step commences");
        LOGGER.info("Proceed? [y/n]");
        String readLine;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            readLine = reader.readLine();
        }
        readLine.trim();
        if ("y".equalsIgnoreCase(readLine) || "yes".equalsIgnoreCase(readLine)) {
            LOGGER.info("Biointerpretation plan confirmed, commencing");
            for (BiointerpretationStep step : steps) {
                performOperation(step, true);
            }
            LOGGER.info("Biointerpretation plan completed");
        } else {
            LOGGER.info("Biointerpretation plan not confirmed, exiting");
        }
    } else if (cl.hasOption(OPTION_SINGLE_OPERATION)) {
        if (!cl.hasOption(OPTION_SINGLE_READ_DB) || !cl.hasOption(OPTION_SINGLE_WRITE_DB)) {
            String msg = "Must specify read and write DB names when performing a single operation";
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        BiointerpretationOperation operation;
        try {
            operation = BiointerpretationOperation.valueOf(cl.getOptionValue(OPTION_SINGLE_OPERATION));
        } catch (IllegalArgumentException e) {
            LOGGER.error("Caught IllegalArgumentException when trying to parse operation '%s': %s",
                    cl.getOptionValue(OPTION_SINGLE_OPERATION), e.getMessage());
            throw e; // Crash if we can't interpret the operation.
        }
        String readDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_READ_DB));
        String writeDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_WRITE_DB));

        performOperation(new BiointerpretationStep(operation, readDB, writeDB), false);
    } else {
        String msg = "Must specify either a config file or a single operation to perform.";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }
}

From source file:com.aestel.chemistry.openEye.fp.Fingerprinter.java

public static void main(String... args) throws IOException {
    long start = System.currentTimeMillis();
    long iCounter = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input file [.ism,.sdf,...]");
    opt.setRequired(true);//from   www. j a va2  s  . c om
    options.addOption(opt);

    opt = new Option("out", true, "output file .tsv or oe-supported");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("idTag", true, "field with ID (default title)");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("fpType", true, "fingerPrintType: maccs|linear7|linear7*4|HashLinear7*4\n"
            + "   maccs: generate maccs keys\n"
            + "   linear7 generate 7 bonds long linear fingerprints (210k known rest hashed)\n"
            + "   linear7*4 linear 7 bonds if more than 4 atoms code atoms as * (5.1k known rest hashed)\n"
            + "   HashLinear7*4: as linear7*4 but hashed to 16k");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("format", true,
            "folded512|folded2048|bitList|fragList|none\n" + "   folded512/2048: hex encoded 512/2048 bits\n"
                    + "   bitList: list of bitpositions\n" + "   none: no fp output for use with writeCodeMap");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("writeCodeMap", false, "Overwrite the codeMap file at the end of processing");
    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 idTag = null;
    if (cmd.hasOption("idTag"))
        idTag = cmd.getOptionValue("idTag");

    String outformat = cmd.getOptionValue("format").toLowerCase().intern();
    if (args.length != 0) {
        exitWithHelp(options);
    }

    String type = cmd.getOptionValue("fpType");
    boolean updateDictionaryFile = cmd.hasOption("writeCodeMap");
    boolean hashUnknownFrag = true;
    if (type.equals("HashLinear7*4"))
        hashUnknownFrag = false;
    if (type.equals("maccs"))
        hashUnknownFrag = false;
    if (updateDictionaryFile)
        hashUnknownFrag = false;
    Fingerprinter fprinter = createFingerprinter(type, updateDictionaryFile, hashUnknownFrag);
    OEMolBase mol = new OEGraphMol();

    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    oemolistream ifs = new oemolistream(inFile);

    Runtime rt = Runtime.getRuntime();
    Outputter out;
    if (outFile.endsWith(".txt") || outFile.endsWith(".tab"))
        out = new TabOutputter(fprinter.getMapper(), outFile, outformat);
    else
        out = new OEOutputter(fprinter.getMapper(), outFile, type, outformat);

    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;
        Fingerprint fp = fprinter.getFingerprint(mol);

        String id;
        if (idTag == null)
            id = mol.GetTitle();
        else
            id = oechem.OEGetSDData(mol, idTag);

        if (iCounter % 100 == 0)
            System.err.print(".");
        if (iCounter % 4000 == 0) {
            System.err.printf(" %d %dsec\tt=%d f=%d u=%d m=%d tf=%d\n", iCounter,
                    (System.currentTimeMillis() - start) / 1000, rt.totalMemory() / 1024,
                    rt.freeMemory() / 1024, (rt.totalMemory() - rt.freeMemory()) / 1024, rt.maxMemory() / 1024,
                    (rt.freeMemory() + (rt.maxMemory() - rt.totalMemory())) / 1024);
        }

        out.output(id, mol, fp);
    }

    System.err.printf("Fingerprinter: Read %d structures in %d sec\n", iCounter,
            (System.currentTimeMillis() - start) / 1000);

    if (updateDictionaryFile)
        fprinter.writeDictionary();
    out.close();
    fprinter.close();
}

From source file:com.splout.db.dnode.TCPStreamer.java

/**
 * This main method can be used for testing the TCP interface directly to a
 * local DNode. Will ask for protocol input from Stdin and print output to
 * Stdout/*from   w ww  .  j ava2 s .  co  m*/
 */
public static void main(String[] args) throws UnknownHostException, IOException, SerializationException {
    SploutConfiguration config = SploutConfiguration.get();
    Socket clientSocket = new Socket("localhost", config.getInt(DNodeProperties.STREAMING_PORT));

    DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
    DataOutputStream outToServer = new DataOutputStream(
            new BufferedOutputStream(clientSocket.getOutputStream()));

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter tablespace: ");
    String tablespace = reader.readLine();

    System.out.println("Enter version number: ");
    long versionNumber = Long.parseLong(reader.readLine());

    System.out.println("Enter partition: ");
    int partition = Integer.parseInt(reader.readLine());

    System.out.println("Enter query: ");
    String query = reader.readLine();

    outToServer.writeUTF(tablespace);
    outToServer.writeLong(versionNumber);
    outToServer.writeInt(partition);
    outToServer.writeUTF(query);

    outToServer.flush();

    byte[] buffer = new byte[0];
    boolean read;
    do {
        read = false;
        int nBytes = inFromServer.readInt();
        if (nBytes > 0) {
            buffer = new byte[nBytes];
            int inRead = inFromServer.read(buffer);
            if (inRead > 0) {
                Object[] res = ResultSerializer.deserialize(ByteBuffer.wrap(buffer), Object[].class);
                read = true;
                System.out.println(Arrays.toString(res));
            }
        }
    } while (read);

    clientSocket.close();
}

From source file:jackrabbit.app.App.java

public static void main(String[] args) {
    if (args.length == 0 || args.length == 1 && args[0].equals("-h")) {
        System.out.println("Usage: java -jar ackrabbit-migration-query-tool-" + VERSION
                + "-jar-with-dependencies.jar "
                + "--src src --src-conf conf [--src-repo-path path] [--src-user src_user] [--src-passwd src_pw] "
                + "[--dest-user dest_user] [--dest-passwd dest_pw] [--dest dest] [--dest-conf conf] [--dest-repo-path path] "
                + "[--cnd cnd] [--node-limit limit] " + "[--query-type type] [--query query]");
        System.out.println("\t --src source repository directory");
        System.out.println("\t --src-conf source repository configuration file");
        System.out.println("\t --src-repo-path path to source node to copy from; default is \"/\"");
        System.out.println("\t --src-user source repository login");
        System.out.println("\t --src-passwd source repository password");
        System.out.println("\t --dest destination repository directory");
        System.out.println("\t --dest-conf destination repository configuration file");
        System.out.println("\t --dest-repo-path path to destination node to copy to; default is \"/\"");
        System.out.println("\t --dest-user destination repository login");
        System.out.println("\t --dest-passwd destination repository password");
        System.out.println(//from w  w w . j ava2 s  . c  o  m
                "\t --node-limit size to partition nodes with before copying. If it is not supplied, no partitioning is performed");
        System.out.println("\t --cnd common node type definition file");
        System.out.println(
                "\t --query query to run in src. If --query is specified, then --dest, --dest-conf, --dest-repo-path and --cnd will be ignored.");
        System.out.println("\t --query-type query type (sql, xpath, JCR-SQL2); default is JCR-SQL2");
        return;
    }
    for (int i = 0; i < args.length; i = i + 2) {
        if (args[i].equals("--src") && i + 1 < args.length) {
            srcRepoDir = args[i + 1];
        } else if (args[i].equals("--dest") && i + 1 < args.length) {
            destRepoDir = args[i + 1];
        } else if (args[i].equals("--src-conf") && i + 1 < args.length) {
            srcConf = args[i + 1];
        } else if (args[i].equals("--dest-conf") && i + 1 < args.length) {
            destConf = args[i + 1];
        } else if (args[i].equals("--src-repo-path") && i + 1 < args.length) {
            srcRepoPath = args[i + 1];
        } else if (args[i].equals("--dest-repo-path") && i + 1 < args.length) {
            destRepoPath = args[i + 1];
        } else if (args[i].equals("--src-user") && i + 1 < args.length) {
            srcUser = args[i + 1];
        } else if (args[i].equals("--src-passwd") && i + 1 < args.length) {
            srcPasswd = args[i + 1];
        } else if (args[i].equals("--dest-user") && i + 1 < args.length) {
            destUser = args[i + 1];
        } else if (args[i].equals("--dest-passwd") && i + 1 < args.length) {
            destPasswd = args[i + 1];
        } else if (args[i].equals("--node-limit") && i + 1 < args.length) {
            nodeLimit = Long.parseLong(args[i + 1]);
        } else if (args[i].equals("--cnd") && i + 1 < args.length) {
            cndPath = args[i + 1];
        } else if (args[i].equals("--query") && i + 1 < args.length) {
            query = args[i + 1];
        } else if (args[i].equals("--query-type") && i + 1 < args.length) {
            queryType = args[i + 1];
        }
    }
    boolean missingArgs = false;

    if (srcRepoDir.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --src option.");
    }
    if (destRepoDir.isEmpty() && !destConf.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --dest option.");
    }
    if (srcConf.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --src-conf option.");
    }
    if (destConf.isEmpty() && !destRepoDir.isEmpty()) {
        missingArgs = true;
        log.error("Please specify the --dest-conf option.");
    }

    if (missingArgs)
        return;

    SimpleCredentials credentials = new SimpleCredentials(srcUser, srcPasswd.toCharArray());
    SimpleCredentials destCredentials = new SimpleCredentials(destUser, destPasswd.toCharArray());

    JackrabbitRepository dest = null;
    RepositoryFactory destRf = null;
    RepositoryFactory srcRf = new RepositoryFactoryImpl(srcConf, srcRepoDir);
    if (!destConf.isEmpty()) {
        destRf = new RepositoryFactoryImpl(destConf, destRepoDir);
    }

    try {
        final JackrabbitRepository src = srcRf.getRepository();
        SessionFactory srcSf = new SessionFactoryImpl(src, credentials);
        final Session srcSession = srcSf.getSession();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                srcSession.logout();
                src.shutdown();
            }
        });
        if (destConf.isEmpty()) {//query mode
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
            if (query.isEmpty()) {
                while (true) {
                    System.out.print(">");
                    String line = in.readLine();
                    if (line == null || line.isEmpty() || line.equalsIgnoreCase("quit")
                            || line.equalsIgnoreCase("exit")) {
                        break;
                    }
                    try {
                        runQuery(srcSession, line, queryType);
                    } catch (RepositoryException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            } else {
                try {
                    runQuery(srcSession, query, queryType);
                } catch (RepositoryException e) {
                    log.error(e.getMessage(), e);
                }
            }
            return;
        }

        dest = destRf.getRepository();
        SessionFactory destSf = new SessionFactoryImpl(dest, destCredentials);
        Session destSession = destSf.getSession();

        try {
            RepositoryManager.registerCustomNodeTypes(destSession, cndPath);
            if (nodeLimit == 0)
                NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, true);
            else
                NodeCopier.copy(srcSession, destSession, srcRepoPath, destRepoPath, nodeLimit, true);
            log.info("Copying " + srcSession.getWorkspace().getName() + " to "
                    + destSession.getWorkspace().getName() + " for " + srcRepoDir + " done.");
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (PathNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        }

        List<String> destWkspaces = RepositoryManager.getDestinationWorkspaces(srcSession, destSession);

        for (String workspace : destWkspaces) {
            Session wsSession = srcSf.getSession(workspace);
            Session wsDestSession = destSf.getSession(workspace);
            try {
                RepositoryManager.registerCustomNodeTypes(wsDestSession, cndPath);
                if (nodeLimit == 0)
                    NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, true);
                else {
                    NodeCopier.copy(wsSession, wsDestSession, srcRepoPath, destRepoPath, nodeLimit, true);
                }
                log.info("Copying " + wsSession.getWorkspace().getName() + " to "
                        + wsDestSession.getWorkspace().getName() + " for " + srcRepoDir + " done.");
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            } catch (ParseException e) {
                log.error(e.getMessage(), e);
            } catch (PathNotFoundException e) {
                log.error(e.getMessage(), e);
            } catch (RepositoryException e) {
                log.error(e.getMessage(), e);
            } finally {
                wsSession.logout();
                wsDestSession.logout();
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } catch (PathNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (dest != null)
            dest.shutdown();
    }
}

From source file:com.genentech.chemistry.tool.mm.SDFMMMinimize.java

/**
 * Main function for running on the command line
 * @param args/*from w  ww .ja  v  a  2  s .co m*/
 */
public static void main(String... args) throws IOException {
    // Get the available options from the programs
    Map<String, List<String>> allowedProgramsAndForceFields = getAllowedProgramsAndForceFields();
    Map<String, List<String>> allowedProgramsAndSolvents = getAllowedProgramsAndSolvents();

    // 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);

    StringBuilder programOptions = new StringBuilder("Program to use for minimization.  Choices are\n");

    for (String program : allowedProgramsAndForceFields.keySet()) {
        programOptions.append("\n***   -program " + program + "   ***\n");
        String forcefields = "";
        for (String option : allowedProgramsAndForceFields.get(program)) {
            forcefields += option + " ";
        }
        programOptions.append("-forcefield " + forcefields + "\n");

        String solvents = "";
        for (String option : allowedProgramsAndSolvents.get(program)) {
            solvents += option + " ";
        }
        programOptions.append("-solvent " + solvents + "\n");
    }

    opt = new Option(OPT_PROGRAM, true, programOptions.toString());
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_FORCEFIELD, true, "Forcefield options.  See -program for choices");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SOLVENT, true, "Solvent options.  See -program for choices");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_FIXED_ATOM_TAG, true, "SD tag name which contains the atom numbers to be held fixed.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_FIX_TORSION, true,
            "true/false. if true, the atoms in fixedAtomTag contains 4 indices of atoms defining a torsion angle to be held fixed");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_WORKING_DIR, true, "Working directory to put files.");
    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 (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 fixedAtomTag = cmd.getOptionValue(OPT_FIXED_ATOM_TAG);
    boolean fixTorsion = (cmd.getOptionValue(OPT_FIX_TORSION) != null
            && cmd.getOptionValue(OPT_FIX_TORSION).equalsIgnoreCase("true"));
    String programName = cmd.getOptionValue(OPT_PROGRAM);
    String forcefield = cmd.getOptionValue(OPT_FORCEFIELD);
    String solvent = cmd.getOptionValue(OPT_SOLVENT);
    String workDir = cmd.getOptionValue(OPT_WORKING_DIR);

    if (workDir == null || workDir.trim().length() == 0)
        workDir = ".";

    // Create a minimizer 
    SDFMMMinimize minimizer = new SDFMMMinimize();
    minimizer.setMethod(programName, forcefield, solvent);
    minimizer.run(inFile, outFile, fixedAtomTag, fixTorsion, workDir);
    minimizer.close();
    System.err.println("Minimization complete.");
}

From source file:com.trsst.Command.java

public static void main(String[] argv) {

    // during alpha period: expire after one week
    Date builtOn = Common.getBuildDate();
    if (builtOn != null) {
        long weekMillis = 1000 * 60 * 60 * 24 * 7;
        Date expiry = new Date(builtOn.getTime() + weekMillis);
        if (new Date().after(expiry)) {
            System.err.println("Build expired on: " + expiry);
            System.err.println("Please obtain a more recent build for testing.");
            System.exit(1);//from  www . j  a v a 2 s  . c  o m
        } else {
            System.err.println("Build will expire on: " + expiry);
        }
    }

    // experimental tor support
    boolean wantsTor = false;
    for (String s : argv) {
        if ("--tor".equals(s)) {
            wantsTor = true;
            break;
        }
    }
    if (wantsTor && !HAS_TOR) {
        try {
            log.info("Attempting to connect to tor network...");
            Security.addProvider(new BouncyCastleProvider());
            JvmGlobalUtil.init();
            NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TOR);
            JvmGlobalUtil.setNetLayerAndNetAddressNameService(netLayer, true);
            log.info("Connected to tor network");
            HAS_TOR = true;
        } catch (Throwable t) {
            log.error("Could not connect to tor: exiting", t);
            System.exit(1);
        }
    }

    // if unspecified, default relay to home.trsst.com
    if (System.getProperty("com.trsst.server.relays") == null) {
        System.setProperty("com.trsst.server.relays", "https://home.trsst.com/feed");
    }

    // default to user-friendlier file names
    String home = System.getProperty("user.home", ".");
    if (System.getProperty("com.trsst.client.storage") == null) {
        File client = new File(home, "Trsst Accounts");
        System.setProperty("com.trsst.client.storage", client.getAbsolutePath());
    }
    if (System.getProperty("com.trsst.server.storage") == null) {
        File server = new File(home, "Trsst System Cache");
        System.setProperty("com.trsst.server.storage", server.getAbsolutePath());
    }
    // TODO: try to detect if launching from external volume like a flash
    // drive and store on the local flash drive instead

    Console console = System.console();
    int result;
    try {
        if (console == null && argv.length == 0) {
            argv = new String[] { "serve", "--gui" };
        }
        result = new Command().doBegin(argv, System.out, System.in);

        // task queue prevents exit unless stopped
        if (TrsstAdapter.TASK_QUEUE != null) {
            TrsstAdapter.TASK_QUEUE.cancel();
        }
    } catch (Throwable t) {
        result = 1; // "general catchall error code"
        log.error("Unexpected error, exiting.", t);
    }

    // if error
    if (result != 0) {
        // force exit
        System.exit(result);
    }
}