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:edu.du.penrose.systems.fedoraApp.util.MetsBatchFileSplitter.java

/**
 * Split a file with multiple METS sections into separate files each containing
 * a single METS record. The input file must contain one or more multiple
 * <mets></mets> elements (sections). if true a OBJID must exist in every <mets> 
 * element, this will become the file name. Otherwise a unique file name is 
 * generated. Return true if the <batch update="true"> is set in the batch file other
 * wise return false (defaults to new file being ingested ).
 * /*from ww  w .  ja  v  a2  s. c om*/
 * @see edu.du.penrose.systems.fedoraApp.batchIngest.bus.BatchIngestThreadManager#setBatchSetStatus(String, String)
 * @param threadStatus this object receives status updates while splitting the file.
 * @param  inFile file to split
 * @param  metsNewDirectory directory containing METS for new objects.
 * @param  metsUpdatesDirectory directory containing METS for existing objects.
 * @param nameFileFromOBJID if true a OBJID must exist in every <mets> element, this will become the file name. Otherwise a unique file name is 
 * generated
 * @param checkValidDiscoveryID if true check that the OBJID contains a valid discovery ID
 * 
 * @throws Exception on any IO error.
 */
static public void splitMetsBatchFile(BatchIngestOptions ingestOptions, ThreadStatusMsg threadStatus,
        File inFile, String metsNewDirectory, String metsUpdatesDirectory, boolean nameFileFromOBJID)
        throws FatalException {
    String metsDirectory = null; // will get set to either the new directory or the updates directory.
    String batchCreationDate = null;
    StringBuffer batchDescription = null;
    boolean isUpdate = false;
    ingestDataType dataType = ingestDataType.ALL;

    FileInputStream batchFileInputStream;
    try {
        batchFileInputStream = new FileInputStream(inFile);
    } catch (FileNotFoundException e) {
        throw new FatalException(e.getMessage());
    }
    DataInputStream batchFileDataInputStream = new DataInputStream(batchFileInputStream);
    BufferedReader batchFileBufferedReader = new BufferedReader(
            new InputStreamReader(batchFileDataInputStream));
    File outFile = null;
    FileOutputStream metsFileOutputStream = null;
    BufferedWriter metsBufferedWriter = null;

    String oneLine = null;
    String documentType = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    int fileCount = 0;
    boolean isBatchFile = false;

    try {
        boolean done = false;
        while (batchFileBufferedReader.ready() && !done) {

            oneLine = batchFileBufferedReader.readLine();
            if (oneLine.contains("<?xml version")) {
                documentType = oneLine;
            }
            if (oneLine.contains(BATCH_ELEMENT) || oneLine.contains(BATCH_ELEMENT_MARKER)) {
                isBatchFile = true;
                if (oneLine.contains("version=" + QUOTE + 2 + QUOTE)
                        || oneLine.contains("version=" + APOST + 2 + APOST)) {
                    splitMetsBatchFile_version_2(ingestOptions, threadStatus, inFile, metsNewDirectory,
                            metsUpdatesDirectory, nameFileFromOBJID, null, null, null, null);
                    done = true;
                } else {
                    splitMetsBatchFile_version_1(ingestOptions, threadStatus, inFile, metsNewDirectory,
                            metsUpdatesDirectory, nameFileFromOBJID);
                    done = true;
                }
            }
        } // while

    } catch (NullPointerException e) {
        String errorMsg = "Unable to split files, Permature end of file: Corrupt:" + inFile.toString() + " ?";
        throw new FatalException(errorMsg);
    } catch (Exception e) {
        String errorMsg = "Unable to split files: " + e.getMessage();
        logger.fatal(errorMsg);
        throw new FatalException(errorMsg);
    } finally {
        try {
            if (batchFileBufferedReader != null) {
                batchFileBufferedReader.close();
            }
            if (metsBufferedWriter != null) {
                metsBufferedWriter.close();
            }
            if (!isBatchFile) {
                throw new FatalException("ERROR: missing <batch> element!");
            }
        } catch (IOException e) {
            throw new FatalException(e.getMessage());
        }
    }

}

From source file:org.intermine.bio.task.GFF3ConverterTask.java

/**
 * Parses ID mapping file into HashMap<String, String>.  This map is used to convert GFF3 IDs to 
 * facilitate merging.//from   w  ww  . j a  v  a  2 s  .c  om
 * @param mappingFile
 */
public void setIDMappingFile(String mappingFile) {
    System.out.println("JDJDJD:: GFF3ConverterTask.setIDMappingFile() = " + mappingFile);
    if (mappingFile.equals("${gff3.IDMappingFile}")) {
        IDMap = null;
    } else {
        BufferedReader in;
        IDMap = new HashMap<String, String>();
        try {
            in = new BufferedReader(new FileReader(mappingFile));
            while (in.ready()) {
                String lineRead = in.readLine();
                String[] line = lineRead.split("\\t");
                //                System.out.print(lineRead);
                if (line[0].length() > 1) {
                    IDMap.put(line[0], line[1]);
                } else {
                    //                   System.out.println(lineRead+"*");
                    continue;
                }
            }
        } catch (Exception e) {
            throw new BuildException(e);
        }
    }
}

From source file:org.kalypso.wspwin.core.prf.PrfReader.java

/**
 * Liest die ersten 13 Zeilen einer Profildatei
 *///  ww  w  .j av  a  2 s.c o m
private final void readMetadata(final BufferedReader r) throws IOException {
    // final Map<Integer, DataString> metaMap = new HashMap<Integer, DataString>();

    // final ArrayList<String> metaStrings = new ArrayList<String>();

    if (!r.ready()) {
        m_logger.log(Level.SEVERE, Messages.getString("org.kalypso.wspwin.core.prf.PrfReader.40")); //$NON-NLS-1$
        throw new IOException();
    }

    for (int i = 1; i < 14; i++) {
        final String line = r.readLine();
        if (line == null) {
            m_logger.log(Level.SEVERE, Messages.getString("org.kalypso.wspwin.core.prf.PrfReader.41")); //$NON-NLS-1$
            break;
        }

        // Linie nach Daten und Text trennen (max 40 Zeichen Text)
        final String textString = line.substring(0, Math.min(40, line.length()));
        textString.trim();
        final String dataString = line.length() > 40 ? line.substring(40, line.length()).trim() : ""; //$NON-NLS-1$
        m_metaMap.put(i, new String[] { textString, dataString });
    }
}

From source file:org.atemsource.dojo.build.DojoBuildMojo.java

private void execute(List<String> params) throws IOException, MojoExecutionException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.directory(workDir);/* w w  w  .j  av a  2s.  c  o m*/
    processBuilder.command(params);
    Process process = processBuilder.start();
    InputStream in = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    InputStream ein = process.getErrorStream();
    BufferedReader ereader = new BufferedReader(new InputStreamReader(ein));
    boolean finished = false;
    do {
        if (reader.ready()) {
            String line = reader.readLine();
            if (line != null) {
                System.out.println(line);
            }

        } else if (ereader.ready()) {
            String line = ereader.readLine();
            if (line != null) {
                System.err.println(line);
            }

        } else {
            try {
                int exit = process.exitValue();
                if (exit != 0) {
                    throw new MojoExecutionException("dojo build ended with exit code " + exit);
                } else {
                    finished = true;
                }
            } catch (IllegalThreadStateException e) {

            }
            Thread.sleep(100);
        }
    } while (!finished);
}

From source file:org.intermine.bio.task.GFF3ConverterTask.java

public void setTypeMappingFile(String mappingFile) {
    System.out.println("JDJDJD:: GFF3ConverterTask.setTypeMappingFile() = " + mappingFile);
    if (mappingFile.equals("${gff3.typeMappingFile}")) {
        typeMap = null;//from  ww w .j  ava 2 s  . c om
    } else {
        BufferedReader in;
        typeMap = new HashMap<String, String>();
        try {
            in = new BufferedReader(new FileReader(mappingFile));
            while (in.ready()) {
                String lineRead = in.readLine();
                String[] line = lineRead.split("\\t");
                //                System.out.print(lineRead);
                if (line[0].length() > 1) {
                    typeMap.put(line[0], line[1]);
                } else {
                    //                   System.out.println(lineRead+"*");
                    continue;
                }
            }
        } catch (Exception e) {
            throw new BuildException(e);
        }
    }
}

From source file:it.cnr.icar.eric.client.ui.thin.security.SecurityUtil.java

/** Generate a key pair and add it to the keystore.
  *// www . j  av  a 2s  .  co  m
  * @param alias
  * @return
  *     A HashSet of X500PrivateCredential objects.
  * @throws Exception
  */
private Set<Object> generateCredentials(String alias) throws JAXRException {

    try {
        HashSet<Object> credentials = new HashSet<Object>();

        // The keystore file is at ${jaxr-ebxml.home}/security/keystore.jks. If
        // the 'jaxr-ebxml.home' property is not set, ${user.home}/jaxr-ebxml/ is
        // used.
        File keyStoreFile = KeystoreUtil.getKeystoreFile();
        String storepass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storepass",
                "ebxmlrr");
        String keypass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.keypass");
        if (keypass == null) {
            // keytool utility requires a six character minimum password.
            // pad passwords with < six chars
            if (alias.length() >= 6) {
                keypass = alias;
            } else if (alias.length() == 5) {
                keypass = alias + "1";
            } else if (alias.length() == 4) {
                keypass = alias + "12";
            } else if (alias.length() == 3) {
                keypass = alias + "123";
            }
            // alias should have at least 3 chars
        }
        log.debug("Generating key pair for '" + alias + "' in '" + keyStoreFile.getAbsolutePath() + "'");

        // When run in S1WS 6.0, this caused some native library errors. It appears that S1WS
        // uses different encryption spis than those in the jdk. 
        //            String[] args = {
        //                "-genkey", "-alias", uid, "-keypass", "keypass",
        //                "-keystore", keyStoreFile.getAbsolutePath(), "-storepass",
        //                new String(storepass), "-dname", "uid=" + uid + ",ou=People,dc=sun,dc=com"
        //            };
        //            KeyTool keytool = new KeyTool();
        //            ByteArrayOutputStream keytoolOutput = new ByteArrayOutputStream();
        //            try {
        //                keytool.run(args, new PrintStream(keytoolOutput));
        //            }
        //            finally {
        //                log.info(keytoolOutput.toString());
        //            }
        // To work around this problem, generate the key pair using keytool (which executes
        // in its own vm. Note that all the parameters must be specified, or keytool prompts
        // for their values and this 'hangs'
        String[] cmdarray = { "keytool", "-genkey", "-alias", alias, "-keypass", keypass, "-keystore",
                keyStoreFile.getAbsolutePath(), "-storepass", storepass, "-dname", "cn=" + alias };
        Process keytool = Runtime.getRuntime().exec(cmdarray);
        try {
            keytool.waitFor();
        } catch (InterruptedException ie) {
        }
        if (keytool.exitValue() != 0) {
            log.error(WebUIResourceBundle.getInstance().getString("message.keytoolCommandFailedDetails"));
            Reader reader = new InputStreamReader(keytool.getErrorStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            while (bufferedReader.ready()) {
                log.error(bufferedReader.readLine());
            }
            throw new JAXRException(
                    WebUIResourceBundle.getInstance().getString("excKeyToolCommandFail") + keytool.exitValue());
        }
        log.debug("Key pair generated successfully.");

        // After generating the keypair in the keystore file, we have to reload
        // SecurityUtil's KeyStore object.
        KeyStore keyStore = it.cnr.icar.eric.client.xml.registry.util.SecurityUtil.getInstance().getKeyStore();
        keyStore.load(new FileInputStream(keyStoreFile), storepass.toCharArray());

        credentials.add(it.cnr.icar.eric.client.xml.registry.util.SecurityUtil.getInstance()
                .aliasToX500PrivateCredential(alias));

        return credentials;
    } catch (Exception e) {
        if (e instanceof JAXRException) {
            throw (JAXRException) e;
        } else {
            throw new JAXRException(e);
        }
    }
}

From source file:fr.treeptik.cloudunit.utils.EmailUtils.java

/**
 * Write body of Email with freemaker template and variables chosen before
 *
 * @param mapConfigEmail//from w  w  w .  ja  v  a 2s .com
 * @return
 */
@SuppressWarnings("unchecked")
private Map<String, Object> writeBody(Map<String, Object> mapConfigEmail) {
    String body;
    Template template = (Template) mapConfigEmail.get("template");
    template.setEncoding("UTF-8");
    String htmlFile = template.getName().replace("ftl", "html");
    FileWriter writer = null;
    File file;
    StringBuilder stringBuilder = new StringBuilder();
    FileReader fileReader = null;

    Map<String, String> mapVariables = (Map<String, String>) mapConfigEmail.get("mapVariables");

    try {
        file = File.createTempFile(htmlFile, "email");
        writer = new FileWriter(file);
        template.process(mapVariables, writer);
        fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        while (bufferedReader.ready()) {
            stringBuilder.append(bufferedReader.readLine());

        }

        bufferedReader.close();
        file.delete();

    } catch (IOException | TemplateException e) {
        logger.error("Error constructBody method : IO issue : " + e);
        e.printStackTrace();
    }
    body = stringBuilder.toString();
    mapConfigEmail.put("body", body);

    return mapConfigEmail;

}

From source file:org.n52.oxf.ses.adapter.SESAdapter.java

public XmlObject handleResponse(String operationName, ByteArrayInputStream input) throws OXFException {
    XmlObject result = null;//from  www .  j a v a  2  s  .  c om
    Envelope env;
    Header header;

    if (operationName != null && input != null) {
        try {
            if (operationName.equals(SESAdapter.REGISTER_PUBLISHER)) {
                env = EnvelopeDocument.Factory.parse(input).getEnvelope();
                header = env.getHeader();

                // check for right action
                // http://docs.oasis-open.org/wsn/brw-2/RegisterPublisher/RegisterPublisherResponse
                XmlObject[] actions = XmlUtil.selectPath(
                        "declare namespace s='http://www.w3.org/2005/08/addressing' .//s:Action", header);
                String action = null;

                // is this the right request? If NOT throw Exception
                if (actions != null && actions.length == 1) {
                    action = actions[0].getDomNode().getFirstChild().getNodeValue();
                    if (!action.equals(
                            "http://docs.oasis-open.org/wsn/brw-2/RegisterPublisher/RegisterPublisherResponse")) {

                        StringBuilder sb = new StringBuilder();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                        while (reader.ready()) {
                            sb.append(reader.readLine());
                        }
                        LOGGER.error("Unexpected Reponse: {}", sb.toString());
                        throw new OXFException(OperationNotSupported + ": Not the right response: \"" + action
                                + " \" <-> Expected is: \"http://docs.oasis-open.org/wsn/brw-2/RegisterPublisher/RegisterPublisherResponse\"!");
                    } else {
                        result = XmlObject.Factory.parse(env.newInputStream());
                    }
                }

                // TODO check if following problem still exist
                // XXX Problem with Namespace and XMLBeans: The document is not a
                // RegisterPublisherResponse@http://docs.oasis-open.org/wsn/br-2: document element
                // namespace mismatch expected "http://docs.oasis-open.org/wsn/br-2" got
                // "http://docs.oasis-open.org/wsn/brw-2"
                //                    result = XmlObject.Factory.parse(body.toString());
                //                    if (result instanceof /*org.oasisOpen.docs.wsn.br2.impl.*/RegisterPublisherResponseDocumentImpl) {
                //                        // soap envelope => body => registerpublisher
                //                        result = ((/*org.oasisOpen.docs.wsn.br2.impl.*/RegisterPublisherResponseDocumentImpl) result).getRegisterPublisherResponse();
                //                    }
            }
        } catch (IOException e) {
            throw new OXFException(e);
        } catch (XmlException e) {
            // TODO what about SOAP-Exceptions?
            throw new OXFException("RegisterPublisherResponse not wellformed XML", e);
        }
    }
    return result;
}

From source file:org.mskcc.cbio.cgds.scripts.ImportUniProtIdMapping.java

public void importData() throws DaoException, IOException {
    Set<String> swissProtAccs = getSwissProtAccessionHuman();
    int rows = 0;
    BufferedReader reader = null;
    try {//  w  w w . j  a  va  2 s.c  o m
        reader = new BufferedReader(new FileReader(uniProtIdMapping));
        Map<Integer, Set<String>> mapEntrezSwissProt = new HashMap<Integer, Set<String>>();
        Map<Integer, Set<String>> mapEntrezUniprot = new HashMap<Integer, Set<String>>();
        while (reader.ready()) {
            String line = reader.readLine();
            String[] tokens = line.split("\t");
            int entrezGeneId = Integer.parseInt(tokens[0]);
            String uniProtId = tokens[1];
            if (swissProtAccs.contains(uniProtId)) {
                Set<String> swiss = mapEntrezSwissProt.get(entrezGeneId);
                if (swiss == null) {
                    swiss = new HashSet<String>();
                    mapEntrezSwissProt.put(entrezGeneId, swiss);
                }
                swiss.add(uniProtId);
            } else {
                Set<String> uniprot = mapEntrezUniprot.get(entrezGeneId);
                if (uniprot == null) {
                    uniprot = new HashSet<String>();
                    mapEntrezUniprot.put(entrezGeneId, uniprot);
                }
                uniprot.add(uniProtId);
            }
            progressMonitor.incrementCurValue();
            ConsoleUtil.showProgress(progressMonitor);
        }
        mapEntrezUniprot.keySet().removeAll(mapEntrezSwissProt.entrySet());
        mapEntrezUniprot.putAll(mapEntrezSwissProt);
        for (Map.Entry<Integer, Set<String>> entry : mapEntrezUniprot.entrySet()) {
            int entrezGeneId = entry.getKey();
            String uniprot = pickOneUniprot(entry.getValue());
            if (uniprot != null) {
                rows += DaoUniProtIdMapping.addUniProtIdMapping(entrezGeneId, uniprot);
            }
        }
        System.out.println("Total number of uniprot id mappings saved: " + rows);
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabaseTest.java

public void testCreatePrincipalIsSavedToFile() {

    File testFile = createPasswordFile(1, 0);

    loadPasswordFile(testFile);/*  www  .  jav  a 2 s  .  c om*/

    final String CREATED_PASSWORD = "guest";
    final String CREATED_B64MD5HASHED_PASSWORD = "CE4DQ6BIb/BVMN9scFyLtA==";
    final String CREATED_USERNAME = "createdUser";

    Principal principal = new Principal() {
        public String getName() {
            return CREATED_USERNAME;
        }
    };

    _database.createPrincipal(principal, CREATED_PASSWORD.toCharArray());

    try {
        BufferedReader reader = new BufferedReader(new FileReader(testFile));

        assertTrue("File has no content", reader.ready());

        assertEquals("Comment line has been corrupted.", TEST_COMMENT, reader.readLine());

        assertTrue("File is missing user data.", reader.ready());

        String userLine = reader.readLine();

        String[] result = Pattern.compile(":").split(userLine);

        assertEquals("User line not complete '" + userLine + "'", 2, result.length);

        assertEquals("Username not correct,", CREATED_USERNAME, result[0]);
        assertEquals("Password not correct,", CREATED_B64MD5HASHED_PASSWORD, result[1]);

        assertFalse("File has more content", reader.ready());

    } catch (IOException e) {
        fail("Unable to valdate file contents due to:" + e.getMessage());
    }
}