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.hzih.sslvpn.servlet.TelnetClientExample.java

/**
 * Main for the TelnetClientExample./*  w w w . j a v a  2  s. c  o  m*/
 * *
 */
public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:com.l2jfree.security.Base64.java

public static void main(String[] args) throws IOException {
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter String to encode: ");
    System.out.println(Base64.encodeBytes(bf.readLine().getBytes()));
}

From source file:net.sf.jsignpdf.InstallCert.java

/**
 * The main - whole logic of Install Cert Tool.
 * /*  w w w. j  a va 2s.  c o  m*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) {
    String host;
    int port;
    char[] passphrase;

    System.out.println("InstallCert - Install CA certificate to Java Keystore");
    System.out.println("=====================================================");

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    try {
        if ((args.length == 1) || (args.length == 2)) {
            String[] c = args[0].split(":");
            host = c[0];
            port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
            String p = (args.length == 1) ? "changeit" : args[1];
            passphrase = p.toCharArray();
        } else {
            String tmpStr;
            do {
                System.out.print("Enter hostname or IP address: ");
                tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            } while (tmpStr == null);
            host = tmpStr;
            System.out.print("Enter port number [443]: ");
            tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null);
            port = tmpStr == null ? 443 : Integer.parseInt(tmpStr);
            System.out.print("Enter keystore password [changeit]: ");
            tmpStr = reader.readLine();
            String p = "".equals(tmpStr) ? "changeit" : tmpStr;
            passphrase = p.toCharArray();
        }

        char SEP = File.separatorChar;
        final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        final File file = new File(dir, "cacerts");

        System.out.println("Loading KeyStore " + file + "...");
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, passphrase);
        in.close();

        SSLContext context = SSLContext.getInstance("TLS");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
        context.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory factory = context.getSocketFactory();

        System.out.println("Opening connection to " + host + ":" + port + "...");
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        try {
            System.out.println("Starting SSL handshake...");
            socket.startHandshake();
            socket.close();
            System.out.println();
            System.out.println("No errors, certificate is already trusted");
        } catch (SSLException e) {
            System.out.println();
            System.out.println("Certificate is not yet trusted.");
            //        e.printStackTrace(System.out);
        }

        X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.out.println("Could not obtain server certificate chain");
            return;
        }

        System.out.println();
        System.out.println("Server sent " + chain.length + " certificate(s):");
        System.out.println();
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
            System.out.println("   Issuer  " + cert.getIssuerDN());
            sha1.update(cert.getEncoded());
            System.out.println("   sha1    " + toHexString(sha1.digest()));
            md5.update(cert.getEncoded());
            System.out.println("   md5     " + toHexString(md5.digest()));
            System.out.println();
        }

        System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: ");
        String line = reader.readLine().trim();
        int k = -1;
        try {
            k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
        } catch (NumberFormatException e) {
        }

        if (k < 0 || k >= chain.length) {
            System.out.println("KeyStore not changed");
        } else {
            try {
                System.out.println("Creating keystore backup");
                final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                final File backupFile = new File(dir,
                        CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date()));
                final FileInputStream fis = new FileInputStream(file);
                final FileOutputStream fos = new FileOutputStream(backupFile);
                IOUtils.copy(fis, fos);
                fis.close();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Installing certificate...");

            X509Certificate cert = chain[k];
            String alias = host + "-" + (k + 1);
            ks.setCertificateEntry(alias, cert);

            OutputStream out = new FileOutputStream(file);
            ks.store(out, passphrase);
            out.close();

            System.out.println();
            System.out.println(cert);
            System.out.println();
            System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'");
        }
    } catch (Exception e) {
        System.out.println();
        System.out.println("----------------------------------------------");
        System.out.println("Problem occured during installing certificate:");
        e.printStackTrace();
        System.out.println("----------------------------------------------");
    }
    System.out.println("Press Enter to finish...");
    try {
        reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.groupC1.control.network.TelnetClientExample.java

/***
 * Main for the TelnetClient.//from w w w .  j  a va  2 s.  com
 ***/
public static void main(String[] args) throws Exception {
    args = new String[] { "169.254.0.10", "10001" };
    FileOutputStream fout = null;
    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }
    String remoteip = args[0];
    int remoteport;
    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }
    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }
    tc = new org.apache.commons.net.telnet.TelnetClient();
    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }
    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);
            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClient");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;
            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");
                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:de.mfo.jsurf.Main.java

/**
 * @param args// w  w w  .  j  a v a2s .c o m
 */
public static void main(String[] args) {

    String jsurf_filename = "";
    Options options = new Options();

    options.addOption("s", "size", true, "width (and height) of a image (default: " + size + ")");
    options.addOption("q", "quality", true,
            "quality of the rendering: 0 (low), 1 (medium, default), 2 (high), 3 (extreme)");
    options.addOption("o", "output", true,
            "output PNG into this file (- means standard output. Use ./- to denote a file literally named -.)");

    CommandLineParser parser = new PosixParser();
    HelpFormatter formatter = new HelpFormatter();
    String cmd_line_syntax = "jsurf [options] jsurf_file";
    String help_header = "jsurf is a renderer for algebraic surfaces. If - is specified as a filename the jsurf file is read from standard input. "
            + "Use ./- to denote a file literally named -.";
    String help_footer = "";
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.getArgs().length > 0)
            jsurf_filename = cmd.getArgs()[0];
        else {
            formatter.printHelp(cmd_line_syntax, help_header, options, help_footer);
            return;
        }

        if (cmd.hasOption("output")) {
        }

        if (cmd.hasOption("size"))
            size = Integer.parseInt(cmd.getOptionValue("size"));

        int quality = 1;
        if (cmd.hasOption("quality"))
            quality = Integer.parseInt(cmd.getOptionValue("quality"));
        switch (quality) {
        case 0:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_1x1;
            break;
        case 2:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_4x4;
            break;
        case 3:
            aam = AntiAliasingMode.SUPERSAMPLING;
            aap = AntiAliasingPattern.OG_4x4;
            break;
        case 1:
            aam = AntiAliasingMode.ADAPTIVE_SUPERSAMPLING;
            aap = AntiAliasingPattern.QUINCUNX;
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
        System.exit(-1);
    } catch (NumberFormatException nfe) {
        formatter.printHelp(cmd_line_syntax, help_header, options, help_footer);
        System.exit(-1);
    }

    final Properties jsurf = new Properties();
    try {
        if (jsurf_filename.equals("-"))
            jsurf.load(System.in);
        else
            jsurf.load(new FileReader(jsurf_filename));
        FileFormat.load(jsurf, asr);
    } catch (Exception e) {
        System.err.println("Unable to read jsurf file " + jsurf_filename);
        e.printStackTrace();
        System.exit(-2);
    }

    asr.setAntiAliasingMode(aam);
    asr.setAntiAliasingPattern(aap);

    // display the image in a window 
    final String window_title = "jsurf: " + jsurf_filename;
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame f = new JFrame(window_title);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JSurferRenderPanel p = null;
            try {
                p = new JSurferRenderPanel(jsurf);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            f.setContentPane(p);

            //                f.getContentPane().add( new JLabel( new ImageIcon( window_image ) ) );
            f.pack();
            //                f.setResizable( false );
            f.setVisible(true);
        }
    });
}

From source file:de.taimos.dvalin.interconnect.model.MessageCryptoUtil.java

/**
 * start this to generate an AES key or (de/en)crypt data
 *
 * @param args the CLI arguments// ww  w.  j a  va  2  s .c  o  m
 */
@SuppressWarnings("resource")
public static void main(String[] args) {
    try {
        System.out.println("Select (k=generate key; c=crypt; d=decrypt):");
        System.out.println();
        Scanner scan = new Scanner(System.in, "UTF-8");
        if (!scan.hasNextLine()) {
            return;
        }
        switch (scan.nextLine()) {
        case "k":
            MessageCryptoUtil.generateKey();
            break;
        case "c":
            System.out.print("Input data: ");
            final String data = scan.nextLine();
            System.out.println(MessageCryptoUtil.crypt(data));
            break;
        case "d":
            System.out.print("Input data: ");
            final String ddata = scan.nextLine();
            System.out.println(MessageCryptoUtil.decrypt(ddata));
            break;
        default:
            break;
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sfr.tv.mom.mgt.HornetqConsole.java

/**
 * @param args the command line arguments
 *///  w w  w.j  a v a 2 s.  c om
public static void main(String[] args) {

    try {

        String jmxHost = "127.0.0.1";
        String jmxPort = "6001";

        // Process command line arguments
        String arg;
        for (int i = 0; i < args.length; i++) {
            arg = args[i];
            switch (arg) {
            case "-h":
                jmxHost = args[++i];
                break;
            case "-p":
                jmxPort = args[++i];
                break;
            default:
                break;
            }
        }

        // Check for arguments consistency
        if (StringUtils.isEmpty(jmxHost) || !NumberUtils.isNumber(jmxPort)) {
            LOGGER.info("Usage : ");
            LOGGER.info("hq-console.jar <-h host(127.0.0.1)> <-p port(6001)>\n");
            System.exit(1);
        }

        System.out.println(
                SystemUtils.LINE_SEPARATOR.concat(Ansi.format("HornetQ Console ".concat(VERSION), Color.CYAN)));

        final StringBuilder _url = new StringBuilder("service:jmx:rmi://").append(jmxHost).append(':')
                .append(jmxPort).append("/jndi/rmi://").append(jmxHost).append(':').append(jmxPort)
                .append("/jmxrmi");

        final String jmxServiceUrl = _url.toString();
        JMXConnector jmxc = null;

        final CommandRouter router = new CommandRouter();

        try {
            jmxc = JMXConnectorFactory.connect(new JMXServiceURL(jmxServiceUrl), null);
            assert jmxc != null; // jmxc must be not null
        } catch (final MalformedURLException e) {
            System.out.println(SystemUtils.LINE_SEPARATOR
                    .concat(Ansi.format(jmxServiceUrl + " :" + e.getMessage(), Color.RED)));
        } catch (Throwable t) {
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Unable to connect to JMX service URL : ".concat(jmxServiceUrl), Color.RED)));
            System.out.print(SystemUtils.LINE_SEPARATOR.concat(
                    Ansi.format("Did you add jmx-staticport-agent.jar to your classpath ?", Color.MAGENTA)));
            System.out.println(SystemUtils.LINE_SEPARATOR.concat(Ansi.format(
                    "Or did you set the com.sun.management.jmxremote.port option in the hornetq server startup script ?",
                    Color.MAGENTA)));
            System.exit(-1);
        }

        System.out.println("\n".concat(Ansi
                .format("Successfully connected to JMX service URL : ".concat(jmxServiceUrl), Color.YELLOW)));

        final MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // PRINT SERVER STATUS REPORT
        System.out.print((String) router.get(Command.STATUS, Option.VM).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.SERVER).execute(mbsc, null));
        System.out.print((String) router.get(Command.STATUS, Option.CLUSTER).execute(mbsc, null));

        printHelp(router);

        // START COMMAND LINE
        Scanner scanner = new Scanner(System.in);
        System.out.print("> ");
        String input;
        while (!(input = scanner.nextLine().concat(" ")).equals("exit ")) {

            String[] cliArgs = input.split("\\ ");
            CommandHandler handler;

            if (cliArgs.length < 1) {
                System.out.print("> ");
                continue;
            }

            Command cmd = Command.fromString(cliArgs[0]);
            if (cmd == null) {
                System.out.print(Ansi.format("Syntax error !", Color.RED).concat("\n"));
                cmd = Command.HELP;
            }

            switch (cmd) {
            case STATUS:
            case LIST:
            case DROP:

                Set<Option> options = router.get(cmd);

                for (Option opt : options) {

                    if (cliArgs[1].equals(opt.toString())) {
                        handler = router.get(cmd, opt);

                        String[] cmdOpts = null;
                        if (cliArgs.length > 2) {
                            cmdOpts = new String[cliArgs.length - 2];
                            for (int i = 0; i < cmdOpts.length; i++) {
                                cmdOpts[i] = cliArgs[2 + i];
                            }
                        }

                        Object result = handler.execute(mbsc, cmdOpts);
                        if (result != null && String.class.isAssignableFrom(result.getClass())) {
                            System.out.print((String) result);
                        }
                        System.out.print("> ");
                    }
                }

                break;

            case FORK:
                // EXECUTE SYSTEM COMMAND
                ProcessBuilder pb = new ProcessBuilder(Arrays.copyOfRange(cliArgs, 1, cliArgs.length));
                pb.inheritIO();
                pb.start();
                break;

            case HELP:
                printHelp(router);
                break;
            }
        }
    } catch (MalformedURLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }

    echo(SystemUtils.LINE_SEPARATOR.concat(Ansi.format("Bye!", Color.CYAN)));

}

From source file:dingwen.Command.java

public static void main(String[] args) {
    ShapeCache shapeCache = new ShapeCache();
    String filePath = Helper.DEFAULT_FILE;
    System.out.println(CommonStatement.NOTE);

    if (args != null && args.length != 0) {
        filePath = args[0];/*from   w  ww.ja  v a 2 s.  c  o m*/
    }
    shapeCache.init(filePath);

    Scanner scanner = new Scanner(System.in);
    while (true) {
        try {
            String command = scanner.nextLine();
            if (command.contains("add")) {
                Command.addShapeCmd(command, shapeCache);

            } else if (command.contains("remove")) {
                Command.removeShapeCmd(command, shapeCache);

            } else if (command.contains("list")) {
                Command.listShapesCmd(command, shapeCache);

            } else if (command.contains("contains")) {
                Command.containsCmd(command, shapeCache);

            } else if (command.equals("help shape")) {
                Command.shapeHelp();

            } else if (command.contains("help")) {
                Command.helpCmd();

            } else if (command.contains("exit")) {
                Command.exitCmd();
                break;

            } else {
                System.out.println(CommonStatement.INPUT_NOT_RECOGNIZE);
            }
        } catch (Exception e) {
            System.out.println(CommonStatement.INPUT_NOT_RECOGNIZE);
        }
    }

}

From source file:PopClean.java

public static void main(String args[]) {
    try {/*  w w w . ja  v  a2s .  c  om*/
        String hostname = null, username = null, password = null;
        int port = 110;
        int sizelimit = -1;
        String subjectPattern = null;
        Pattern pattern = null;
        Matcher matcher = null;
        boolean delete = false;
        boolean confirm = true;

        // Handle command-line arguments
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-user"))
                username = args[++i];
            else if (args[i].equals("-pass"))
                password = args[++i];
            else if (args[i].equals("-host"))
                hostname = args[++i];
            else if (args[i].equals("-port"))
                port = Integer.parseInt(args[++i]);
            else if (args[i].equals("-size"))
                sizelimit = Integer.parseInt(args[++i]);
            else if (args[i].equals("-subject"))
                subjectPattern = args[++i];
            else if (args[i].equals("-debug"))
                debug = true;
            else if (args[i].equals("-delete"))
                delete = true;
            else if (args[i].equals("-force")) // don't confirm
                confirm = false;
        }

        // Verify them
        if (hostname == null || username == null || password == null || sizelimit == -1)
            usage();

        // Make sure the pattern is a valid regexp
        if (subjectPattern != null) {
            pattern = Pattern.compile(subjectPattern);
            matcher = pattern.matcher("");
        }

        // Say what we are going to do
        System.out
                .println("Connecting to " + hostname + " on port " + port + " with username " + username + ".");
        if (delete) {
            System.out.println("Will delete all messages longer than " + sizelimit + " bytes");
            if (subjectPattern != null)
                System.out.println("that have a subject matching: [" + subjectPattern + "]");
        } else {
            System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes");
            if (subjectPattern != null)
                System.out.println("that have a subject matching: [" + subjectPattern + "]");
        }

        // If asked to delete, ask for confirmation unless -force is given
        if (delete && confirm) {
            System.out.println();
            System.out.print("Do you want to proceed (y/n) [n]: ");
            System.out.flush();
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            String response = console.readLine();
            if (!response.equals("y")) {
                System.out.println("No messages deleted.");
                System.exit(0);
            }
        }

        // Connect to the server, and set up streams
        s = new Socket(hostname, port);
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

        // Read the welcome message from the server, confirming it is OK.
        System.out.println("Connected: " + checkResponse());

        // Now log in
        send("USER " + username); // Send username, wait for response
        send("PASS " + password); // Send password, wait for response
        System.out.println("Logged in");

        // Check how many messages are waiting, and report it
        String stat = send("STAT");
        StringTokenizer t = new StringTokenizer(stat);
        System.out.println(t.nextToken() + " messages in mailbox.");
        System.out.println("Total size: " + t.nextToken());

        // Get a list of message numbers and sizes
        send("LIST"); // Send LIST command, wait for OK response.
        // Now read lines from the server until we get . by itself
        List msgs = new ArrayList();
        String line;
        for (;;) {
            line = in.readLine();
            if (line == null)
                throw new IOException("Unexpected EOF");
            if (line.equals("."))
                break;
            msgs.add(line);
        }

        // Now loop through the lines we read one at a time.
        // Each line should specify the message number and its size.
        int nummsgs = msgs.size();
        for (int i = 0; i < nummsgs; i++) {
            String m = (String) msgs.get(i);
            StringTokenizer st = new StringTokenizer(m);
            int msgnum = Integer.parseInt(st.nextToken());
            int msgsize = Integer.parseInt(st.nextToken());

            // If the message is too small, ignore it.
            if (msgsize <= sizelimit)
                continue;

            // If we're listing messages, or matching subject lines
            // find the subject line for this message
            String subject = null;
            if (!delete || pattern != null) {
                subject = getSubject(msgnum); // get the subject line

                // If we couldn't find a subject, skip the message
                if (subject == null)
                    continue;

                // If this subject does not match the pattern, then
                // skip the message
                if (pattern != null) {
                    matcher.reset(subject);
                    if (!matcher.matches())
                        continue;
                }

                // If we are listing, list this message
                if (!delete) {
                    System.out.println("Subject " + msgnum + ": " + subject);
                    continue; // so we never delete it
                }
            }

            // If we were asked to delete, then delete the message
            if (delete) {
                send("DELE " + msgnum);
                if (pattern == null)
                    System.out.println("Deleted message " + msgnum);
                else
                    System.out.println("Deleted message " + msgnum + ": " + subject);
            }
        }

        // When we're done, log out and shutdown the connection
        shutdown();
    } catch (Exception e) {
        // If anything goes wrong print exception and show usage
        System.err.println(e);
        usage();
        // Always try to shutdown nicely so the server doesn't hang on us
        shutdown();
    }
}

From source file:de.akquinet.dustjs.DustEngine.java

public static void main(String[] args) throws URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(DustOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(DustOptions.DUST_OPTION, true, "Path to a custom dust.js for Rhino version.");
    try {/* w  ww.ja  v  a 2 s .c  om*/
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        DustOptions options = new DustOptions();
        if (cmdLine.hasOption(DustOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(DustOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(DustOptions.DUST_OPTION)) {
            options.setDust(new File(cmdLine.getOptionValue(DustOptions.DUST_OPTION)).toURI().toURL());
        }
        DustEngine engine = new DustEngine(options);
        String[] files = cmdLine.getArgs();

        String src = null;
        if (files == null || files.length == 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            src = sw.toString();
        }

        if (src != null && !src.isEmpty()) {
            System.out.println(engine.compile(src, "test"));
            return;
        }

        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0])));
            return;
        }

        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]));
            return;
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar dust-engine.jar input [output] [options]", cmdOptions);
    System.exit(1);
}