Example usage for java.io BufferedReader ready

List of usage examples for java.io BufferedReader ready

Introduction

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

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:org.intermine.install.swing.CreateDatabaseWorker.java

/**
 * Create a database using the Postgres <code>createdb</code> program.
 * /* w w w. ja  v  a 2  s.co m*/
 * @param server The database server.
 * @param databaseName The database name.
 * @param userName The database user name.
 * @param password The user password.
 * @param encoding The encoding for the database.
 * 
 * @throws IOException if there is a problem running <code>createdb</code>.
 *  
 * @throws InterruptedException if the thread is interrupted while running
 * the <code>createdb</code>.
 * 
 * @throws DatabaseCreationException if the process completes but failed
 * to create the database.
 */
protected void createDatabaseWithCreatedb(String server, String databaseName, String userName, String password,
        String encoding) throws IOException, InterruptedException, DatabaseCreationException {

    String[] commands = { "/usr/bin/createdb", "-h", server, "-E", encoding, "-O", userName, "-W", "-T",
            "template0", databaseName };

    if (logger.isDebugEnabled()) {
        StringBuilder command = new StringBuilder();
        for (int i = 0; i < commands.length; i++) {
            if (i > 0) {
                command.append(' ');
            }
            command.append(commands[i]);
        }
        logger.debug(command);
    }

    StringBuilder output = new StringBuilder();
    StringBuilder errorOutput = new StringBuilder();

    Integer exitCode = null;
    Process p = Runtime.getRuntime().exec(commands);
    try {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        boolean passwordSet = false;
        while (true) {
            try {
                while (stdin.ready()) {
                    char c = (char) stdin.read();
                    output.append(c);
                }
                while (stderr.ready()) {
                    char c = (char) stderr.read();
                    errorOutput.append(c);
                }

                if (!passwordSet && errorOutput.indexOf("Password:") >= 0) {
                    PrintStream out = new PrintStream(p.getOutputStream(), true);
                    out.println(password);
                    passwordSet = true;
                }

                exitCode = p.exitValue();
                // If this succeeds, we're done.
                break;
            } catch (IllegalThreadStateException e) {
                // Process not done, so wait and continue.
                Thread.sleep(250);
            }
        }
    } finally {
        try {
            p.exitValue();
        } catch (IllegalThreadStateException e) {
            // Not finished, but something has failed.
            p.destroy();
        }
    }

    if (errorOutput.length() > 0) {
        throw new DatabaseCreationException(exitCode, output.toString(), errorOutput.toString());
    }

    if (exitCode != 0) {
        throw new DatabaseCreationException("Return code from createdb = " + exitCode, exitCode,
                output.toString(), errorOutput.toString());
    }
}

From source file:com.gplus.api.GPlusEDCAsActivityTest.java

@Test
public void Tests() throws Exception {
    InputStream is = GPlusEDCAsActivityTest.class.getResourceAsStream("/GPlusEDCFixed.json");
    if (is == null)
        System.out.println("null");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
    jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    jsonMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);

    try {/*w  ww . j  av a 2  s  . c  o m*/
        while (br.ready()) {
            String line = br.readLine();

            Activity activity = null;
            try {
                activity = gplusSerializer.deserialize(line);
            } catch (Exception e) {
                LOGGER.error(line);
                e.printStackTrace();
                Assert.fail("Exception on gplus Serializer.deserialize(jsonString) : " + e);
            }

            try {
                String activityString = gplusSerializer.serialize(activity);
                LOGGER.debug(activityString);
            } catch (Exception e) {
                LOGGER.error(activity.toString());
                e.printStackTrace();
                Assert.fail("Exception on gplus Serializer.serialize(activity) : " + e);
            }

        }
    } catch (Exception e) {
        System.out.println("Exception: " + e);
        LOGGER.error(e.getMessage());
        Assert.fail("");
    }
}

From source file:com.reddit.api.RedditEDCAsActivityJSONTest.java

@Test
public void Tests() throws Exception {
    InputStream is = RedditEDCAsActivityJSONTest.class.getResourceAsStream("/RedditEDCFixed.json");
    if (is == null)
        System.out.println("null");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
    jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    jsonMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);

    try {//w  ww.  j  a v  a  2 s  . c om
        while (br.ready()) {
            String line = br.readLine();

            Activity activity = null;
            try {
                activity = redditSerializer.deserialize(line);
            } catch (Exception e) {
                LOGGER.error(line);
                e.printStackTrace();
                Assert.fail("Exception on redditSerializer.deserialize(jsonString) : " + e);
            }

            try {
                String activityString = redditSerializer.serialize(activity);
                System.out.println(jsonMapper.writeValueAsString(activity));
            } catch (Exception e) {
                LOGGER.error(activity.toString());
                e.printStackTrace();
                Assert.fail("Exception on redditSerializer.serialize(activity) : " + e);
            }

            //LOGGER.info(activity);
        }
    } catch (Exception e) {
        System.out.println("Exception: " + e);
        LOGGER.error(e.getMessage());
        Assert.fail("");
    }
}

From source file:org.apache.streams.gnip.facebook.test.FacebookEDCAsActivityTest.java

@Ignore
@Test//from www .  ja  va 2  s  .c  om
public void Tests() throws Exception {
    InputStream is = FacebookEDCAsActivityTest.class.getResourceAsStream("/FacebookEDC.xml");
    if (is == null)
        System.out.println("null");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    xmlMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
    jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
    jsonMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
    jsonMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);

    try {
        while (br.ready()) {
            String line = br.readLine();
            if (!StringUtils.isEmpty(line)) {
                LOGGER.debug(line);
                Object activityObject = xmlMapper.readValue(line, Object.class);

                String jsonString = jsonMapper.writeValueAsString(activityObject);

                JSONObject jsonObject = new JSONObject(jsonString);

                JSONObject fixedObject = GnipActivityFixer.fix(jsonObject);

                Activity activity = null;
                try {
                    activity = jsonMapper.readValue(fixedObject.toString(), Activity.class);
                } catch (Exception e) {
                    LOGGER.error(jsonObject.toString());
                    LOGGER.error(fixedObject.toString());
                    e.printStackTrace();
                    Assert.fail();
                }
                //LOGGER.info(activity);
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        Assert.fail();
    }
}

From source file:org.hyperic.hq.product.DetectionUtil.java

/**
 * This method finds all the childs of the provided process
 * @param parentPid//  www  .  ja va2s  .c o m
 */
public static Set<Long> getAllChildPid(long parentPid) {
    Set<Long> childPids = new HashSet<Long>();

    if (IS_UNIX) {
        String cmd = "ps -o pid --no-headers --ppid " + String.valueOf(parentPid);
        String line;
        BufferedReader input = null;
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = input.readLine()) != null) {
                line = line.trim();
                if (!line.equals("") && isNumber(line)) {
                    Long childPid = Long.valueOf(line);
                    childPids.addAll(getAllChildPid(childPid));
                    childPids.add(childPid);
                }
            }
        } catch (Exception e) {
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    } else if (IS_WINDOWS) {
        final String cmd = "wmic process get processid,parentprocessid";
        String line;
        BufferedReader input = null;
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            //[HQ-4176] - don't block this thread
            if (!input.ready()) {
                return childPids;
            }
            long lPpid = -1;
            String sPpid = "";
            String sCpid = "";
            long lCpid = -1;
            while ((line = input.readLine()) != null) {
                try {
                    line = line.trim();
                    sPpid = line.substring(0, line.indexOf(" "));
                    lPpid = Long.valueOf(sPpid);
                    if (parentPid == lPpid) {
                        sCpid = line.substring(line.indexOf(" ")).trim();
                        lCpid = Long.valueOf(sCpid);
                        childPids.addAll(getAllChildPid(lCpid));
                        childPids.add(lCpid);
                    } else {
                        continue;
                    }
                } catch (Exception e) {
                    continue;
                }
            }

        } catch (Exception e) {
            log.error(e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    }
    return childPids;
}

From source file:org.springframework.sync.diffsync.DiffSyncTest.java

private String resource(String name) throws IOException {
    ClassPathResource resource = new ClassPathResource("/org/springframework/sync/" + name + ".json");
    BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
    StringBuilder builder = new StringBuilder();
    while (reader.ready()) {
        builder.append(reader.readLine());
    }/*from  w  w w  .ja  v  a2s .c o m*/
    return builder.toString();
}

From source file:org.wso2.carbon.identity.authenticator.krb5.Krb5Authenticator.java

private boolean loginWithKrb5(String username, String password, String remoteAddress)
        throws AuthenticationException {
    //Proceed with Kerberos TGT request
    String uuid = UUID.randomUUID().toString();
    ProcessBuilder procBldr = new ProcessBuilder("/usr/bin/kinit", "-l", "10d", "-r", "5d", "-c",
            tgtCachePrefix + uuid, username);
    procBldr.directory(new File(CARBON_HOME));
    Map<String, String> env = procBldr.environment();
    if (KRB5_CONFIG == null)
        KRB5_CONFIG = "/etc/krb5.conf";
    env.put("KRB5_CONFIG", KRB5_CONFIG);
    log.info(env.get("KRB5_CONFIG"));
    HttpSession session = getHttpSession();
    try {//from   w w  w  . j  ava 2  s.  c om
        Process proc = procBldr.start();
        InputStream procErr = proc.getErrorStream();
        InputStream procOut = proc.getInputStream();
        //Read the output from the program
        byte[] buffer = new byte[256];
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
        BufferedReader err = new BufferedReader(new InputStreamReader(procErr));
        boolean isError = (procErr.available() > 0) ? true : false;
        if (!isError) {
            out.write(password);
            out.newLine();
            out.close();
            if (proc.waitFor() != 0) {
                log.warn("Kinit Failed");
                if (procErr.available() > 0) {
                    String line = null;
                    String msg = "";
                    while (err.ready() && (line = err.readLine()) != null)
                        msg += line;
                    if (!msg.equals(""))
                        throw new AuthenticationException(msg);
                }
            }
            //Looks like all went well and we got the TGT, lets renew the TGT...
            procBldr = new ProcessBuilder("/usr/bin/kinit", "-R", "-c", tgtCachePrefix + uuid);
            proc = procBldr.start();
            if (proc.waitFor() != 0) {
                log.warn("TGT Renewal Failed");
                File tgt = new File(tgtCachePrefix + uuid);
                tgt.delete();
                throw new AuthenticationException("TGT Renewal Failed");
            }
            AuthenticationAdmin authAdmin = new AuthenticationAdmin();
            boolean loggedIn = authAdmin.login(username, password, remoteAddress);
            if (loggedIn) {
                nameToUuidMap.put(username, uuid);
                session.setAttribute(Krb5AuthenticatorConstants.USER_TICKET_CACHE, tgtCachePrefix + uuid);
            }
            return loggedIn;
        } else {
            log.error("Incorrect kinit command: " + err.readLine());
            throw new AuthenticationException("Incorrect kinit command");
        }
    } catch (IOException ioe) {
        log.warn(ioe.getMessage());
        ioe.printStackTrace();
        throw new AuthenticationException(ioe.getMessage());
    } catch (InterruptedException e) {
        e.printStackTrace();
        throw new AuthenticationException(e.getMessage());
    }
}

From source file:eu.stratosphere.pact.runtime.task.DataSinkTaskTest.java

@Test
@SuppressWarnings("unchecked")
public void testSortingDataSinkTask() {

    int keyCnt = 100;
    int valCnt = 20;

    super.initEnvironment(MEMORY_MANAGER_SIZE * 4, NETWORK_BUFFER_SIZE);
    super.addInput(new UniformRecordGenerator(keyCnt, valCnt, true), 0);

    DataSinkTask<Record> testTask = new DataSinkTask<Record>();

    // set sorting
    super.getTaskConfig().setInputLocalStrategy(0, LocalStrategy.SORT);
    super.getTaskConfig().setInputComparator(new RecordComparatorFactory(new int[] { 1 },
            ((Class<? extends Key<?>>[]) new Class[] { IntValue.class })), 0);
    super.getTaskConfig().setMemoryInput(0, 4 * 1024 * 1024);
    super.getTaskConfig().setFilehandlesInput(0, 8);
    super.getTaskConfig().setSpillingThresholdInput(0, 0.8f);

    super.registerFileOutputTask(testTask, MockOutputFormat.class, new File(tempTestPath).toURI().toString());

    try {//from   ww  w  .  j av  a2s  . c o m
        testTask.invoke();
    } catch (Exception e) {
        LOG.debug(e);
        Assert.fail("Invoke method caused exception.");
    }

    File tempTestFile = new File(this.tempTestPath);

    Assert.assertTrue("Temp output file does not exist", tempTestFile.exists());

    FileReader fr = null;
    BufferedReader br = null;
    try {
        fr = new FileReader(tempTestFile);
        br = new BufferedReader(fr);

        Set<Integer> keys = new HashSet<Integer>();

        int curVal = -1;
        while (br.ready()) {
            String line = br.readLine();

            Integer key = Integer.parseInt(line.substring(0, line.indexOf("_")));
            Integer val = Integer.parseInt(line.substring(line.indexOf("_") + 1, line.length()));

            // check that values are in correct order
            Assert.assertTrue("Values not in ascending order", val >= curVal);
            // next value hit
            if (val > curVal) {
                if (curVal != -1) {
                    // check that we saw 100 distinct keys for this values
                    Assert.assertTrue("Keys missing for value", keys.size() == 100);
                }
                // empty keys set
                keys.clear();
                // update current value
                curVal = val;
            }

            Assert.assertTrue("Duplicate key for value", keys.add(key));
        }

    } catch (FileNotFoundException e) {
        Assert.fail("Out file got lost...");
    } catch (IOException ioe) {
        Assert.fail("Caught IOE while reading out file");
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Throwable t) {
            }
        }
        if (fr != null) {
            try {
                fr.close();
            } catch (Throwable t) {
            }
        }
    }
}

From source file:net.itransformers.topologyviewer.fulfilmentfactory.impl.TelnetCLIInterface.java

public String readUntil(String regexp) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    logger.info("looking for : " + regexp);
    int chInt;//from  ww  w. j a  va 2s  . c  o m
    StringBuffer sb = new StringBuffer();
    while ((chInt = reader.read()) != -1) {
        char ch = (char) chInt;
        if (ch == '\n') {
            logger.info(sb.toString());
            sb.setLength(0);
            continue;
        }
        sb.append(ch);
        String st = sb.toString();
        if (st.matches(regexp)) {
            logger.info("### Found match: " + sb);
            return st;
        }
        if (!reader.ready()) {
            logger.info("Buffer is not ready. Read characters until now: " + sb.toString());
        }
    }
    return null;
}

From source file:com.aerospike.load.AerospikeLoad.java

/**
 * Process a single file//  ww  w.  j a  v a  2 s  .co m
 */
private void processFile() {
    int lineNumber = 0;

    log.trace("Hosts: " + this.client.getNodeNames());
    long start = System.currentTimeMillis();
    try {
        BufferedReader br = new BufferedReader(
                new InputStreamReader(new FileInputStream(this.fileName), "UTF8"));
        log.debug("Reading file:  " + Utils.getFileName(fileName));
        while (br.ready()) {
            String line;

            //skip reading 1st line of data file
            if (params.ignoreFirstLine) {
                lineNumber++;
                String metaColumn = br.readLine();
                counters.write.recordTotal = counters.write.recordTotal - metaColumn.length();
            }
            AsWriterTask task = null;
            while ((line = br.readLine()) != null) {
                lineNumber++;
                log.trace("Read line " + lineNumber + " from file " + Utils.getFileName(fileName));

                // Throttle the read to write ratio
                while ((counters.write.readCount.get()
                        - (counters.write.writeCount.get() + counters.write.writeErrors.get())) > rwThrottle) {
                    Thread.sleep(20);
                }
                if (params.fileType.equalsIgnoreCase(Constants.CSV_FILE)) {
                    //add 2 to handle different file size in different platform.
                    task = new AsWriterTask(fileName, lineNumber, (line.length() + 1),
                            Parser.getCSVRawColumns(line, params.delimiter), metadataColumnDefs, binColumnDefs,
                            this.client, params, counters);
                    counters.write.readerProcessed.incrementAndGet();
                } else {
                    log.error("File format not supported");
                }
                log.trace("Submitting line " + lineNumber + " in file " + Utils.getFileName(fileName));
                writerPool.submit(task);

                counters.write.readCount.incrementAndGet();
            }
        }

        br.close();

    } catch (IOException e) {
        counters.write.readErrors.incrementAndGet();
        log.error("Error processing file: " + Utils.getFileName(fileName) + ": Line: " + lineNumber);
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        counters.write.readErrors.incrementAndGet();
        log.error("Error processing file: " + Utils.getFileName(fileName) + ": Line: " + lineNumber);
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
    }
    long stop = System.currentTimeMillis();
    log.info(String.format("Reader completed %d-lines in %.3fsec, From file: %s", lineNumber,
            (float) (stop - start) / 1000, Utils.getFileName(fileName)));
}