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

public static void main(String argv[]) {
    int optind;/*from  w ww .  jav  a 2  s . c o m*/
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (optind >= argv.length) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            while (optind < argv.length) {
                int msgnum = Integer.parseInt(argv[optind++]);
                System.out.println("Getting message number: " + msgnum);
                Message m = null;

                try {
                    m = folder.getMessage(msgnum);
                    dumpPart(m);
                } catch (IndexOutOfBoundsException iex) {
                    System.out.println("Message number out of range");
                }
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:examples.unix.rshell.java

public static void main(String[] args) {
    String server, localuser, remoteuser, command;
    RCommandClient client;/* w w w  . j  a va 2  s . c  o  m*/

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

    client = new RCommandClient();

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

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

    try {
        client.rcommand(localuser, remoteuser, command);
    } catch (IOException e) {
        try {
            client.disconnect();
        } catch (IOException f) {
        }
        e.printStackTrace();
        System.err.println("Could not execute command.");
        System.exit(1);
    }

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

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

    System.exit(0);
}

From source file:net.jingx.main.Main.java

/**
 * @param args// w ww .  j  av  a  2  s. co  m
 * @throws IOException 
 */
public static void main(String[] args) {
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption(CLI_SECRET, true, "generate secret key (input is the configuration key from google)");
    options.addOption(CLI_PASSCODE, true, "generate passcode (input is the secret key)");
    options.addOption(new Option(CLI_HELP, "print this message"));
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(CLI_SECRET)) {
            String confKey = line.getOptionValue(CLI_SECRET);
            String secret = generateSecret(confKey);
            System.out.println("Your secret to generate pins: " + secret);
        } else if (line.hasOption(CLI_PASSCODE)) {
            String secret = line.getOptionValue(CLI_PASSCODE);
            String pin = computePin(secret, null);
            System.out.println(pin);
        } else if (line.hasOption(CLI_HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("GAuthCli", options);
        } else {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        MainGui window = new MainGui();
                        window.doSetVisible();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            return;
        }
        System.out.println("Press any key to exit");
        System.in.read();
    } catch (Exception e) {
        System.out.println("Unexpected exception:" + e.getMessage());
    }
    System.exit(0);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    InetAddress serverIPAddress = InetAddress.getByName("localhost");
    int port = 19000;
    InetSocketAddress serverAddress = new InetSocketAddress(serverIPAddress, port);
    Selector selector = Selector.open();
    SocketChannel channel = SocketChannel.open();
    channel.configureBlocking(false);/*from w w w .  jav a2s .  c o  m*/
    channel.connect(serverAddress);
    int operations = SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    channel.register(selector, operations);

    userInputReader = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        if (selector.select() > 0) {
            boolean doneStatus = processReadySet(selector.selectedKeys());
            if (doneStatus) {
                break;
            }
        }
    }
    channel.close();
}

From source file:com.toms.mq.rabbitmq.tutorial.part2.TcpAmqp.java

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

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

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:context/part2/*-tcp.xml");

    LOGGER.info("\n========================================================="
            + "\n                                            "
            + "\n   This is the TCP-AMQP Sample -                   "
            + "\n                                            "
            + "\n   Start a netcat, listening on port 11112 -          "
            + "\n   netcat -l 11112                              "
            + "\n                                            "
            + "\n   In another terminal, telnet to localhost 11111      "
            + "\n   Enter text and you will see it echoed to the netcat   "
            + "\n                                            "
            + "\n   Press Enter in this console to terminate           "
            + "\n                                            "
            + "\n=========================================================");

    System.in.read();
    context.close();
}

From source file:com.nabla.project.application.tool.runner.ServiceRunner.java

/**
 * DOCUMENT ME!/* w ww  .j  ava2 s. c  o m*/
 * 
 * @param args DOCUMENT ME!
 * @throws Exception DOCUMENT ME!
 * @throws RuntimeException DOCUMENT ME!
 */
public static void main(String args[]) throws Exception {

    ObjectInputStream ois = new ObjectInputStream(System.in);
    Object methodArgs[] = (Object[]) ois.readObject();

    if (args.length < 3) {

        throw new RuntimeException(
                "Error : usage : java com.nabla.project.application.tool.runner.ServiceRunner configFileName beanName methodName");

    }

    String configFileName = args[0];
    String beanName = args[1];
    String methodName = args[2];
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { configFileName });
    Object service = context.getBean(beanName);
    Method serviceMethod = null;
    Method methods[] = service.getClass().getMethods();

    for (Method method : methods) {

        if (method.getName().equals(methodName)) {

            serviceMethod = method;

        }

    }

    if (serviceMethod == null) {

        throw new RuntimeException("Method " + methodName + " not found in class " + service.getClass());

    }

    serviceMethod.invoke(service, methodArgs);

}

From source file:alluxio.master.journal.JournalTool.java

/**
 * Reads a journal via/*from  ww  w. j  a  v  a2 s  .  c  om*/
 * {@code java -cp \
 * assembly/target/alluxio-assemblies-<ALLUXIO-VERSION>-jar-with-dependencies.jar \
 * alluxio.master.journal.JournalTool < journal/FileSystemMaster/log.out}.
 *
 * @param args arguments passed to the tool
 * @throws IOException if a non-Alluxio related exception occurs
 */
public static void main(String[] args) throws IOException {
    if (!parseInputArgs(args)) {
        usage();
        System.exit(EXIT_FAILED);
    }
    if (sHelp) {
        usage();
        System.exit(EXIT_SUCCEEDED);
    }
    if (!sNoTimeout && !stdinHasData()) {
        System.exit(EXIT_FAILED);
    }

    JournalFormatter formatter = new ProtoBufJournalFormatter();
    JournalInputStream journalStream = formatter.deserialize(System.in);
    JournalEntry entry;
    while ((entry = journalStream.read()) != null) {
        System.out.print(entry);
        System.out.println(ENTRY_SEPARATOR);
    }
}

From source file:SimpleCalcStreamTok.java

public static void main(String[] av) throws IOException {
    if (av.length == 0)
        new SimpleCalcStreamTok(new InputStreamReader(System.in)).doCalc();
    else/*from   w  w w . j a va  2  s.c  o  m*/
        for (int i = 0; i < av.length; i++)
            new SimpleCalcStreamTok(av[i]).doCalc();
}

From source file:ProdCons1.java

public static void main(String[] args) throws IOException {
    ProdCons1 pc = new ProdCons1();
    System.out.println("Ready (p to produce, c to consume):");
    int i;//  w w  w.j  a v  a 2 s.  c  o m
    while ((i = System.in.read()) != -1) {
        char ch = (char) i;
        switch (ch) {
        case 'p':
            pc.produce();
            break;
        case 'c':
            pc.consume();
            break;
        }
    }
}

From source file:com.l2jfree.loginserver.tools.L2GameServerRegistrar.java

/**
 * Launches the interactive game server registration.
 * //from w ww  .  j a v a2  s  .c  om
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Game Server Registration");
    _log.info("Please choose:");
    _log.info("list - list registered game servers");
    _log.info("reg - register a game server");
    _log.info("rem - remove a registered game server");
    _log.info("hexid - generate a legacy hexid file");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2GameServerRegistrar reg = new L2GameServerRegistrar();

    String line;
    try {
        RegistrationState next = RegistrationState.INITIAL_CHOICE;
        while ((line = br.readLine()) != null) {
            line = line.trim().toLowerCase();
            switch (reg.getState()) {
            case GAMESERVER_ID:
                try {
                    int id = Integer.parseInt(line);
                    if (id < 1 || id > 127)
                        throw new IllegalArgumentException("ID must be in [1;127].");
                    reg.setId(id);
                    reg.setState(next);
                } catch (RuntimeException e) {
                    _log.info("You must input a number between 1 and 127");
                }

                if (reg.getState() == RegistrationState.ALLOW_BANS) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT allowBans FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();
                        if (rs.next()) {
                            _log.info("A game server is already registered on ID " + reg.getId());
                            reg.setState(RegistrationState.INITIAL_CHOICE);
                        } else
                            _log.info("Allow account bans from this game server? [y/n]:");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                } else if (reg.getState() == RegistrationState.REMOVE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("DELETE FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        int cnt = ps.executeUpdate();
                        if (cnt == 0)
                            _log.info("No game server registered on ID " + reg.getId());
                        else
                            _log.info("Game server removed.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (reg.getState() == RegistrationState.GENERATE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT authData FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            reg.setAuth(rs.getString("authData"));
                            byte[] b = HexUtil.hexStringToBytes(reg.getAuth());

                            Properties pro = new Properties();
                            pro.setProperty("ServerID", String.valueOf(reg.getId()));
                            pro.setProperty("HexID", HexUtil.hexToString(b));

                            BufferedOutputStream os = new BufferedOutputStream(
                                    new FileOutputStream("hexid.txt"));
                            pro.store(os, "the hexID to auth into login");
                            IOUtils.closeQuietly(os);
                            _log.info("hexid.txt has been generated.");
                        } else
                            _log.info("No game server registered on ID " + reg.getId());

                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not generate hexid.txt!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                }
                break;
            case ALLOW_BANS:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        reg.setTrusted(true);
                    else if (line.charAt(0) == 'n')
                        reg.setTrusted(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    byte[] auth = Rnd.nextBytes(new byte[BYTES]);
                    reg.setAuth(HexUtil.bytesToHexString(auth));

                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO gameserver (id, authData, allowBans) VALUES (?, ?, ?)");
                        ps.setInt(1, reg.getId());
                        ps.setString(2, reg.getAuth());
                        ps.setBoolean(3, reg.isTrusted());
                        ps.executeUpdate();
                        ps.close();

                        _log.info("Registered game server on ID " + reg.getId());
                        _log.info("The authorization string is:");
                        _log.info(reg.getAuth());
                        _log.info("Use it when registering this login server.");
                        _log.info("If you need a legacy hexid file, use the 'hexid' command.");
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }

                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            default:
                if (line.equals("list")) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT id, allowBans FROM gameserver");
                        ResultSet rs = ps.executeQuery();
                        while (rs.next())
                            _log.info("ID: " + rs.getInt("id") + ", trusted: " + rs.getBoolean("allowBans"));
                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (line.equals("reg")) {
                    _log.info("Enter the desired ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.ALLOW_BANS;
                } else if (line.equals("rem")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.REMOVE;
                } else if (line.equals("hexid")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.GENERATE;
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}