Example usage for java.io BufferedReader BufferedReader

List of usage examples for java.io BufferedReader BufferedReader

Introduction

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

Prototype

public BufferedReader(Reader in) 

Source Link

Document

Creates a buffering character-input stream that uses a default-sized input buffer.

Usage

From source file:com.gomoob.embedded.EmbeddedMongo.java

/**
 * Main entry of the program./*from  w  w  w. j  a v  a2s  .c o  m*/
 * 
 * @param args arguments used to customize starting.
 * 
 * @throws Exception If an error occured while executing the server.
 */
public static void main(String[] args) throws Exception {

    // Creates a default execution context, then the configuration of this context can be changed depending on the 
    // command line parameters received.
    context = new Context();

    // Parse the command line
    parseCommandLine(args);

    boolean terminated = false;

    System.out.println("MONGOD_HOST=" + context.getMongoContext().getNet().getServerAddress().getHostName());
    System.out.println("MONGOD_PORT=" + context.getMongoContext().getNet().getPort());
    System.out.println("SERVER_SOCKET_PORT=" + context.getSocketContext().getServerSocket().getLocalPort());

    Socket socket = null;
    BufferedReader reader = null;
    Writer writer = null;

    while (!terminated) {

        socket = context.getSocketContext().getServerSocket().accept();

        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new OutputStreamWriter(new DataOutputStream(socket.getOutputStream()));

        System.out.println("Waiting for command...");
        String commandString = reader.readLine();
        System.out.println(commandString);

        ICommand command = parseCommandString(commandString);

        IResponse response = command.run(context);

        writer.write(response.toJSON());

        writer.close();

        // If the current socket is opened close it
        if (!socket.isClosed()) {
            socket.close();
        }

        // If stop is required
        terminated = response.isTerminationRequired();

    }

    context.getSocketContext().getServerSocket().close();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

public static void main(String[] args) {
    // first get the db connection properties
    String url = urlSet.get(args[1]);
    String user = args[2];//from w ww  .  j  a v  a 2  s  . co m
    String word = args[3];

    // make sure we have the Oracle driver somewhere
    try {
        Class.forName("oracle.jdbc.OracleDriver");
        Class.forName("org.postgresql.Driver");
    } catch (Exception x) {
        System.out.println("Unable to load the driver class!");
        System.exit(0);
    }
    // connect to the database
    try {
        dbConnection = DriverManager.getConnection(url, user, word);
        ClinicalBean.setDBConnection(dbConnection);
    } catch (SQLException x) {
        x.printStackTrace();
        System.exit(1);
    }

    final String xmlList = args[0];
    BufferedReader br = null;
    try {
        final Map<String, String> clinicalFiles = new HashMap<String, String>();
        final Map<String, String> biospecimenFiles = new HashMap<String, String>();
        final Map<String, String> fullFiles = new HashMap<String, String>();

        //noinspection IOResourceOpenedButNotSafelyClosed
        br = new BufferedReader(new FileReader(xmlList));

        // read the file list to get all the files to load
        while (br.ready()) {
            final String[] in = br.readLine().split("\\t");
            String xmlfile = in[0];
            String archive = in[1];

            if (xmlfile.contains("_clinical")) {
                clinicalFiles.put(xmlfile, archive);
            } else if (xmlfile.contains("_biospecimen")) {
                biospecimenFiles.put(xmlfile, archive);
            } else {
                fullFiles.put(xmlfile, archive);
            }
        }

        Date dateAdded = Calendar.getInstance().getTime();

        // NOTE!!! This deletes all data before the load starts, assuming we are re-loading everything.
        // a better way would be to figure out what has changed and load that, or to be able to load multiple versions of the data in the schema
        emptyClinicalTables(user);

        // load any "full" files first -- in case some archives aren't split yet
        for (final String file : fullFiles.keySet()) {
            String archive = fullFiles.get(file);
            System.out.println("Full file " + file + " in " + archive);
            // need to re-instantiate the disease-specific beans for each file
            createDiseaseSpecificBeans(xmlList);
            String disease = getDiseaseName(archive);
            processFullXmlFile(file, archive, disease, dateAdded);

            // memory leak or something... have to commit and close all connections and re-get connection
            // after each file to keep from using too much heap space.  this troubles me, but I have never had
            // the time to figure out why it happens
            resetConnections(url, user, word);
        }

        // now process all clinical files, and insert patients and clinical data
        for (final String clinicalFile : clinicalFiles.keySet()) {
            createDiseaseSpecificBeans(xmlList);
            String archive = clinicalFiles.get(clinicalFile);
            System.out.println("Clinical file " + clinicalFile + " in " + archive);
            String disease = getDiseaseName(archive);
            processClinicalXmlFile(clinicalFile, archive, disease, dateAdded);
            resetConnections(url, user, word);
        }

        // now process biospecimen files
        for (final String biospecimenFile : biospecimenFiles.keySet()) {
            createDiseaseSpecificBeans(xmlList);
            String archive = biospecimenFiles.get(biospecimenFile);
            String disease = getDiseaseName(archive);
            System.out.println("Biospecimen file " + biospecimenFile);
            processBiospecimenXmlFile(biospecimenFile, archive, disease, dateAdded);
            resetConnections(url, user, word);
        }

        // this sets relationships between these clinical tables and data browser tables, since we delete
        // and reload every time
        setForeignKeys();
        dbConnection.commit();
        dbConnection.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:io.apiman.tools.jdbc.ApimanJdbcServer.java

public static void main(String[] args) {
    try {//  w ww . ja va 2s.  c om
        File dataDir = new File("target/h2");
        String url = "jdbc:h2:tcp://localhost:9092/apiman";

        if (dataDir.exists()) {
            FileUtils.deleteDirectory(dataDir);
        }
        dataDir.mkdirs();

        Server.createTcpServer("-tcpPassword", "sa", "-baseDir", dataDir.getAbsolutePath(), "-tcpPort", "9092",
                "-tcpAllowOthers").start();
        Class.forName("org.h2.Driver");

        try (Connection connection = DriverManager.getConnection(url, "sa", "")) {
            System.out.println("Connection Established: " + connection.getMetaData().getDatabaseProductName()
                    + "/" + connection.getCatalog());
            executeUpdate(connection,
                    "CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username))");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')");
            executeUpdate(connection,
                    "INSERT INTO users (username, password) VALUES ('ballen', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')");
            executeUpdate(connection,
                    "CREATE TABLE roles (rolename varchar(255) NOT NULL, username varchar(255) NOT NULL)");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('user', 'bwayne')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('admin', 'bwayne')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ckent', 'user')");
            executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ballen', 'user')");
        }

        System.out.println("======================================================");
        System.out.println("JDBC (H2) server started successfully.");
        System.out.println("");
        System.out.println("  Data: " + dataDir.getAbsolutePath());
        System.out.println("  JDBC URL: " + url);
        System.out.println("  JDBC User: sa");
        System.out.println("  JDBC Password: ");
        System.out.println(
                "  Authentication Query:   SELECT * FROM users u WHERE u.username = ? AND u.password = ?");
        System.out.println("  Authorization Query:    SELECT r.rolename FROM roles r WHERE r.username = ?");
        System.out.println("======================================================");
        System.out.println("");
        System.out.println("");
        System.out.println("Press Enter to stop the JDBC server.");
        new BufferedReader(new InputStreamReader(System.in)).readLine();

        System.out.println("Shutting down the JDBC server...");

        Server.shutdownTcpServer("tcp://localhost:9092", "", true, true);

        System.out.println("Done!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.bitsofproof.example.Simple.java

public static void main(String[] args) {
    Security.addProvider(new BouncyCastleProvider());

    final CommandLineParser parser = new GnuParser();
    final Options gnuOptions = new Options();
    gnuOptions.addOption("h", "help", false, "I can't help you yet");
    gnuOptions.addOption("s", "server", true, "Server URL");
    gnuOptions.addOption("u", "user", true, "User");
    gnuOptions.addOption("p", "password", true, "Password");

    System.out.println("BOP Bitcoin Server Simple Client 3.5.0 (c) 2013-2014 bits of proof zrt.");
    CommandLine cl = null;/*from w w w .  jav a  2  s  .  c  o m*/
    String url = null;
    String user = null;
    String password = null;
    try {
        cl = parser.parse(gnuOptions, args);
        url = cl.getOptionValue('s');
        user = cl.getOptionValue('u');
        password = cl.getOptionValue('p');
    } catch (org.apache.commons.cli.ParseException e) {
        e.printStackTrace();
        System.exit(1);
    }
    if (url == null || user == null || password == null) {
        System.err.println("Need -s server -u user -p password");
        System.exit(1);
    }

    BCSAPI api = getServer(url, user, password);
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        long start = System.currentTimeMillis();
        api.ping(start);
        System.out.println("Server round trip " + (System.currentTimeMillis() - start) + "ms");
        api.addAlertListener(new AlertListener() {
            @Override
            public void alert(String s, int severity) {
                System.err.println("ALERT: " + s);
            }
        });
        System.out.println("Talking to " + (api.isProduction() ? "PRODUCTION" : "test") + " server");
        ConfirmationManager confirmationManager = new ConfirmationManager();
        confirmationManager.init(api, 144);
        System.out.printf("Please enter wallet name: ");
        String wallet = input.readLine();
        SimpleFileWallet w = new SimpleFileWallet(wallet + ".wallet");
        TransactionFactory am = null;
        if (!w.exists()) {
            System.out.printf("Enter passphrase: ");
            String passphrase = input.readLine();
            System.out.printf("Enter master (empty for new): ");
            String master = input.readLine();
            if (master.equals("")) {
                w.init(passphrase);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
            } else {
                StringTokenizer tokenizer = new StringTokenizer(master, "@");
                String key = tokenizer.nextToken();
                long since = 0;
                if (tokenizer.hasMoreElements()) {
                    since = Long.parseLong(tokenizer.nextToken()) * 1000;
                }
                w.init(passphrase, ExtendedKey.parse(key), true, since);
                w.unlock(passphrase);
                System.out.printf("First account: ");
                String account = input.readLine();
                am = w.createAccountManager(account);
                w.lock();
                w.persist();
                w.sync(api);
            }
        } else {
            w = SimpleFileWallet.read(wallet + ".wallet");
            w.sync(api);
            List<String> names = w.getAccountNames();
            System.out.println("Accounts:");
            System.out.println("---------");
            String first = null;
            for (String name : names) {
                System.out.println(name);
                if (first == null) {
                    first = name;
                }
            }
            System.out.println("---------");
            am = w.getAccountManager(first);
            System.out.println("Using account " + first);
        }
        confirmationManager.addAccount(am);
        api.registerTransactionListener(am);

        while (true) {
            printMenu();
            String answer = input.readLine();
            System.out.printf("\n");
            if (answer.equals("1")) {
                System.out.printf("The balance is: " + printBit(am.getBalance()) + "\n");
                System.out.printf("     confirmed: " + printBit(am.getConfirmed()) + "\n");
                System.out.printf("    receiveing: " + printBit(am.getReceiving()) + "\n");
                System.out.printf("        change: " + printBit(am.getChange()) + "\n");
                System.out.printf("(      sending: " + printBit(am.getSending()) + ")\n");
            } else if (answer.equals("2")) {
                for (Address a : am.getAddresses()) {
                    System.out.printf(a + "\n");
                }
            } else if (answer.equals("3")) {
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
            } else if (answer.equals("4")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                ExtendedKeyAccountManager im = (ExtendedKeyAccountManager) am;
                System.out.printf(
                        im.getMaster().serialize(api.isProduction()) + "@" + im.getCreated() / 1000 + "\n");
                w.lock();
            } else if (answer.equals("5")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.printf("Number of recipients");
                Integer nr = Integer.valueOf(input.readLine());
                Transaction spend;
                if (nr.intValue() == 1) {
                    System.out.printf("Receiver address: ");
                    String address = input.readLine();
                    System.out.printf("amount (Bit): ");
                    long amount = parseBit(input.readLine());
                    spend = am.pay(Address.fromSatoshiStyle(address), amount);
                    System.out.println("About to send " + printBit(amount) + " to " + address);
                } else {
                    List<Address> addresses = new ArrayList<>();
                    List<Long> amounts = new ArrayList<>();
                    long total = 0;
                    for (int i = 0; i < nr; ++i) {
                        System.out.printf("Receiver address: ");
                        String address = input.readLine();
                        addresses.add(Address.fromSatoshiStyle(address));
                        System.out.printf("amount (Bit): ");
                        long amount = parseBit(input.readLine());
                        amounts.add(amount);
                        total += amount;
                    }
                    spend = am.pay(addresses, amounts);
                    System.out.println("About to send " + printBit(total));
                }
                System.out.println("inputs");
                for (TransactionInput in : spend.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : spend.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                w.lock();
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(spend);
                    System.out.printf("Sent transaction: " + spend.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else if (answer.equals("6")) {
                System.out.printf("Address: ");
                Set<Address> match = new HashSet<Address>();
                match.add(Address.fromSatoshiStyle(input.readLine()));
                api.scanTransactionsForAddresses(match, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("7")) {
                System.out.printf("Public key: ");
                ExtendedKey ek = ExtendedKey.parse(input.readLine());
                api.scanTransactions(ek, 0, 10, 0, new TransactionListener() {
                    @Override
                    public boolean process(Transaction t) {
                        System.out.printf("Found transaction: " + t.getHash() + "\n");
                        return true;
                    }
                });
            } else if (answer.equals("a")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                am = w.getAccountManager(account);
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("c")) {
                System.out.printf("Enter account name: ");
                String account = input.readLine();
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                am = w.createAccountManager(account);
                System.out.println("using account: " + account);
                w.lock();
                w.persist();
                api.registerTransactionListener(am);
                confirmationManager.addAccount(am);
            } else if (answer.equals("m")) {
                System.out.printf("Enter passphrase: ");
                String passphrase = input.readLine();
                w.unlock(passphrase);
                System.out.println(w.getMaster().serialize(api.isProduction()));
                System.out.println(w.getMaster().getReadOnly().serialize(true));
                w.lock();
            } else if (answer.equals("s")) {
                System.out.printf("Enter private key: ");
                String key = input.readLine();
                ECKeyPair k = ECKeyPair.parseWIF(key);
                KeyListAccountManager alm = new KeyListAccountManager();
                alm.addKey(k);
                alm.syncHistory(api);
                Address a = am.getNextReceiverAddress();
                Transaction t = alm.pay(a, alm.getBalance(), PaymentOptions.receiverPaysFee);
                System.out.println("About to sweep " + printBit(alm.getBalance()) + " to " + a);
                System.out.println("inputs");
                for (TransactionInput in : t.getInputs()) {
                    System.out.println(in.getSourceHash() + " " + in.getIx());
                }
                System.out.println("outputs");
                for (TransactionOutput out : t.getOutputs()) {
                    System.out.println(out.getOutputAddress() + " " + printBit(out.getValue()));
                }
                System.out.printf("Type yes to go: ");
                if (input.readLine().equals("yes")) {
                    api.sendTransaction(t);
                    System.out.printf("Sent transaction: " + t.getHash());
                } else {
                    System.out.printf("Nothing happened.");
                }
            } else {
                System.exit(0);
            }
        }
    } catch (Exception e) {
        System.err.println("Something went wrong");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.mijecu25.sqlplus.SQLPlus.java

public static void main(String[] args) throws IOException {
    // Create and load the properties from the application properties file
    Properties properties = new Properties();
    properties.load(SQLPlus.class.getClassLoader().getResourceAsStream(SQLPlus.APPLICATION_PROPERTIES_FILE));

    SQLPlus.logger.info("Initializing " + SQLPlus.PROGRAM_NAME + " version "
            + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));

    // Check if the user is using a valid console (i.e. not from Eclipse)
    if (System.console() == null) {
        // The Console object for the JVM could not be found. Alert the user 
        SQLPlus.logger.fatal(Messages.FATAL + "A JVM Console object was not found. Try running "
                + SQLPlus.PROGRAM_NAME + "from the command line");
        System.out.println(// w ww. ja v  a 2  s  . c om
                Messages.FATAL + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. "
                        + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line.");

        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(PROGRAM_NAME));
        return;
    }

    // UI intro
    System.out.println("Welcome to " + SQLPlus.PROGRAM_NAME
            + "! This program has a DSL to add alerts to various SQL DML events.");
    System.out.println("Be sure to use " + SQLPlus.PROGRAM_NAME + " from the command line.");
    System.out.println();

    // Get the version
    System.out.println("Version: " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));
    System.out.println();

    // Read the license file
    BufferedReader bufferedReader;
    bufferedReader = new BufferedReader(new FileReader(SQLPlus.LICENSE_FILE));

    // Read a line
    String line = bufferedReader.readLine();

    // While the line is not null
    while (line != null) {
        System.out.println(line);

        // Read a new lines
        line = bufferedReader.readLine();
    }

    // Close the buffer
    bufferedReader.close();
    System.out.println();

    // Create the jline console that allows us to remember commands, use arrow keys, and catch interruptions
    // from the user
    SQLPlus.console = new ConsoleReader();
    SQLPlus.console.setHandleUserInterrupt(true);

    try {
        // Get credentials from the user
        SQLPlus.logger.info("Create SQLPlusConnection");
        SQLPlus.createSQLPlusConnection();
    } catch (NullPointerException | SQLException | IllegalArgumentException e) {
        // NPE: This exception can occur if the user is running the program where the JVM Console
        // object cannot be found.
        // SQLE: TODO should I add here the error code?
        // This exception can occur when trying to establish a connection
        // IAE: This exception can occur when trying to establish a connection
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, e.getClass().getName()));
        System.out.println(Messages.FATAL + Messages.FATAL_EXCEPTION_ACTION(e.getClass().getSimpleName()) + " "
                + Messages.CHECK_LOG_FILES);
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
        return;
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();

        return;
    }

    System.out.println("Connection established! Commands end with " + SQLPlus.END_OF_COMMAND);
    System.out.println("Type " + SQLPlus.EXIT + " or " + SQLPlus.QUIT + " to exit the application ");

    try {
        // Execute the input scanner
        while (true) {
            // Get a line from the user until the hit enter (carriage return, line feed/ new line).
            System.out.print(SQLPlus.PROMPT);
            try {
                line = SQLPlus.console.readLine().trim();
            } catch (NullPointerException npe) {
                // TODO test this behavior
                // If this exception is catch, it is very likely that the user entered the end of line command.
                // This means that the program should quit.
                SQLPlus.logger.warn(Messages.WARNING + "The input from the user is null. It is very likely that"
                        + "the user entered the end of line command and they want to quit.");
                SQLPlus.exitSQLPlus();

                return;
            }

            // If the user did not enter anything
            if (line.isEmpty()) {
                // Continue to the next iteration
                continue;
            }

            if (line.equals(".")) {
                line = "use courses;";
            }

            if (line.equals("-")) {
                line = "select created_at from classes;";
            }

            if (line.equals("--")) {
                line = "select name, year from classes;";
            }

            if (line.equals("*")) {
                line = "select * from classes;";
            }

            if (line.equals("x")) {
                line = "select name from classes, classes;";
            }

            if (line.equals("e")) {
                line = "select * feom classes;";
            }

            // Logic to quit
            if (line.equals(SQLPlus.QUIT) || line.equals(SQLPlus.EXIT)) {
                SQLPlus.logger.info("The user wants to quit " + SQLPlus.PROGRAM_NAME);
                SQLPlus.exitSQLPlus();
                break;
            }

            // Use a StringBuilder since jline works weird when it has read a line. The issue we were having was with the
            // end of command logic. jline does not keep the input from the user in the variable that was stored in. Each
            // time jline reads a new line, the variable is empty
            StringBuilder query = new StringBuilder();
            query.append(line);

            // While the user does not finish the command with the SQLPlus.END_OF_COMMAND
            while (query.charAt(query.length() - 1) != SQLPlus.END_OF_COMMAND) {
                // Print the wait for command prompt and get the next line for the user
                System.out.print(SQLPlus.WAIT_FOR_END_OF_COMMAND);
                query.append(" ");
                line = StringUtils.stripEnd(SQLPlus.console.readLine(), null);
                query.append(line);
            }

            SQLPlus.logger.info("Raw input from the user: " + query);

            try {
                Statement statement;

                try {
                    // Execute the antlr code to parse the user input
                    SQLPlus.logger.info("Will parse the user input to determine what to execute");
                    ANTLRStringStream input = new ANTLRStringStream(query.toString());
                    SQLPlusLex lexer = new SQLPlusLex(input);
                    CommonTokenStream tokens = new CommonTokenStream(lexer);
                    SQLPlusParser parser = new SQLPlusParser(tokens);

                    statement = parser.sqlplus();
                } catch (RecognitionException re) {
                    // TODO move this to somehwere else
                    //                        String message = Messages.WARNING + "You have an error in your SQL syntax. Check the manual"
                    //                                + " that corresponds to your " + SQLPlus.sqlPlusConnection.getCurrentDatabase()
                    //                                + " server or " + SQLPlus.PROGRAM_NAME + " for the correct syntax";
                    //                        SQLPlus.logger.warn(message);
                    //                        System.out.println(message);
                    statement = new StatementDefault();
                }

                statement.setStatement(query.toString());
                SQLPlus.sqlPlusConnection.execute(statement);
            } catch (UnsupportedOperationException uoe) {
                // This exception can occur when the user entered a command allowed by the parsers, but not currently
                // supported by SQLPlus. This can occur because the parser is written in such a way that supports
                // the addition of features.
                SQLPlus.logger.warn(Messages.WARNING + uoe);
                System.out.println(
                        Messages.WARNING + Messages.FATAL_EXCEPTION_ACTION(uoe.getClass().getSimpleName()) + " "
                                + Messages.CHECK_LOG_FILES);
                SQLPlus.logger.warn(Messages.WARNING + "The previous command is not currently supported.");
            }

        }
    } catch (IllegalArgumentException iae) {
        // This exception can occur when a command is executed but it had illegal arguments. Most likely
        // it is a programmer's error and should be addressed by the developer.
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, iae.getClass().getName()));
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();
    }
}

From source file:com.yahoo.athenz.example.ztoken.HttpExampleClient.java

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

    // parse our command line to retrieve required input

    CommandLine cmd = parseCommandLine(args);

    String domainName = cmd.getOptionValue("domain");
    String serviceName = cmd.getOptionValue("service");
    String privateKeyPath = cmd.getOptionValue("pkey");
    String keyId = cmd.getOptionValue("keyid");
    String url = cmd.getOptionValue("url");
    String ztsUrl = cmd.getOptionValue("ztsurl");
    String providerDomain = cmd.getOptionValue("provider-domain");
    String providerRole = cmd.getOptionValue("provider-role");

    // we need to generate our principal credentials (ntoken). In
    // addition to the domain and service names, we need the
    // the service's private key and the key identifier - the
    // service with the corresponding public key must already be
    // registered in ZMS

    PrivateKey privateKey = Crypto.loadPrivateKey(new File(privateKeyPath));
    ServiceIdentityProvider identityProvider = new SimpleServiceIdentityProvider(domainName, serviceName,
            privateKey, keyId);/*from  ww w . j  a va2  s  .c o m*/

    // now we need to retrieve a role token (ztoken) for accessing
    // the provider Athenz enabled service

    RoleToken roleToken = null;
    try (ZTSClient ztsClient = new ZTSClient(ztsUrl, domainName, serviceName, identityProvider)) {
        roleToken = ztsClient.getRoleToken(providerDomain, providerRole);
    }

    if (roleToken == null) {
        System.out.println(
                "Unable to retrieve role token for: " + providerRole + " in domain: " + providerDomain);
        System.exit(1);
    }

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // set our Athenz credentials. The ZTSClient provides the header
    // name that we must use for authorization token while the role
    // token itself provides the token string (ztoken).

    System.out.println("Using RoleToken: " + roleToken.getToken());
    con.setRequestProperty(ZTSClient.getHeader(), roleToken.getToken());

    // now process our request

    int responseCode = con.getResponseCode();
    switch (responseCode) {
    case HttpURLConnection.HTTP_FORBIDDEN:
        System.out.println("Request was forbidden - not authorized: " + con.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        System.out.println("Successful response: ");
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
        }
        break;
    default:
        System.out.println("Request failed - response status code: " + responseCode);
    }
}

From source file:com.kappaware.logtrawler.Main.java

@SuppressWarnings("static-access")
static public void main(String[] argv) throws Throwable {

    Config config;/*from   w  w w. ja v a  2  s . c o  m*/

    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("config-file")
            .withDescription("JSON configuration file").create("c"));
    options.addOption(OptionBuilder.hasArg().withArgName("folder").withLongOpt("folder")
            .withDescription("Folder to monitor").create("f"));
    options.addOption(OptionBuilder.hasArg().withArgName("exclusion").withLongOpt("exclusion")
            .withDescription("Exclusion regex").create("x"));
    options.addOption(OptionBuilder.hasArg().withArgName("adminEndpoint").withLongOpt("admin-endpoint")
            .withDescription("Endpoint for admin REST").create("e"));
    options.addOption(OptionBuilder.hasArg().withArgName("outputFlow").withLongOpt("output-flow")
            .withDescription("Target to post result on").create("o"));
    options.addOption(OptionBuilder.hasArg().withArgName("hostname").withLongOpt("hostname")
            .withDescription("This hostname").create("h"));
    options.addOption(OptionBuilder.withLongOpt("displayDot").withDescription("Display Dot").create("d"));
    options.addOption(OptionBuilder.hasArg().withArgName("mimeType").withLongOpt("mime-type")
            .withDescription("Valid MIME type").create("m"));
    options.addOption(OptionBuilder.hasArg().withArgName("allowedAdmin").withLongOpt("allowedAdmin")
            .withDescription("Allowed admin network").create("a"));
    options.addOption(OptionBuilder.hasArg().withArgName("configFile").withLongOpt("gen-config-file")
            .withDescription("Generate JSON configuration file").create("g"));
    options.addOption(OptionBuilder.hasArg().withArgName("maxBatchSize").withLongOpt("max-batch-size")
            .withDescription("Max JSON batch (array) size").create("b"));

    CommandLineParser clParser = new BasicParser();
    CommandLine line;
    String configFile = null;
    try {
        // parse the command line argument
        line = clParser.parse(options, argv);
        if (line.hasOption("c")) {
            configFile = line.getOptionValue("c");
            config = Json.fromJson(Config.class,
                    new BufferedReader(new InputStreamReader(new FileInputStream(configFile))));
        } else {
            config = new Config();
        }
        if (line.hasOption("f")) {
            String[] fs = line.getOptionValues("f");
            // Get the first agent (Create it if needed)
            if (config.getAgents() == null || config.getAgents().size() == 0) {
                Config.Agent agent = new Config.Agent("default");
                config.addAgent(agent);
            }
            Config.Agent agent = config.getAgents().iterator().next();
            for (String f : fs) {
                agent.addFolder(new Config.Agent.Folder(f, false));
            }
        }
        if (line.hasOption("e")) {
            String e = line.getOptionValue("e");
            config.setAdminEndpoint(e);
        }
        if (line.hasOption("o")) {
            String[] es = line.getOptionValues("o");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    for (String s : es) {
                        agent.addOuputFlow(s);
                    }
                }
            }
        }
        if (line.hasOption("h")) {
            String e = line.getOptionValue("h");
            config.setHostname(e);
        }
        if (line.hasOption("x")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    if (agent.getFolders() != null) {
                        for (Folder folder : agent.getFolders()) {
                            String[] exs = line.getOptionValues("x");
                            for (String ex : exs) {
                                folder.addExcludedPath(ex);
                            }
                        }
                    }
                }
            }
        }
        if (line.hasOption("m")) {
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    String[] exs = line.getOptionValues("m");
                    for (String ex : exs) {
                        agent.addLogMimeType(ex);
                    }
                }
            }
        }
        if (line.hasOption("a")) {
            String[] exs = line.getOptionValues("a");
            for (String ex : exs) {
                config.addAdminAllowedNetwork(ex);
            }
        }
        if (line.hasOption("d")) {
            config.setDisplayDot(true);
        }
        if (line.hasOption("b")) {
            Integer i = getIntegerParameter(line, "b");
            if (config.getAgents() != null) {
                for (Agent agent : config.getAgents()) {
                    agent.setOutputMaxBatchSize(i);
                }
            }
        }
        config.setDefault();
        if (line.hasOption("g")) {
            String fileName = line.getOptionValue("g");
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, false)));
            out.println(Json.toJson(config, true));
            out.flush();
            out.close();
            System.exit(0);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        usage(options, exp.getMessage());
        return;
    }

    try {
        // Check config
        if (config.getAgents() == null || config.getAgents().size() < 1) {
            throw new ConfigurationException("At least one folder to monitor must be provided!");
        }
        Map<String, AgentHandler> agentHandlerByName = new HashMap<String, AgentHandler>();
        for (Config.Agent agent : config.getAgents()) {
            agentHandlerByName.put(agent.getName(), new AgentHandler(agent));
        }
        if (!Utils.isNullOrEmpty(config.getAdminEndpoint())) {
            new AdminServer(config, agentHandlerByName);
        }
    } catch (ConfigurationException e) {
        log.error(e.toString());
        System.exit(1);
    } catch (Throwable t) {
        log.error("Error in main", t);
        System.exit(2);
    }
}

From source file:ms1quant.MS1Quant.java

/**
 * @param args the command line arguments MS1Quant parameterfile
 *//*from ww  w  .j ava  2  s  .  c  o m*/
public static void main(String[] args) throws Exception {

    BufferedReader reader = null;
    try {
        System.out.println(
                "=================================================================================================");
        System.out.println("Umpire MS1 quantification and feature detection analysis (version: "
                + UmpireInfo.GetInstance().Version + ")");
        if (args.length < 3 || !args[1].startsWith("-mode")) {
            System.out
                    .println("command : java -jar -Xmx10G MS1Quant.jar ms1quant.params -mode[1 or 2] [Option]");
            System.out.println("\n-mode");
            System.out.println("\t1:Single file mode--> mzXML_file PepXML_file");
            System.out.println("\t\tEx: -mode1 file1.mzXML file1.pep.xml");
            System.out.println(
                    "\t2:Folder mode--> mzXML_Folder PepXML_Folder, all generated csv tables will be merged into a single csv file");
            System.out.println("\t\tEx: -mode2 /data/mzxml/ /data/pepxml/");
            System.out.println("\nOptions");
            System.out.println(
                    "\t-C\tNo of concurrent files to be processed (only for folder mode), Ex. -C5, default:1");
            System.out.println("\t-p\tMinimum probability, Ex. -p0.9, default:0.9");
            System.out.println("\t-ID\tDetect identified feature only");
            System.out.println("\t-O\toutput folder, Ex. -O/data/");
            return;
        }
        ConsoleLogger consoleLogger = new ConsoleLogger();
        consoleLogger.SetConsoleLogger(Level.DEBUG);
        consoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "ms1quant_debug.log");
        Logger logger = Logger.getRootLogger();
        logger.debug("Command: " + Arrays.toString(args));
        logger.info("MS1Quant version: " + UmpireInfo.GetInstance().Version);

        String parameterfile = args[0];
        logger.info("Parameter file: " + parameterfile);
        File paramfile = new File(parameterfile);
        if (!paramfile.exists()) {
            logger.error("Parameter file " + paramfile.getAbsolutePath()
                    + " cannot be found. The program will exit.");
        }

        reader = new BufferedReader(new FileReader(paramfile.getAbsolutePath()));
        String line = "";
        InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600);
        int NoCPUs = 2;
        int NoFile = 1;
        param.DetermineBGByID = false;
        param.EstimateBG = true;

        //<editor-fold defaultstate="collapsed" desc="Read parameter file">
        while ((line = reader.readLine()) != null) {
            if (!"".equals(line) && !line.startsWith("#")) {
                logger.info(line);
                //System.out.println(line);
                if (line.split("=").length < 2) {
                    continue;
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                if (type.startsWith("para.")) {
                    type = type.replace("para.", "SE.");
                }
                String value = line.split("=")[1].trim();
                switch (type) {
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                //<editor-fold defaultstate="collapsed" desc="instrument parameters">

                case "SE.MS1PPM": {
                    param.MS1PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2PPM": {
                    param.MS2PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.SN": {
                    param.SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2SN": {
                    param.MS2SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSIntensity": {
                    param.MinMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSMSIntensity": {
                    param.MinMSMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinRTRange": {
                    param.MinRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.MaxNoPeakCluster": {
                    param.MaxNoPeakCluster = Integer.parseInt(value);
                    param.MaxMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinNoPeakCluster": {
                    param.MinNoPeakCluster = Integer.parseInt(value);
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinMS2NoPeakCluster": {
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MaxCurveRTRange": {
                    param.MaxCurveRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.Resolution": {
                    param.Resolution = Integer.parseInt(value);
                    break;
                }
                case "SE.RTtol": {
                    param.RTtol = Float.parseFloat(value);
                    break;
                }
                case "SE.NoPeakPerMin": {
                    param.NoPeakPerMin = Integer.parseInt(value);
                    break;
                }
                case "SE.StartCharge": {
                    param.StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.EndCharge": {
                    param.EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2StartCharge": {
                    param.MS2StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2EndCharge": {
                    param.MS2EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.NoMissedScan": {
                    param.NoMissedScan = Integer.parseInt(value);
                    break;
                }
                case "SE.Denoise": {
                    param.Denoise = Boolean.valueOf(value);
                    break;
                }
                case "SE.EstimateBG": {
                    param.EstimateBG = Boolean.valueOf(value);
                    break;
                }
                case "SE.RemoveGroupedPeaks": {
                    param.RemoveGroupedPeaks = Boolean.valueOf(value);
                    break;
                }
                case "SE.MinFrag": {
                    param.MinFrag = Integer.parseInt(value);
                    break;
                }
                case "SE.IsoPattern": {
                    param.IsoPattern = Float.valueOf(value);
                    break;
                }
                case "SE.StartRT": {
                    param.startRT = Float.valueOf(value);
                }
                case "SE.EndRT": {
                    param.endRT = Float.valueOf(value);
                }

                //</editor-fold>
                }
            }
        }
        //</editor-fold>

        int mode = 1;
        if (args[1].equals("-mode2")) {
            mode = 2;
        } else if (args[1].equals("-mode1")) {
            mode = 1;
        } else {
            logger.error("-mode number not recongized. The program will exit.");
        }

        String mzXML = "";
        String pepXML = "";
        String mzXMLPath = "";
        String pepXMLPath = "";
        File mzXMLfile = null;
        File pepXMLfile = null;
        File mzXMLfolder = null;
        File pepXMLfolder = null;
        int idx = 0;
        if (mode == 1) {
            mzXML = args[2];
            logger.info("Mode1 mzXML file: " + mzXML);
            mzXMLfile = new File(mzXML);
            if (!mzXMLfile.exists()) {
                logger.error("Mode1 mzXML file " + mzXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            pepXML = args[3];
            logger.info("Mode1 pepXML file: " + pepXML);
            pepXMLfile = new File(pepXML);
            if (!pepXMLfile.exists()) {
                logger.error("Mode1 pepXML file " + pepXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            idx = 4;
        } else if (mode == 2) {
            mzXMLPath = args[2];
            logger.info("Mode2 mzXML folder: " + mzXMLPath);
            mzXMLfolder = new File(mzXMLPath);
            if (!mzXMLfolder.exists()) {
                logger.error("Mode2 mzXML folder " + mzXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            pepXMLPath = args[3];
            logger.info("Mode2 pepXML folder: " + pepXMLPath);
            pepXMLfolder = new File(pepXMLPath);
            if (!pepXMLfolder.exists()) {
                logger.error("Mode2 pepXML folder " + pepXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            idx = 4;
        }

        String outputfolder = "";
        float MinProb = 0f;
        for (int i = idx; i < args.length; i++) {
            if (args[i].startsWith("-")) {
                if (args[i].equals("-ID")) {
                    param.TargetIDOnly = true;
                    logger.info("Detect ID feature only: true");
                }
                if (args[i].startsWith("-O")) {
                    outputfolder = args[i].substring(2);
                    logger.info("Output folder: " + outputfolder);

                    File outputfile = new File(outputfolder);
                    if (!outputfolder.endsWith("\\") | outputfolder.endsWith("/")) {
                        outputfolder += "/";
                    }
                    if (!outputfile.exists()) {
                        outputfile.mkdir();
                    }
                }
                if (args[i].startsWith("-C")) {
                    try {
                        NoFile = Integer.parseInt(args[i].substring(2));
                        logger.info("No of concurrent files: " + NoFile);
                    } catch (Exception ex) {
                        logger.error(args[i]
                                + " is not a correct integer format, will process only one file at a time.");
                    }
                }
                if (args[i].startsWith("-p")) {
                    try {
                        MinProb = Float.parseFloat(args[i].substring(2));
                        logger.info("probability threshold: " + MinProb);
                    } catch (Exception ex) {
                        logger.error(args[i] + " is not a correct format, will use 0 as threshold instead.");
                    }
                }
            }
        }

        reader.close();
        TandemParam tandemparam = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        PTMManager.GetInstance();

        if (param.TargetIDOnly) {
            param.EstimateBG = false;
            param.ApexDelta = 1.5f;
            param.NoMissedScan = 10;
            param.MiniOverlapP = 0.2f;
            param.RemoveGroupedPeaks = false;
            param.CheckMonoIsotopicApex = false;
            param.DetectByCWT = false;
            param.FillGapByBK = false;
            param.IsoCorrThreshold = -1f;
            param.SmoothFactor = 3;
        }

        if (mode == 1) {
            logger.info("Processing " + mzXMLfile.getAbsolutePath() + "....");
            long time = System.currentTimeMillis();
            LCMSPeakMS1 LCMS1 = new LCMSPeakMS1(mzXMLfile.getAbsolutePath(), NoCPUs);
            LCMS1.SetParameter(param);

            LCMS1.Resume = false;
            if (!param.TargetIDOnly) {
                LCMS1.CreatePeakFolder();
            }
            LCMS1.ExportPeakClusterTable = true;

            if (pepXMLfile.exists()) {
                tandemparam.InteractPepXMLPath = pepXMLfile.getAbsolutePath();
                LCMS1.ParsePepXML(tandemparam, MinProb);
                logger.info("No. of PSMs included: " + LCMS1.IDsummary.PSMList.size());
                logger.info("No. of Peptide ions included: " + LCMS1.IDsummary.GetPepIonList().size());
            }

            if (param.TargetIDOnly) {
                LCMS1.SaveSerializationFile = false;
            }

            if (param.TargetIDOnly || !LCMS1.ReadPeakCluster()) {
                LCMS1.PeakClusterDetection();
            }

            if (pepXMLfile.exists()) {
                LCMS1.AssignQuant(false);
                LCMS1.IDsummary.ExportPepID(outputfolder);
            }
            time = System.currentTimeMillis() - time;
            logger.info(LCMS1.ParentmzXMLName + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
            LCMS1.BaseClearAllPeaks();
            LCMS1.SetSpectrumParser(null);
            LCMS1.IDsummary = null;
            LCMS1 = null;
            System.gc();
        } else if (mode == 2) {

            LCMSID IDsummary = new LCMSID("", "", "");
            logger.info("Parsing all pepXML files in " + pepXMLPath + "....");
            for (File file : pepXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("pep.xml")
                        || file.getName().toLowerCase().endsWith("pepxml")) {
                    PepXMLParser pepXMLParser = new PepXMLParser(IDsummary, file.getAbsolutePath(), MinProb);
                }
            }
            HashMap<String, LCMSID> LCMSIDMap = IDsummary.GetLCMSIDFileMap();

            ExecutorService executorPool = null;
            executorPool = Executors.newFixedThreadPool(NoFile);

            logger.info("Processing all mzXML files in " + mzXMLPath + "....");
            for (File file : mzXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("mzxml")) {
                    LCMSID id = LCMSIDMap.get(FilenameUtils.getBaseName(file.getName()));
                    if (id == null || id.PSMList == null) {
                        logger.warn("No IDs found in :" + FilenameUtils.getBaseName(file.getName())
                                + ". Quantification for this file is skipped");
                        continue;
                    }
                    if (!id.PSMList.isEmpty()) {
                        MS1TargetQuantThread thread = new MS1TargetQuantThread(file, id, NoCPUs, outputfolder,
                                param);
                        executorPool.execute(thread);
                    }
                }
            }
            LCMSIDMap.clear();
            LCMSIDMap = null;
            IDsummary = null;
            executorPool.shutdown();
            try {
                executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                logger.info("interrupted..");
            }

            if (outputfolder == null | outputfolder.equals("")) {
                outputfolder = mzXMLPath;
            }

            logger.info("Merging PSM files..");
            File output = new File(outputfolder);
            FileWriter writer = new FileWriter(output.getAbsolutePath() + "/PSM_merge.csv");
            boolean header = false;
            for (File csvfile : output.listFiles()) {
                if (csvfile.getName().toLowerCase().endsWith("_psms.csv")) {
                    BufferedReader outreader = new BufferedReader(new FileReader(csvfile));
                    String outline = outreader.readLine();
                    if (!header) {
                        writer.write(outline + "\n");
                        header = true;
                    }
                    while ((outline = outreader.readLine()) != null) {
                        writer.write(outline + "\n");
                    }
                    outreader.close();
                    csvfile.delete();
                }
            }
            writer.close();
        }
        logger.info("MS1 quant module is complete.");
    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:com.dlmu.heipacker.crawler.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from  w ww .  j  a  va  2s  . co  m*/
        // Create local execution context
        HttpContext localContext = new BasicHttpContext();

        HttpGet httpget = new HttpGet("http://localhost/test");

        boolean trying = true;
        while (trying) {
            System.out.println("executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget, localContext);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Consume response content
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);

            int sc = response.getStatusLine().getStatusCode();

            AuthState authState = null;
            HttpHost authhost = null;
            if (sc == HttpStatus.SC_UNAUTHORIZED) {
                // Target host authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            }
            if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // Proxy authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
            }

            if (authState != null) {
                System.out.println("----------------------------------------");
                AuthScheme authscheme = authState.getAuthScheme();
                System.out.println("Please provide credentials for " + authscheme.getRealm() + "@"
                        + authhost.toHostString());

                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter username: ");
                String user = console.readLine();
                System.out.print("Enter password: ");
                String password = console.readLine();

                if (user != null && user.length() > 0) {
                    Credentials creds = new UsernamePasswordCredentials(user, password);
                    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
                    trying = true;
                } else {
                    trying = false;
                }
            } else {
                trying = false;
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*  w w w .  j av  a  2  s.  co m*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                @Override
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}