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.topicquests.tcp.TupleSpaceConnector.java

/**
 * Returns field "cargo" // w w  w  .  j  a  va 2  s .  co m
 * @param json
 * @param listener
 */
void sendMessage(String json, ITupleSpaceConnectorListener listener) {
    IResult result = new ResultPojo();
    try {
        //         System.out.println("Server "+port);
        Socket skt = srvr.accept();
        //           System.out.println("Server has connected! ");
        PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
        //           System.out.println("Sending string: " + json);
        out.print(json);
        out.flush();
        //           System.out.println("SS-1");
        //   InputStream is = skt.getInputStream();
        //           System.out.println("SS-2");
        StringBuilder buf = new StringBuilder();
        String line;
        InputStream is = skt.getInputStream();
        //           System.out.println("SS-2a "+skt.isInputShutdown()); //false
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        //           System.out.println("SS-3 "+in.ready()); //false
        while (!in.ready()) { // stuck here
            //              System.out.print(".");
            synchronized (synchObject) {
                try {
                    synchObject.wait(50);
                } catch (Exception e) {
                }
            }
        }
        int x;
        while ((x = in.read()) > -1)
            buf.append((char) x);
        in.close();
        out.close();
        //           System.out.println("SS-4 "+buf);

        //         skt.close();
        line = buf.toString();
        environment.logDebug("TupleSpaceConnector got back " + line);
        JSONObject jobj = (JSONObject) parser.parse(line);
        //what we get back IS the cargo from the original tuple
        result.setResultObject(jobj.toString());
    } catch (Exception e) {
        environment.logError(e.getMessage(), e);
        result.addErrorString(e.getMessage());
    }
    listener.acceptResult(result);
}

From source file:org.apache.streams.instagram.test.data.InstagramUserInfoDataConverterIT.java

@Test
public void InstagramUserInfoDataConverterIT() throws Exception {
    InputStream is = InstagramUserInfoDataConverterIT.class.getResourceAsStream("/testUserInfoData.txt");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    PrintStream outStream = new PrintStream(new BufferedOutputStream(
            new FileOutputStream("target/test-classes/InstagramUserInfoDataConverterIT.txt")));

    try {/*from w  w w.j  av a2s.  c  o m*/
        while (br.ready()) {
            String line = br.readLine();
            if (!StringUtils.isEmpty(line)) {

                LOGGER.info("raw: {}", line);

                UserInfoData userInfoData = gson.fromJson(line, UserInfoData.class);

                ActivityObjectConverter<UserInfoData> converter = new InstagramUserInfoDataConverter();

                ActivityObject activityObject = converter.toActivityObject(userInfoData);

                LOGGER.info("activityObject: {}", activityObject.toString());

                assertThat(activityObject, is(not(nullValue())));

                assertThat(activityObject.getId(), is(not(nullValue())));
                assertThat(activityObject.getImage(), is(not(nullValue())));
                assertThat(activityObject.getDisplayName(), is(not(nullValue())));
                assertThat(activityObject.getSummary(), is(not(nullValue())));

                Map<String, Object> extensions = (Map<String, Object>) activityObject.getAdditionalProperties()
                        .get("extensions");
                assertThat(extensions, is(not(nullValue())));
                assertThat(extensions.get("following"), is(not(nullValue())));
                assertThat(extensions.get("followers"), is(not(nullValue())));
                assertThat(extensions.get("screenName"), is(not(nullValue())));
                assertThat(extensions.get("posts"), is(not(nullValue())));

                assertThat(activityObject.getAdditionalProperties().get("handle"), is(not(nullValue())));
                assertThat(activityObject.getId(), is(not(nullValue())));
                assertThat(activityObject.getUrl(), is(not(nullValue())));

                assertThat(activityObject.getAdditionalProperties().get("provider"), is(not(nullValue())));

                outStream.println(mapper.writeValueAsString(activityObject));

            }
        }
        outStream.flush();

    } catch (Exception ex) {
        LOGGER.error("Exception: ", ex);
        outStream.flush();
        Assert.fail();
    }
}

From source file:de.bley.word.filereader.ReaderFile.java

/**
 *
 * @param filepath Pfad der zulesenden Datei.
 * @return Inhalt des angegebenen Dateipfads.
 *//*  w ww  . j a va2s .  co  m*/
@Override
public String readFile(String filepath) {
    final StringBuilder builder = new StringBuilder();
    final File f = new File(filepath);
    if (f.exists()) {
        final BufferedReader bufferedReader;
        try {

            bufferedReader = new BufferedReader(new FileReader(filepath));
        } catch (FileNotFoundException ex) {
            log.fatal("Datei nicht gefunden " + filepath, ex);
            return "";
        }

        try {
            while (bufferedReader.ready()) {
                builder.append(bufferedReader.readLine()).append("\n");
            }
        } catch (IOException ex) {
            log.fatal("IOException readFiles() ", ex);
        }
    }
    return builder.toString();
}

From source file:au.org.ala.ecodata.IniReader.java

/**
 * errors result in a log of the error only
 * @param filename file to load into document object
 *///from   w w w  .ja v  a  2s. co  m
private void loadFile(String filename) {
    try {
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String currentSection = "";
        String key;
        String value;
        int i;
        while (in.ready()) {
            String line = in.readLine().trim();//don't care about whitespace
            // ignore the comments
            if (line.startsWith("#") || line.startsWith(";")) {
                continue;
            }
            if (line.length() > 2 && line.charAt(0) == '[') {
                i = line.lastIndexOf("]");
                if (i <= 0 && line.length() > 1) { //last brace might be missing
                    currentSection = line.substring(1);
                } else if (i > 2) { //empty section names are ignored
                    currentSection = line.substring(1, i);
                }
            } else if (line.length() > 2) {
                key = "";
                value = "";
                i = line.indexOf("="); //rather than split incase value contains '='
                if (i > 1) {
                    key = line.substring(0, i);
                }
                if (i < line.length() - 1) {
                    value = line.substring(i + 1);
                }
                //do not add if key is empty
                document.put(currentSection + "\\" + key, value);

            }
        }
        in.close();
    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:eu.peppol.as2.MdnMimeMessageInspector.java

public Map<String, String> getMdnFields() {
    Map<String, String> ret = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    try {/*from ww  w.  j  av  a2 s .  co  m*/

        BodyPart bp = getMessageDispositionNotificationPart();
        boolean contentIsBase64Encoded = false;

        //
        // look for base64 transfer encoded MDN's (when Content-Transfer-Encoding is present)
        //
        // Content-Type: message/disposition-notification
        // Content-Transfer-Encoding: base64
        //
        // "Content-Transfer-Encoding not used in HTTP transport Because HTTP, unlike SMTP,
        // does not have an early history involving 7-bit restriction.
        // There is no need to use the Content Transfer Encodings of MIME."
        //
        String[] contentTransferEncodings = bp.getHeader("Content-Transfer-Encoding");
        if (contentTransferEncodings != null && contentTransferEncodings.length > 0) {
            if (contentTransferEncodings.length > 1)
                log.warn("MDN has multiple Content-Transfer-Encoding, we only try the first one");
            String encoding = contentTransferEncodings[0];
            if (encoding == null)
                encoding = "";
            encoding = encoding.trim();
            log.info("MDN specifies Content-Transfer-Encoding : '" + encoding + "'");
            if ("base64".equalsIgnoreCase(encoding)) {
                contentIsBase64Encoded = true;
            }
        }

        Object content = bp.getContent();
        if (content instanceof InputStream) {
            InputStream contentInputStream = (InputStream) content;

            if (contentIsBase64Encoded) {
                log.debug("MDN seems to be base64 encoded, wrapping content stream in Base64 decoding stream");
                contentInputStream = new Base64InputStream(contentInputStream); // wrap in base64 decoding stream
            }

            BufferedReader r = new BufferedReader(new InputStreamReader(contentInputStream));
            while (r.ready()) {
                String line = r.readLine();
                int firstColon = line.indexOf(":"); // "Disposition: ......"
                if (firstColon > 0) {
                    String key = line.substring(0, firstColon).trim(); // up to :
                    String value = line.substring(firstColon + 1).trim(); // skip :
                    ret.put(key, value);
                }
            }
        } else {
            throw new Exception("Unsupported MDN content, expected InputStream found @ " + content.toString());
        }

    } catch (Exception e) {
        throw new IllegalStateException("Unable to retrieve the values from the MDN : " + e.getMessage(), e);
    }
    return ret;
}

From source file:com.codecrate.shard.transfer.pcgen.PcgenObjectImporter.java

public Collection importObjects(File file, ProgressMonitor progress) {
    Collection results = new ArrayList();
    BufferedReader reader = null;
    Source source = null;/*from www .  j  a  va 2  s.c om*/

    progress.startTask("Importing pcgen objects from " + file.getName(), getNumberOfFileLines(file));
    try {
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        while (reader.ready() && !progress.isCancelled()) {
            String line = reader.readLine().trim();
            if (sourceLineHandler.isSourceLine(line)) {
                source = (Source) sourceLineHandler.handleLine(line, source);
            } else if (!isEmptyLine(line)) {
                try {
                    results.add(lineHandler.handleLine(line, source));
                } catch (Exception e) {
                    LOG.error("Error processing line: " + line, e);
                }
            }

            progress.completeUnitOfWork();
        }
    } catch (IOException e) {
        LOG.error("Error importing file: " + file, e);
    } finally {
        closeReader(reader);
    }

    progress.finish();

    return results;
}

From source file:edu.du.penrose.systems.fedoraApp.util.MetsBatchFileSplitter.java

/**
 * Parse the batch ingest command line and store the command in the returned BatchIngestOption object.
 * //www .j av a 2  s.  c  o  m
 * @param ingestOptions
 * @param batchCommandFile
 * @return the passed in ingestOptions
 * @throws FatalException
 */
public static BatchIngestOptions setCommandLineOptions(BatchIngestOptions ingestOptions, File batchCommandFile)
        throws FatalException {
    FileInputStream batchFileInputStream = null;
    DataInputStream batchFileDataInputStream = null;
    BufferedReader batchFileBufferedReader = null;

    boolean isBatchFile = false;
    boolean validCommandLine = false;

    try {
        batchFileInputStream = new FileInputStream(batchCommandFile);
        batchFileDataInputStream = new DataInputStream(batchFileInputStream);
        batchFileBufferedReader = new BufferedReader(new InputStreamReader(batchFileDataInputStream));

        while (batchFileBufferedReader.ready()) {

            String documentType = "";
            String oneLine = batchFileBufferedReader.readLine();
            if (oneLine.contains("<?xml version")) {
                documentType = oneLine;
            }
            if (oneLine.contains("<batch")) {
                isBatchFile = true;
            }

            if (oneLine.contains(("<ingestControl")) && oneLine.indexOf("<!") == -1) {
                if ((!oneLine.contains("command")) || (!oneLine.contains("type"))) {
                    throw new FatalException("Invalid batchDescription");
                }

                String ingestControlLine = oneLine.trim();
                validCommandLine = parseCommandLine(ingestOptions, oneLine);
                break;
            }
        } // while

    } catch (NullPointerException e) {
        String errorMsg = "Unable to split files, Permature end of file: Corrupt:" + batchCommandFile.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 (!isBatchFile) {
                throw new FatalException("ERROR: missing <batch> element!");
            }
            if (!validCommandLine) {
                throw new FatalException("ERROR: missing or Invalid <batch> command line!");
            }
        } catch (IOException e) {
            throw new FatalException(e.getMessage());
        }
    }

    return ingestOptions;
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriterTests.java

/**
* Utility method to check that the contents of a CSV employee file match the list of employees we used to generate it
* 
* @param fileName The file to read//  ww  w .j a  v  a 2  s  .c o  m
* @param employees The list of employees we expect to read from the file
*/
private void compareCsv(InputStream inputStream, List<Employee> employees) throws IOException {
    BufferedReader reader = null;

    reader = new BufferedReader(new InputStreamReader(inputStream));

    for (Employee employee : employees) {
        if (!reader.ready()) {
            fail("File contained insufficient rows");
        }
        String line = reader.readLine();
        String expected = employee.getFirstName() + "," + employee.getLastName() + "," + employee.getJobTitle();
        assertThat(line, is(expected));
    }

    if (reader.ready()) {
        fail("File contained more data than expected");
    }
}

From source file:org.lsc.webai.utils.ForkProcess.java

private String readMessages(BufferedReader input) {
    StringBuffer messages = new StringBuffer();
    try {//ww w.  j  a v  a 2  s  .  c o m
        if (input != null) {
            String line = null;
            while (input.ready() && (line = input.readLine()) != null && !"".equals(line)) {
                messages.append(line.trim()).append("\n");
            }
        }
        return messages.toString();
    } catch (IOException e) {
        LOGGER.error(e.toString(), e);
        return null;
    } finally {
        // try {
        // if(input != null) {
        // input.close();
        // }
        // } catch (IOException e) {
        // LOGGER.error(e.toString(),e);
        // }
    }
}

From source file:servlets.uploadHeader.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//  w  w w. ja  v  a 2  s.  c o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, SQLException {
    response.setContentType("text/html;charset=UTF-8");

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        int projectID = 0;

        textdisplay.Project thisProject = null;
        if (request.getParameter("projectID") != null) {
            projectID = Integer.parseInt(request.getParameter("projectID"));
            thisProject = new textdisplay.Project(projectID);
            if (ServletFileUpload.isMultipartContent(request)) {
                ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
                List fileItemsList = servletFileUpload.parseRequest(request);

                String optionalFileName = "";
                FileItem fileItem = null;
                Iterator it = fileItemsList.iterator();
                while (it.hasNext()) {
                    FileItem fileItemTemp = (FileItem) it.next();
                    String tmp = fileItemTemp.getFieldName();
                    if (fileItemTemp.getFieldName().compareTo("file") == 0
                            && (fileItemTemp.getName().endsWith("txt")
                                    || fileItemTemp.getName().endsWith("xml"))) {

                        String textData;//=fileItemTemp.getString();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(fileItemTemp.getInputStream(), "UTF-8"));
                        StringBuilder b = new StringBuilder("");
                        while (in.ready()) {
                            b.append(in.readLine());
                        }
                        textData = b.toString();
                        try {
                            thisProject.setHeaderText(textData);
                        } catch (SQLException ex) {
                            Logger.getLogger(uploadHeader.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        response.sendRedirect("projectMetadata.jsp?projectID=" + projectID);
                        return;

                    }

                    else {
                        out.print(
                                "You must upload a .txt or .xml file, other formats are not supported at this time.");
                    }

                }
            }
        }
    } finally {
        out.close();
    }
}