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:CSVFile.java

public static void main(String[] args) throws IOException {

    // Construct a new CSV parser.
    CSV csv = new CSV();

    if (args.length == 0) { // read standard input
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
        process(csv, is);//from  w w  w  .j  ava 2s . co  m
    } else {
        for (int i = 0; i < args.length; i++) {
            process(csv, new BufferedReader(new FileReader(args[i])));
        }
    }
}

From source file:com.lightboxtechnologies.spectrum.InfoPutter.java

public static void main(String[] args) throws IOException {
    final Configuration conf = HBaseConfiguration.create();

    final String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

    if (otherArgs.length != 2) {
        System.err.println("Usage: InfoPutter <imageID> <friendly_name>");
        System.exit(1);/*from  www .jav a  2  s  .  c  om*/
    }

    final String imageID = otherArgs[0];
    final String friendlyName = otherArgs[1];

    HTable imgTable = null;

    try {
        imgTable = HBaseTables.summon(conf, HBaseTables.IMAGES_TBL_B, HBaseTables.IMAGES_COLFAM_B);

        // check whether the image ID is in the images table
        final byte[] hash = Bytes.toBytes(imageID);

        final Get get = new Get(hash);
        final Result result = imgTable.get(get);

        if (result.isEmpty()) {
            // row does not exist, add it

            final byte[] friendly_col = "friendly_name".getBytes();
            final byte[] json_col = "json".getBytes();

            final byte[] friendly_b = friendlyName.getBytes();
            final byte[] json_b = IOUtils.toByteArray(System.in);

            final Put put = new Put(hash);
            put.add(HBaseTables.IMAGES_COLFAM_B, friendly_col, friendly_b);
            put.add(HBaseTables.IMAGES_COLFAM_B, json_col, json_b);

            imgTable.put(put);

            System.exit(0);
        } else {
            // row exists, fail!
            System.exit(1);
        }
    } finally {
        imgTable.close();
    }
}

From source file:DropReceivedLines.java

public static void main(String[] av) {
    DropReceivedLines d = new DropReceivedLines();
    // For stdin, act as a filter. For named files,
    // update each file in place (safely, by creating a new file).
    try {//from www. ja va2  s .  c o m
        if (av.length == 0)
            d.process(new BufferedReader(new InputStreamReader(System.in)), new PrintWriter(System.out));
        else
            for (int i = 0; i < av.length; i++)
                d.process(av[i]);
    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
    } catch (IOException e) {
        System.err.println("I/O error " + e);
    }
}

From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    loadConfig();//from w  ww .  j av a  2s .c o  m

    AlphonseBot bot = new AlphonseBot(nick, pass, server, channels, maxXKCD, noVoiceNicks, masters,
            dadLeaveTimes);
    bot.setMessageDelay(500);
    try {
        bot.startConnection();
    } catch (IOException | IrcException ex) {
        Logger.getLogger(MSTDeskEngRunner.class.getName()).log(Level.SEVERE, null, ex);
    }

    boolean quit = false;
    while (!quit) {
        String curLine = scan.nextLine();

        switch (curLine) {
        case "exit":
            System.out.println("Quitting.");
            bot.onPreQuit();
            bot.disconnect();
            bot.dispose();
            writeConfig();
            quit = true;
            System.out.println("Quit'd.");
            break;
        case "msg":
            Scanner lineScan = new Scanner(scan.nextLine());
            try {
                bot.sendMessage(lineScan.next(), lineScan.nextLine());
            } catch (Exception e) {
                System.err.println(e.getClass().toString());
                System.err.println("Not enough args");
            }
            break;
        default:
            System.out.println("Invalid command.");
        }
    }
}

From source file:edu.msu.cme.rdp.readseq.ToFasta.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("m", "mask", true, "Mask sequence name indicating columns to drop");
    String maskSeqid = null;//from  ww  w .j a v  a  2s  .co m

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("mask")) {
            maskSeqid = line.getOptionValue("mask");
        }

        args = line.getArgs();
        if (args.length == 0) {
            throw new Exception("");
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: to-fasta <input-file>", options);
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
        return;
    }

    SeqReader reader = null;

    FastaWriter out = new FastaWriter(System.out);
    Sequence seq;
    int totalSeqs = 0;
    long totalTime = System.currentTimeMillis();

    for (String fname : args) {
        if (fname.equals("-")) {
            reader = new SequenceReader(System.in);
        } else {
            File seqFile = new File(fname);

            if (maskSeqid == null) {
                reader = new SequenceReader(seqFile);
            } else {
                reader = new IndexedSeqReader(seqFile, maskSeqid);
            }
        }

        long startTime = System.currentTimeMillis();
        int thisFileTotalSeqs = 0;
        while ((seq = reader.readNextSequence()) != null) {
            out.writeSeq(seq.getSeqName().replace(" ", "_"), seq.getDesc(), seq.getSeqString());
            thisFileTotalSeqs++;
        }
        totalSeqs += thisFileTotalSeqs;
        System.err.println("Converted " + thisFileTotalSeqs + " (total sequences: " + totalSeqs
                + ") sequences from " + fname + " (" + reader.getFormat() + ") to fasta in "
                + (System.currentTimeMillis() - startTime) / 1000 + " s");
    }
    System.err.println("Converted " + totalSeqs + " to fasta in "
            + (System.currentTimeMillis() - totalTime) / 1000 + " s");

    out.close();
}

From source file:com.mobius.software.mqtt.performance.controller.ControllerRunner.java

public static void main(String[] args) {
    try {/* w ww.j ava2  s .com*/
        /*URI baseURI = URI.create(args[0].replace("-baseURI=", ""));
        configFile = args[1].replace("-configFile=", "");*/
        String userDir = System.getProperty("user.dir");
        System.out.println("user.dir: " + userDir);
        setConfigFilePath(userDir + "/config.properties");
        Properties prop = new Properties();
        prop.load(new FileInputStream(configFile));
        System.out.println("properties loaded...");

        String hostname = prop.getProperty("hostname");
        Integer port = Integer.parseInt(prop.getProperty("port"));
        URI baseURI = new URI(null, null, hostname, port, null, null, null);

        configureConsoleLogger();
        System.out.println("starting http server...");
        JerseyServer server = new JerseyServer(baseURI);
        System.out.println("http server started");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("press any key to stop: ");
        br.readLine();
        server.terminate();
    } catch (Throwable e) {
        logger.error("AN ERROR OCCURED: " + e.getMessage());
        e.printStackTrace();
    } finally {
        System.exit(0);
    }
}

From source file:leader.LeaderSelectorExample.java

public static void main(String[] args) throws Exception {
    // all of the useful sample code is in ExampleClient.java

    System.out.println("Create " + CLIENT_QTY
            + " clients, have each negotiate for leadership and then wait a random number of seconds before letting another leader election occur.");
    System.out.println(/* ww w. j  a  v a  2  s .  co m*/
            "Notice that leader election is fair: all clients will become leader and will do so the same number of times.");

    List<CuratorFramework> clients = Lists.newArrayList();
    List<ExampleClient> examples = Lists.newArrayList();
    TestingServer server = new TestingServer();
    try {
        for (int i = 0; i < CLIENT_QTY; ++i) {
            CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                    new ExponentialBackoffRetry(1000, 3));
            clients.add(client);

            ExampleClient example = new ExampleClient(client, PATH, "Client #" + i);
            examples.add(example);

            client.start();
            example.start();
        }

        System.out.println("Press enter/return to quit\n");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    } finally {
        System.out.println("Shutting down...");

        for (ExampleClient exampleClient : examples) {
            IOUtils.closeQuietly(exampleClient);
        }
        for (CuratorFramework client : clients) {
            IOUtils.closeQuietly(client);
        }

        IOUtils.closeQuietly(server);
    }
}

From source file:AdminExample.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    String accessToken = "";//Insert your access token here. Note this must be from an account that is an Admin of an account.
    String user1Email = ""; //You need access to these two email account.
    String user2Email = ""; //Note Gmail and Hotmail allow email aliasing. 
    //joe@gmail.com will get email sent to joe+user1@gmail.com 

    try {//  w  ww  .  j av  a  2  s .  co  m
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Adding user " + user1Email);

        //Add the users:
        User user = new User();
        user.setEmail(user1Email);
        user.setAdmin(false);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser1Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser1Result.result.email + " added with userId " + newUser1Result.result.getId());

        user = new User();
        user.setEmail(user2Email);
        user.setAdmin(true);
        user.setLicensedSheetCreator(true);

        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), user);
        Result<User> newUser2Result = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<User>>() {
                });
        System.out.println(
                "User " + newUser2Result.result.email + " added with userId " + newUser2Result.result.getId());
        System.out.println("Please visit the email inbox for the users " + user1Email + " and  " + user2Email
                + " and confirm membership to the account.");
        System.out.print("Press Enter to continue");
        in.readLine();

        //List all the users of the org
        connection = (HttpURLConnection) new URL(USERS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<User> users = mapper.readValue(connection.getInputStream(), new TypeReference<List<User>>() {
        });

        System.out.println("The following are members of your account: ");

        for (User orgUser : users) {
            System.out.println("\t" + orgUser.getEmail());
        }

        //Create a sheet as the admin
        Sheet newSheet = new Sheet();
        newSheet.setName("Admin's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user1
        newSheet = new Sheet();
        newSheet.setName("User 1's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        //Here is where the magic happens - Any action performed in this call will be on behalf of the
        //user provided. Note that this person must be a confirmed member of your org. 
        //Also note that the email address is url-encoded.
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user1Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //Create a sheet as user2
        newSheet = new Sheet();
        newSheet.setName("User 2's Sheet");
        newSheet.setColumns(Arrays.asList(new Column("Column 1", "TEXT_NUMBER", null, true, null),
                new Column("Column 2", "TEXT_NUMBER", null, null, null),
                new Column("Column 3", "TEXT_NUMBER", null, null, null)));
        connection = (HttpURLConnection) new URL(SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        mapper.writeValue(connection.getOutputStream(), newSheet);
        mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() {
        });

        //List all the sheets in the org:
        System.out.println("The following sheets are owned by members of your account: ");
        connection = (HttpURLConnection) new URL(USERS_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");
        List<Sheet> allSheets = mapper.readValue(connection.getInputStream(), new TypeReference<List<Sheet>>() {
        });

        for (Sheet orgSheet : allSheets) {
            System.out.println("\t" + orgSheet.getName() + " - " + orgSheet.getOwner());
        }

        //Now delete user1 and transfer their sheets to user2
        connection = (HttpURLConnection) new URL(USER_URL.replace(ID, newUser1Result.getResult().getId() + "")
                + "?transferTo=" + newUser2Result.getResult().getId()).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Assume-User", URLEncoder.encode(user2Email, "UTF-8"));
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setRequestMethod("DELETE");
        Result<Object> resultObject = mapper.readValue(connection.getInputStream(),
                new TypeReference<Result<Object>>() {
                });

        System.out.println("Sheets transferred : " + resultObject.getSheetsTransferred());

    } catch (IOException e) {

        InputStream is = connection == null ? null : ((HttpURLConnection) connection).getErrorStream();
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            try {
                response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                Result<?> result = mapper.readValue(response.toString(), Result.class);
                System.err.println(result.message);

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

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:test.node.TestNodeRunner.java

public static void main(String[] args) {

    // Test Job//www. j  av a 2s.co m
    TestJob testJob = new TestJob();

    try {

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

        GridNode node = Grid.startGridNode();

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

        sw.stop();

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

        // Submit Job
        log.debug("Submitting Job");

        sw.start();

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

            public void onResult(Serializable result) {
                System.err.println(result);
            }

        });
        try {
            log.info("Job Result : " + future.getResult());
        } catch (RemoteInvocationFailureException e) {
            e.getCause().printStackTrace();
        }

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

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

        log.info("Unregistered, Terminating...");
        System.exit(0);

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

}

From source file:se.berazy.api.examples.App.java

/**
 * Operation examples./*from  w ww .j  a  v  a2  s.co m*/
 * @param args
 */
public static void main(String[] args) {
    Scanner scanner = null;
    try {
        client = new BookkeepingClient();
        System.out.println("Choose operation to invoke:\n");
        System.out.println("1. Create invoice");
        System.out.println("2. Credit invoice");
        scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            line = (line != null) ? line.trim().toLowerCase() : "";
            if (line.equals("1")) {
                outPutResponse(createInvoice());
            } else if (line.equals("2")) {
                outPutResponse(creditInvoice());
            } else if (line.equals("q") || line.equals("quit") || line.equals("exit")) {
                System.exit(0);
            } else {
                System.out.println("\nPlease choose an operation from 1-7.");
            }
        }
        scanner.close();
    } catch (Exception ex) {
        System.out.println(String.format(
                "\nAn exception occured, press CTRL+C to exit or enter 'q', 'quit' or 'exit'.\n\nException: %s %s",
                ex.getMessage(), ex.getStackTrace()));
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
}