Example usage for java.io BufferedReader read

List of usage examples for java.io BufferedReader read

Introduction

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

Prototype

public int read(char cbuf[], int off, int len) throws IOException 

Source Link

Document

Reads characters into a portion of an array.

Usage

From source file:net.alastairwyse.oraclepermissiongenerator.datainterfacelayer.RestRemoteDataModelProxy.java

/**
 * Converts an HttpResponse object to a string.
 * @param   httpResponse  The HttpResponse to convert.
 * @return                The HttpResponse converted to a string.
 * @throws  IOException   if an error occurs when converting the HTTP response to a string.
 *///ww w.j  a v a2s  .c  o m
private String ConvertHttpResponseToString(HttpResponse httpResponse) throws IOException {
    char[] characterBuffer = new char[(int) httpResponse.getEntity().getContentLength()];
    // TODO: If project compliance is changed to Java 1.7 or higher, change below to try with resources statement  
    InputStreamReader inputStreamReader = new InputStreamReader(httpResponse.getEntity().getContent());
    try {
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader,
                (int) httpResponse.getEntity().getContentLength());
        try {
            bufferedReader.read(characterBuffer, 0, (int) httpResponse.getEntity().getContentLength());
        } finally {
            bufferedReader.close();
        }
    } finally {
        inputStreamReader.close();
    }

    return new String(characterBuffer);
}

From source file:org.openhab.binding.sonance.internal.SonanceBinding.java

/**
 * Send volume commands to groups (music zones)
 *
 * @param itemName//from  ww w . j  av  a 2 s . c o  m
 *            item name to send update to
 * @param command
 *            Sonance IP code to execute
 * @param outToServer
 *            date output stream we can write to
 * @param i
 *            bufered reader where we can read from
 * @throws IOException
 *             throws an exception when we can't reach to amplifier
 */
private void sendVolumeCommand(String itemName, String command, DataOutputStream outToServer, BufferedReader i)
        throws IOException {
    char[] cbuf = new char[50]; // Response is always 50 characters

    logger.debug("Sending volume command {}", command);

    outToServer.write(hexStringToByteArray(command));
    i.read(cbuf, 0, 50);

    Matcher m = volumePattern.matcher(new String(cbuf));

    if (m.find()) {
        String volume = m.group(1);
        eventPublisher.postUpdate(itemName, new DecimalType(volume));
        logger.debug("Setting volume for item {} on {}", itemName, volume);
    } else {
        logger.error("Error sending regular volume command {}, received this: {}", command, new String(cbuf));
    }
}

From source file:org.openhab.binding.sonance.internal.SonanceBinding.java

/**
 * Enable or disable specific groups (music zones)
 *
 * @param itemName// ww w.jav  a2s.c  o  m
 *            item name to send update to
 * @param command
 *            Sonance IP code to execute
 * @param outToServer
 *            date output stream we can write to
 * @param i
 *            bufered reader where we can read from
 * @throws IOException
 *             throws an exception when we can't reach to amplifier
 */
private void sendMuteCommand(String itemName, String command, DataOutputStream outToServer, BufferedReader i)
        throws IOException {
    char[] cbuf = new char[50]; // Response is always 50 characters

    logger.debug("Sending mute command {}", command);
    outToServer.write(hexStringToByteArray(command));
    i.read(cbuf, 0, 50);

    String result = new String(cbuf);

    logger.trace("Received this result: {}", result);

    if (result.contains("Mute=on") || result.contains("MuteOn")) {
        eventPublisher.postUpdate(itemName, OnOffType.OFF);
        logger.debug("Setting mute item {} on OFF", itemName);
    } else if (result.contains("Mute=off") || result.contains("MuteOff")) {
        eventPublisher.postUpdate(itemName, OnOffType.ON);
        logger.debug("Setting mute item {} on ON", itemName);
    } else {
        logger.error("Error sending mute command {}, received this: {}", command, result);
    }
}

From source file:org.openhab.binding.sonance.internal.SonanceBinding.java

/**
 * Wake up or put amplifier to sleep//from w w  w. jav  a2  s .c o m
 *
 * @param itemName
 *            item name to send update to
 * @param command
 *            Sonance IP code to execute
 * @param outToServer
 *            date output stream we can write to
 * @param i
 *            bufered reader where we can read from
 * @throws IOException
 *             throws an exception when we can't reach to amplifier
 */
private void sendPowerCommand(String itemName, String command, DataOutputStream outToServer, BufferedReader i)
        throws IOException {
    char[] cbuf = new char[50]; // Response is always 50 characters

    logger.debug("Sending power command {}", command);
    outToServer.write(hexStringToByteArray(command));
    i.read(cbuf, 0, 50);

    String result = new String(cbuf);

    logger.trace("Received power response: {}", result);

    if (result.contains("Off")) {
        eventPublisher.postUpdate(itemName, OnOffType.OFF);
        logger.debug("Setting power item {} on OFF", itemName);
    } else if (result.contains("On")) {
        eventPublisher.postUpdate(itemName, OnOffType.ON);
        logger.debug("Setting power item {} on ON", itemName);
    } else {
        logger.trace("Error sending power command {}, received this: {}", command, result);
    }
}

From source file:com.datafibers.kafka.connect.SchemaedFileSourceTask.java

private List<SourceRecord> pollFromStream() throws InterruptedException {
    // Unfortunately we can't just use readLine() because it blocks 
    // in an uninterruptible way.  Instead we have to manage
    // splitting lines ourselves, using simple backoff when 
    // no new data is available.
    try {/*ww  w  .java2s . co m*/
        final BufferedReader readerCopy;
        synchronized (this) {
            readerCopy = reader;
        }
        if (readerCopy == null)
            return null;

        ArrayList<SourceRecord> records = null;

        int nread = 0;
        while (readerCopy.ready()) {
            nread = readerCopy.read(buffer, offset, buffer.length - offset);
            log.trace("Read {} bytes from {}", nread, logFilename());

            if (nread > 0) {
                offset += nread;
                if (offset == buffer.length) {
                    char[] newbuf = new char[buffer.length * 2];
                    System.arraycopy(buffer, 0, newbuf, 0, buffer.length);
                    buffer = newbuf;
                }

                String line;
                do {
                    line = extractLine();
                    if (line != null) {
                        log.trace("Read a line from {}", logFilename());
                        if (records == null)
                            records = new ArrayList<>();

                        records.add(new SourceRecord(offsetKey(filename), offsetValue(streamOffset), topic,
                                Schema.STRING_SCHEMA, line));
                    }
                } while (line != null);
            }
        }
        if (nread <= 0)
            synchronized (this) {
                this.wait(1000);
            }

        return records;
    } catch (IOException e) {
        // Underlying stream was killed, probably as a result 
        // of calling stop. Allow to return null, and driving 
        // thread will handle any shutdown if necessary.
    }
    return null;
}

From source file:com.datafibers.kafka.connect.FileGenericSourceTask.java

@Override
public List<SourceRecord> poll() throws InterruptedException {
    if (!inProgressPaths.isEmpty()) {
        try {//ww  w  . java2s .  com
            Path currentPath = inProgressPaths.remove(0);
            processedPaths.add(currentPath);
            filename = currentPath.getFileName().toString();
            fileInProcessing = FileUtils.getFile(currentPath.toString() + FILENAME_EXT_PROCESSING);
            fileProcessed = FileUtils.getFile(currentPath.toString() + FILENAME_EXT_PROCESSED);
            FileUtils.moveFile(FileUtils.getFile(currentPath.toString()), fileInProcessing);

            stream = new FileInputStream(fileInProcessing);

            Map<String, Object> offset = context.offsetStorageReader()
                    .offset(Collections.singletonMap(FILENAME_FIELD, filename));
            if (offset != null && !overwrite) {
                log.info("Found previous offset, will not process {}", filename);
                return null;
            } else
                streamOffset = 0L;

            reader = new BufferedReader(new InputStreamReader(stream));
            log.info("Opened {} for reading", filename);
        } catch (IOException e) {
            throw new ConnectException(String.format("Unable to open file %", filename), e);
        }
    } else {
        log.warn("********* Waiting for file that meets the glob criteria! *********");
        synchronized (this) {
            this.wait(interval);
            findMatch();
        }
        return null;
    }

    ArrayList<SourceRecord> records = new ArrayList<SourceRecord>();
    //StringBuilder fileContent = new StringBuilder();

    try {
        final BufferedReader readerCopy;
        synchronized (this) {
            readerCopy = reader;
        }
        if (readerCopy == null)
            return null;

        int nread = 0;
        while (readerCopy.ready()) {
            nread = readerCopy.read(buffer, offset, buffer.length - offset);
            log.trace("Read {} bytes from {}", nread, filename);

            if (nread > 0) {
                offset += nread;
                if (offset == buffer.length) {
                    char[] newbuf = new char[buffer.length * 2];
                    System.arraycopy(buffer, 0, newbuf, 0, buffer.length);
                    buffer = newbuf;
                }

                String line;
                do {
                    line = extractLine();
                    if (line != null) {
                        line = line.trim();
                        log.trace("Read a line from {}", filename);
                        if (records == null)
                            records = new ArrayList<>();
                        /*                records.add(new SourceRecord(offsetKey(filename), offsetValue(streamOffset), topic,
                                              dataSchema, structDecodingRoute(line, filename)));*/
                        if (schemaValidate) {
                            records.add(new SourceRecord(offsetKey(filename), offsetValue(streamOffset), topic,
                                    dataSchema, structDecodingRoute(line, filename)));
                        } else {
                            log.info("STRING SCHEMA Processing");
                            records.add(new SourceRecord(offsetKey(filename), offsetValue(streamOffset), topic,
                                    Schema.STRING_SCHEMA, line));
                        }

                    }
                    new ArrayList<SourceRecord>();
                } while (line != null);
            }
        }

        // Finish processing and rename as processed.
        FileUtils.moveFile(fileInProcessing, fileProcessed);

        if (nread <= 0)
            synchronized (this) {
                this.wait(1000);
            }

        return records;

    } catch (IOException e) {
        throw new ConnectException(String.format("Unable to read file %", filename), e);
    }

}

From source file:io.cloudslang.content.httpclient.consume.HttpResponseConsumer.java

private void consumeToDestinationFile() throws IOException {
    BufferedReader reader;
    BufferedWriter fileWriter = null;
    FileOutputStream fos = null;/*  ww  w . jav a  2s .c  o m*/
    try {
        try {
            reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), responseCharacterSet));
            fos = new FileOutputStream(new File(destinationFile));
            fileWriter = new BufferedWriter(new OutputStreamWriter(fos, responseCharacterSet));
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(
                    "Could not parse '" + HttpClientInputs.RESPONSE_CHARACTER_SET + "'. " + e.getMessage(), e);
        }
        char[] buffer = new char[1024];
        int b;
        while ((b = reader.read(buffer, 0, buffer.length)) != -1) {
            fileWriter.write(buffer, 0, b);
        }
        fileWriter.flush();
    } finally {
        if (fos != null) {
            safeClose(fos);
        }
        if (fileWriter != null) {
            safeClose(fileWriter);
        }
    }
}

From source file:com.xmlcalabash.io.ReadableData.java

private void readData(StepContext stepContext) {
    runtime.getTracer().debug(null, stepContext, -1, this, null, "    DATA > LOADING...");

    if (documents == null) {
        documents = new DocumentSequence(runtime);
    }/*from   w  w w.  j  a  v  a  2s .  c o m*/

    c_init.close(stepContext.curChannel);

    if (uri == null) {
        documents.addChannel(stepContext.curChannel);
        runtime.getTracer().debug(null, stepContext, -1, this, null, "    DATA > NOTHING");
    } else {
        if (doc == null) {
            String userContentType = parseContentType(contentType);
            String userCharset = parseCharset(contentType);
            URI dataURI = getDataUri(uri);

            TreeWriter tree = new TreeWriter(runtime);
            tree.startDocument(dataURI);

            InputStream stream;

            try {
                stream = getStream(dataURI);
                String serverContentType = getContentType();

                if ("content/unknown".equals(serverContentType) && contentType != null) {
                    // pretend...
                    serverContentType = contentType;
                }

                String serverBaseContentType = parseContentType(serverContentType);
                String serverCharset = parseCharset(serverContentType);

                if (serverCharset != null) {
                    // HACK! Make the content type here consistent with the content type returned
                    // from the http-request tests, just to make the test suite results more
                    // consistent.
                    serverContentType = serverBaseContentType + "; charset=\"" + serverCharset + "\"";
                }

                // If the user specified a charset and the server did not and it's a file: URI,
                // assume the user knows best.
                // FIXME: provide some way to override this!!!

                String charset = serverCharset;
                if ("file".equals(dataURI.getScheme()) && serverCharset == null
                        && serverBaseContentType.equals(userContentType)) {
                    charset = userCharset;
                }

                if (runtime.transparentJSON() && HttpUtils.jsonContentType(contentType)) {
                    if (charset == null) {
                        // FIXME: Is this right? I think it is...
                        charset = "UTF-8";
                    }
                    InputStreamReader reader = new InputStreamReader(stream, charset);
                    JSONTokener jt = new JSONTokener(reader);
                    XdmNode jsonDoc = JSONtoXML.convert(runtime.getProcessor(), jt, runtime.jsonFlavor());
                    tree.addSubtree(jsonDoc);
                } else {
                    tree.addStartElement(wrapper);
                    if (XProcConstants.c_data.equals(wrapper)) {
                        if ("content/unknown".equals(serverContentType)) {
                            tree.addAttribute(_contentType, "application/octet-stream");
                        } else {
                            tree.addAttribute(_contentType, serverContentType);
                        }
                        if (!isText(serverContentType, charset)) {
                            tree.addAttribute(_encoding, "base64");
                        }
                    } else {
                        if ("content/unknown".equals(serverContentType)) {
                            tree.addAttribute(c_contentType, "application/octet-stream");
                        } else {
                            tree.addAttribute(c_contentType, serverContentType);
                        }
                        if (!isText(serverContentType, charset)) {
                            tree.addAttribute(c_encoding, "base64");
                        }
                    }
                    tree.startContent();

                    if (isText(serverContentType, charset)) {
                        BufferedReader bufread;
                        if (charset == null) {
                            // FIXME: Is this right? I think it is...
                            charset = "UTF-8";
                        }
                        BufferedReader bufreader = new BufferedReader(new InputStreamReader(stream, charset));
                        int maxlen = 4096 * 3;
                        char[] chars = new char[maxlen];
                        int read = bufreader.read(chars, 0, maxlen);
                        while (read >= 0) {
                            if (read > 0) {
                                String data = new String(chars, 0, read);
                                tree.addText(data);
                            }
                            read = bufreader.read(chars, 0, maxlen);
                        }
                        bufreader.close();
                    } else {
                        // Fill the buffer each time so that we get an even number of base64 lines
                        int maxlen = 4096 * 3;
                        byte[] bytes = new byte[maxlen];
                        int pos = 0;
                        int readlen = maxlen;
                        boolean done = false;
                        while (!done) {
                            int read = stream.read(bytes, pos, readlen);
                            if (read >= 0) {
                                pos += read;
                                readlen -= read;
                            } else {
                                done = true;
                            }

                            if ((readlen == 0) || done) {
                                String base64 = Base64.encodeBytes(bytes, 0, pos);
                                tree.addText(base64 + "\n");
                                pos = 0;
                                readlen = maxlen;
                            }
                        }
                        stream.close();
                    }
                    tree.addEndElement();
                }
            } catch (IOException ioe) {
                throw new XProcException(XProcConstants.dynamicError(29), ioe);
            }

            tree.endDocument();

            doc = tree.getResult();
        }

        documents.newPipedDocument(stepContext.curChannel, doc);
        runtime.getTracer().debug(null, stepContext, -1, this, null, "    DATA > LOADED");
    }

    // close documents        
    documents.close(stepContext.curChannel);
}

From source file:org.openhab.binding.sonance.internal.SonanceBinding.java

/**
 * Sets the group to the specified target volume. Amplifier doesn't support
 * direct volume commands, so a loop is needed
 *
 * @param itemName/*from w ww  . ja  v  a 2 s .co  m*/
 *            item to publish result to
 * @param group
 *            target group
 * @param targetVolume
 *            target volume
 * @param outToServer
 *            data output stream where we can write to
 * @param i
 *            buffered reader where we can read from
 * @param endpoint
 *            ip:port
 * @throws IOException
 *             throws an IOException when we can't reach the amplifier
 */
private void setVolumeCommand(String itemName, String group, int targetVolume, DataOutputStream outToServer,
        BufferedReader i, String endpoint) throws IOException {
    char[] cbuf = new char[50]; // Response is always 50 characters

    String question = String.format("%s%s%s", SonanceConsts.DIRECT_VOLUME_QUERY,
            Integer.toHexString(183 + targetVolume), group);
    logger.trace("Sending this to amplifier: {}", question);

    outToServer.write(hexStringToByteArray(question));
    i.read(cbuf, 0, 50);

    String result = new String(cbuf);
    logger.trace("Received this as response : {}", result);
    Matcher m = volumePattern.matcher(result);

    if (m.find()) {
        double currentVolume = Integer.parseInt(m.group(1));
        eventPublisher.postUpdate(itemName, new DecimalType(currentVolume));
        logger.debug("Updating {} with new volume {}", itemName, currentVolume);
    } else {
        logger.error("Error sending volume command, received this: {}", new String(cbuf));
    }
}

From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean running_state = CMS.isInRunningState();

    if (!running_state)
        throw new IOException("CMS server is not ready to serve.");

    HttpServletRequest req = request;/*from w ww  .j av a  2  s  .co m*/
    HttpServletResponse resp = response;

    CMSRequest cmsRequest = newCMSRequest();

    // set argblock
    cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request)));

    // set http request
    cmsRequest.setHttpReq(request);

    // set http response
    cmsRequest.setHttpResp(response);

    // set servlet config.
    cmsRequest.setServletConfig(mConfig);

    // set servlet context.
    cmsRequest.setServletContext(mConfig.getServletContext());

    char[] content = null;
    String encodedreq = null;
    String method = null;
    int len = -1;
    IPKIMessage msg = null;
    IPKIMessage replymsg = null;

    // NOTE must read all bufer before redoing handshake for
    // ssl client auth for client auth to work.

    // get request method
    method = req.getMethod();

    // get content length
    len = request.getContentLength();

    // get content, a base 64 encoded serialized request.
    if (len > 0) {
        InputStream in = request.getInputStream();
        InputStreamReader inreader = new InputStreamReader(in, "UTF8");
        BufferedReader reader = new BufferedReader(inreader, len);

        content = new char[len];
        int done = reader.read(content, 0, len);
        int total = done;

        while (done >= 0 && total < len) {
            done = reader.read(content, total, len - total);
            total += done;
        }
        reader.close();
        encodedreq = new String(content);
    }

    // force client auth handshake, validate RA and get RA's Id.
    // NOTE must do this after all contents are read for ssl
    // redohandshake to work

    X509Certificate peerCert;

    try {
        peerCert = getPeerCert(req);
    } catch (EBaseException e) {
        mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    if (peerCert == null) {
        // XXX log something here.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // authenticate RA

    String RA_Id = null;
    String raUserId = null;
    IAuthToken token = null;

    try {
        token = authenticate(request);
        raUserId = token.getInString("userid");
        RA_Id = peerCert.getSubjectDN().toString();
    } catch (EInvalidCredentials e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } catch (EBaseException e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN());

    // authorize
    AuthzToken authzToken = null;

    try {
        authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit");
    } catch (Exception e) {
        // do nothing for now
    }

    if (authzToken == null) {
        cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED);
        return;
    }

    // after cert validated, check http request.
    if (!method.equalsIgnoreCase("POST")) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    if (len <= 0) {
        resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED);
        return;
    }

    // now process request.

    CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id);
    try {
        // decode request.
        msg = (IPKIMessage) mReqEncoder.decode(encodedreq);
        // process request
        replymsg = processRequest(RA_Id, raUserId, msg, token);
    } catch (IOException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (EBaseException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
    }

    CMS.debug("ConnectorServlet: done processRequest");

    // encode reply
    try {
        String encodedrep = mReqEncoder.encode(replymsg);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("text/html");
        resp.setContentLength(encodedrep.length());

        // send reply
        OutputStream out = response.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8");

        writer.write(encodedrep);
        writer.flush();
        writer.close();
        out.flush();
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: error writing e=" + e.toString());
    }
    CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id);
}