Example usage for java.io InputStreamReader InputStreamReader

List of usage examples for java.io InputStreamReader InputStreamReader

Introduction

In this page you can find the example usage for java.io InputStreamReader InputStreamReader.

Prototype

public InputStreamReader(InputStream in) 

Source Link

Document

Creates an InputStreamReader that uses the default charset.

Usage

From source file:CSVRE.java

public static void main(String[] argv) throws IOException {
    System.out.println(CSV_PATTERN);
    new CSVRE().process(new BufferedReader(new InputStreamReader(System.in)));
}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrSimpleIndexApp.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("i", null, true, "Input File");
    options.addOption("u", null, true, "Solr URI");
    options.addOption("n", null, true, "Batch size");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {//ww w . j  a v a 2  s  .c o m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("i")) {
            inputFile = cmd.getOptionValue("i");
        } else {
            Usage("Specify Input File");
        }

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        if (cmd.hasOption("n")) {
            batchQty = Integer.parseInt(cmd.getOptionValue("n"));
        }

        SolrServerWrapper solrServer = new SolrServerWrapper(solrURI);

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(inputFile)));

        XmlHelper xmlHlp = new XmlHelper();

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        for (int docNum = 1; docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {

            // 1. Read document text
            Map<String, String> docFields = null;
            HashMap<String, Object> objDocFields = new HashMap<String, Object>();

            try {
                docFields = xmlHlp.parseXMLIndexEntry(docText);
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText);
                throw new Exception("Parsing error.");
            }

            for (Map.Entry<String, String> e : docFields.entrySet()) {
                //System.out.println(e.getKey() + " " + e.getValue());
                objDocFields.put(e.getKey(), e.getValue());
            }

            solrServer.indexDocument(objDocFields);
            if ((docNum - 1) % batchQty == 0)
                solrServer.indexCommit();
        }
        solrServer.indexCommit();

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:edu.oregonstate.eecs.mcplan.domains.yahtzee2.YahtzeeClient.java

/**
 * @param args/*from ww w . j  a v a  2s  .  c om*/
 * @throws IOException
 */
public static void main(final String[] args) throws IOException {
    final RandomGenerator rng = new MersenneTwister(42);
    final YahtzeeState s0 = new YahtzeeState(rng);
    final YahtzeeSimulator sim = new YahtzeeSimulator(rng, s0);

    final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    while (!sim.state().isTerminal()) {
        printState(sim.state());
        final String cmd = reader.readLine();
        final String[] parts = cmd.split(" ");
        if ("keep".equals(parts[0])) {
            final int[] keepers = new int[Hand.Nfaces];
            for (int i = 1; i < parts.length; ++i) {
                final int v = Integer.parseInt(parts[i]);
                keepers[v - 1] += 1;
            }
            sim.takeAction(new JointAction<YahtzeeAction>(new KeepAction(keepers)));
        } else if ("score".equals(parts[0])) {
            final YahtzeeScores category = YahtzeeScores.valueOf(parts[1]);
            sim.takeAction(new JointAction<YahtzeeAction>(new ScoreAction(category)));
        } else if ("undo".equals(parts[0])) {
            sim.untakeLastAction();
        } else {
            System.out.println("!!! Bad command");
        }
    }
    System.out.println("********** Terminal **********");
    printState(sim.state());
}

From source file:ExecuteSQL.java

public static void main(String[] args) {
    Connection conn = null; // Our JDBC connection to the database server
    try {/*  ww  w. j  a  va 2s  .  co m*/
        String driver = null, url = null, user = "", password = "";

        // Parse all the command-line arguments
        for (int n = 0; n < args.length; n++) {
            if (args[n].equals("-d"))
                driver = args[++n];
            else if (args[n].equals("-u"))
                user = args[++n];
            else if (args[n].equals("-p"))
                password = args[++n];
            else if (url == null)
                url = args[n];
            else
                throw new IllegalArgumentException("Unknown argument.");
        }

        // The only required argument is the database URL.
        if (url == null)
            throw new IllegalArgumentException("No database specified");

        // If the user specified the classname for the DB driver, load
        // that class dynamically. This gives the driver the opportunity
        // to register itself with the DriverManager.
        if (driver != null)
            Class.forName(driver);

        // Now open a connection the specified database, using the
        // user-specified username and password, if any. The driver
        // manager will try all of the DB drivers it knows about to try to
        // parse the URL and connect to the DB server.
        conn = DriverManager.getConnection(url, user, password);

        // Now create the statement object we'll use to talk to the DB
        Statement s = conn.createStatement();

        // Get a stream to read from the console
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Loop forever, reading the user's queries and executing them
        while (true) {
            System.out.print("sql> "); // prompt the user
            System.out.flush(); // make the prompt appear now.
            String sql = in.readLine(); // get a line of input from user

            // Quit when the user types "quit".
            if ((sql == null) || sql.equals("quit"))
                break;

            // Ignore blank lines
            if (sql.length() == 0)
                continue;

            // Now, execute the user's line of SQL and display results.
            try {
                // We don't know if this is a query or some kind of
                // update, so we use execute() instead of executeQuery()
                // or executeUpdate() If the return value is true, it was
                // a query, else an update.
                boolean status = s.execute(sql);

                // Some complex SQL queries can return more than one set
                // of results, so loop until there are no more results
                do {
                    if (status) { // it was a query and returns a ResultSet
                        ResultSet rs = s.getResultSet(); // Get results
                        printResultsTable(rs, System.out); // Display them
                    } else {
                        // If the SQL command that was executed was some
                        // kind of update rather than a query, then it
                        // doesn't return a ResultSet. Instead, we just
                        // print the number of rows that were affected.
                        int numUpdates = s.getUpdateCount();
                        System.out.println("Ok. " + numUpdates + " rows affected.");
                    }

                    // Now go see if there are even more results, and
                    // continue the results display loop if there are.
                    status = s.getMoreResults();
                } while (status || s.getUpdateCount() != -1);
            }
            // If a SQLException is thrown, display an error message.
            // Note that SQLExceptions can have a general message and a
            // DB-specific message returned by getSQLState()
            catch (SQLException e) {
                System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
            }
            // Each time through this loop, check to see if there were any
            // warnings. Note that there can be a whole chain of warnings.
            finally { // print out any warnings that occurred
                SQLWarning w;
                for (w = conn.getWarnings(); w != null; w = w.getNextWarning())
                    System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
            }
        }
    }
    // Handle exceptions that occur during argument parsing, database
    // connection setup, etc. For SQLExceptions, print the details.
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException)
            System.err.println("SQL State: " + ((SQLException) e).getSQLState());
        System.err.println(
                "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>");
    }

    // Be sure to always close the database connection when we exit,
    // whether we exit because the user types 'quit' or because of an
    // exception thrown while setting things up. Closing this connection
    // also implicitly closes any open statements and result sets
    // associated with it.
    finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

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  .  java  2  s.  c  om
    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.datastax.sparql.ConsoleCompiler.java

public static void main(final String[] args) throws IOException {
    //args = "/examples/modern1.sparql";
    final Options options = new Options();
    options.addOption("f", "file", true, "a file that contains a SPARQL query");
    options.addOption("g", "graph", true,
            "the graph that's used to execute the query [classic|modern|crew|kryo file]");
    // TODO: add an OLAP option (perhaps: "--olap spark"?)

    final CommandLineParser parser = new DefaultParser();
    final CommandLine commandLine;

    try {/*from   ww w . j  a v  a 2 s  .c om*/
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printHelp(1);
        return;
    }

    final InputStream inputStream = commandLine.hasOption("file")
            ? new FileInputStream(commandLine.getOptionValue("file"))
            : System.in;
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final StringBuilder queryBuilder = new StringBuilder();

    if (!reader.ready()) {
        printHelp(1);
    }

    String line;
    while (null != (line = reader.readLine())) {
        queryBuilder.append(System.lineSeparator()).append(line);
    }

    final String queryString = queryBuilder.toString();
    final Graph graph;

    if (commandLine.hasOption("graph")) {
        switch (commandLine.getOptionValue("graph").toLowerCase()) {
        case "classic":
            graph = TinkerFactory.createClassic();
            break;
        case "modern":
            graph = TinkerFactory.createModern();
            System.out.println("Modern Graph Created");
            break;
        case "crew":
            graph = TinkerFactory.createTheCrew();
            break;
        default:
            graph = TinkerGraph.open();
            System.out.println("Graph Created");
            long startTime = System.nanoTime();
            graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph"));
            long endTime = System.nanoTime();
            System.out.println("Time taken to load graph from kyro file: " + (endTime - startTime) / 1000000
                    + " mili seconds");
            break;
        }
    } else {

        graph = TinkerFactory.createModern();
    }

    final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph,
            queryString);

    printWithHeadline("SPARQL Query", queryString);
    printWithHeadline("Traversal (prior execution)", traversal);

    Bytecode traversalByteCode = traversal.asAdmin().getBytecode();

    //JavaTranslator.of(graph.traversal()).translate(traversalByteCode);

    System.out.println("the Byte Code : " + traversalByteCode.toString());
    printWithHeadline("Result", String.join(System.lineSeparator(), JavaTranslator.of(graph.traversal())
            .translate(traversalByteCode).toStream().map(Object::toString).collect(Collectors.toList())));
    printWithHeadline("Traversal (after execution)", traversal);
}

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  ww. j  a v  a 2 s .co m
        for (int i = 0; i < av.length; i++)
            new SimpleCalcStreamTok(av[i]).doCalc();
}

From source file:org.javaee7.ejb.stateless.remote.AccountSessionBeanWithInterface.java

public static void main(String[] args) {
    try {//from   w w  w  . j ava2s .co  m
        ObjectMapper mapper = new ObjectMapper();
        URL url = new URL("http://localhost:8180/account-1.0-SNAPSHOT/statistics");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        String result = null;
        while ((output = br.readLine()) != null) {
            result = result + output;
        }
        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
}

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

/**
 * Launches the interactive game server registration.
 * //from  w ww.  j a va  2 s.  c  o m
 * @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);
    }
}

From source file:de.inpiraten.jdemocrator.TAN.generator.TANGenerator.java

public static void main(String[] args) {

    //Intro message
    GPL.printLicenseNotice();/*from ww w  .j  ava2  s . c o  m*/
    System.out.println("\njDemocrator Authority TAN Generator");
    System.out.println("===================================\n");

    System.out.println("This programm will generate voting TANs for a semi-online secrete voting.");

    try {
        //Initialize TAN Generator
        TANGenerator G = new TANGenerator(new BufferedReader(new InputStreamReader(System.in)));

        //Randomly generate master TANs
        G.generateMasterTANs();

        //Generate TANs from master TANs
        TAN[][] tans = new TAN[G.event.numberOfElections][];
        for (int i = 0; i < tans.length; i++) {
            try {
                tans[i] = G.event.TANType.generateFromMasterTAN(G.masterTAN[i], G.event,
                        G.event.numberOfVoters);
            } catch (NoSuchAlgorithmException e) {
                System.out.println("The Key Derivation function described as " + G.event.keyDerivationFunction
                        + " is not supported. Exiting.");
                System.exit(2);
            } catch (InvalidKeySpecException e) {
                System.out.println("Invalied Key Spec Exception while generating TANs. Exiting.");
                System.exit(3);
            }
        }

        //Mix up the TANs
        for (int i = 0; i < tans.length; i++) {
            shuffle(tans[i]);
        }

        //TODO Write the TANs and master TANs to (printable) files
    } catch (IOException e) {
        System.out.println("An I/O Error occured");
        System.exit(1);
    }

}