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(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:de.wikilab.android.friendica01.TwAjax.java

public String convertStreamToString(InputStream is) throws IOException {
    /*//w  w w.  ja  v a  2  s  .  c om
     * To convert the InputStream to String we use the
     * Reader.read(char[] buffer) method. We iterate until the
     * Reader return -1 which means there's no more data to
     * read. We use the StringWriter class to produce the string.
     */
    if (is != null) {
        StringWriter writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:com.neusou.bioroid.restful.RestfulClient.java

/**
* Executes HTTP method/*ww  w  .ja v a 2  s  . c om*/
* @param <T> Http Request Method class
* @param <V> Restful response class
* @param <M> restful method class
* @param <R> response handler class
* @param httpMethod http request method
* @param rh response handler
* @param data extra invocation data
*/
public <T extends HttpRequestBase, V extends IRestfulResponse<?>, M extends RestfulMethod, R extends RestfulResponseHandler<V, M>> void execute(
        final T httpMethod, R rh, final Bundle data) {
    Logger.l(Logger.DEBUG, LOG_TAG, "execute() " + httpMethod.getRequestLine().toString());

    DefaultHttpClient httpClient = new DefaultHttpClient();
    V response = null;

    String exceptionMessage = null;
    String cachedResponse = null;

    boolean isResponseCached = data.getBoolean(KEY_USE_CACHE, mUseCacheByDefault);

    String requestUrl = httpMethod.getRequestLine().getUri().toString();

    Logger.l(Logger.DEBUG, LOG_TAG, "# # # # #  useCache? " + isResponseCached);

    if (mResponseCacheInitialized && isResponseCached) {
        httpMethod.getParams().setBooleanParameter("param1", true);
        //Log.d(LOG_TAG, "paramstring: "+paramString);
        cachedResponse = mCacheResponseDbHelper.getResponse(requestUrl, httpMethod.getMethod());
        Logger.l(Logger.DEBUG, LOG_TAG, "# # # # # cached response: " + cachedResponse);
        response = rh.createResponse(cachedResponse);
        response.set(new StringReader(cachedResponse));
    }

    if (cachedResponse == null) {
        try {
            response = httpClient.execute(httpMethod, rh);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            exceptionMessage = e.getMessage();
            httpMethod.abort();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            exceptionMessage = "not connected to the internet";
            httpMethod.abort();
        } catch (IOException e) {
            e.printStackTrace();
            exceptionMessage = "connection error. please try again.";
            httpMethod.abort();
        }

        // cache the response
        if (exceptionMessage == null && mResponseCacheInitialized && isResponseCached) {
            Logger.l(Logger.DEBUG, LOG_TAG, "# # # # # inserting response to cache: " + response);
            M method = data.getParcelable(XTRA_METHOD);
            BufferedReader br = new BufferedReader(response.get());
            StringBuilder sb = new StringBuilder();
            char[] buffer = new char[51200];
            try {
                while (true) {
                    int bytesRead;
                    bytesRead = br.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    }
                    sb.append(buffer, 0, bytesRead);
                }
                mCacheResponseDbHelper.insertResponse(requestUrl, sb.toString(),
                        Calendar.getInstance().getTime().getTime(), httpMethod.getMethod(), method.getCallId());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // process response                  
    //Logger.l(Logger.DEBUG, LOG_TAG, "starting service with action: "+INTENT_PROCESS_RESPONSE);
    Intent processIntent = new Intent();
    processIntent.setAction(INTENT_PROCESS_RESPONSE);
    processIntent.putExtra(XTRA_RESPONSE, response);
    processIntent.putExtra(XTRA_ERROR, exceptionMessage);
    processIntent.putExtra(XTRA_REQUEST, data);
    mContext.startService(processIntent);

    boolean imcallback = data.getBoolean(KEY_IMMEDIATECALLBACK, false);
    if (imcallback) {
        Bundle callbackData = new Bundle();
        callbackData.putBundle(XTRA_REQUEST, data);
        callbackData.putParcelable(XTRA_RESPONSE, response);
        callbackData.putString(XTRA_ERROR, exceptionMessage);
        broadcastCallback(mContext, callbackData,
                generateKey(mContext.getPackageName(), mName, RestfulClient.KEY_CALLBACK_INTENT));
    }

}

From source file:com.marklogic.shell.Shell.java

private void run(String[] args) {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//w ww.j  a  v a2  s .  c  o m
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        exitWithError(e.getMessage());
    }

    if (cmd.hasOption("h")) {
        printHelp();
    }

    String user = cmd.getOptionValue("u");
    String password = cmd.getOptionValue("p");
    String host = cmd.getOptionValue("H");
    String database = cmd.getOptionValue("d");
    Integer port = null;
    try {
        port = new Integer(cmd.getOptionValue("P"));
    } catch (NumberFormatException ignored) {
    }

    if (user == null)
        user = properties.getString("user");
    if (password == null)
        password = properties.getString("password");
    if (host == null)
        host = properties.getString("host");
    if (port == null) {
        try {
            port = new Integer(properties.getInt("port", DEFAULT_PORT));
        } catch (ConversionException e) {
            printHelp("Invalid port number: " + properties.getString("port"));
        }
    }

    if (user == null || password == null || port == null || host == null) {
        printHelp("You must provide a user, password, host and port.");
    }

    properties.setProperty("user", user);
    properties.setProperty("password", password);
    properties.setProperty("host", host);
    properties.setProperty("database", database);
    properties.setProperty("port", port.toString());
    if (properties.getString("scroll") == null || properties.getString("scroll").length() <= 0) {
        properties.setProperty("scroll", String.valueOf(DEFAULT_SCROLL));
    }

    if (cmd.hasOption("F")) {
        properties.setProperty("pretty-print-xml", "true");
    }

    String xqueryFile = cmd.getOptionValue("f");
    InputStream in = null;
    if (xqueryFile != null) {
        try {
            in = new FileInputStream(new File(xqueryFile));
        } catch (FileNotFoundException e) {
            exitWithError("File " + xqueryFile + " not found: " + e.getMessage());
        }
    } else {
        in = System.in;
    }
    int stdinBytes = 0;
    try {
        stdinBytes = in.available();
    } catch (IOException ignored) {
    }

    if (cmd.hasOption("l")) {
        // XXX this is a hack to support loading from command line without
        // duplication of code
        // XXX make sure load command doesn't have conflicting args
        load loader = new load(this.options);
        loader.execute(this, args);
    } else if (stdinBytes > 0) {
        StringBuffer xquery = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            char[] b = new char[4 * 1024];
            int n;
            while ((n = reader.read(b)) > 0) {
                xquery.append(b, 0, n);
            }
        } catch (IOException e) {
            exitWithError("Failed to read query from stdin: " + e.getMessage());
        }

        Session session = getContentSource().newSession();
        AdhocQuery request = session.newAdhocQuery(xquery.toString());
        try {
            outputResultSequence(session.submitRequest(request), false);
        } catch (RequestException e) {
            outputException(e);
        }
    } else {
        try {
            checkConnection(properties.getString("user"), properties.getString("password"),
                    properties.getString("host"), properties.getInt("port", DEFAULT_PORT));
        } catch (ShellException e) {
            outputLine("Failed to connect to Mark Logic. Invalid connection information.");
            outputException(e);
            exitWithError("Goodbye.");
        }
        printWelcome();
        outputLine("");
        try {
            startShell();
        } catch (Exception e) {
            e.printStackTrace();
            outputLine("Shell exited abnormally with exception: " + e.getClass().toString());
            outputLine("Error message: " + e.getMessage());
            outputLine("Goodbye.");
        }
    }
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.RangeStreamingTest.java

public void test_multiple_ranges() throws IOException {
    GetMethod get = new GetMethod(rootUrl);
    get.setRequestHeader(new Header("Range", "bytes 0-9,-10"));
    int status = httpClient.executeMethod(get);
    assertEquals("Expect 206/PARTIAL CONTENT", 206, status);

    String contentType = get.getResponseHeader("Content-Type").getValue();
    assertTrue("Content Type must be multipart/byteranges", contentType.contains("multipart/byteranges"));
    String boundary = contentType.substring(contentType.indexOf("boundary=") + "boundary=".length());

    BufferedReader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));

    String line = reader.readLine();
    while (!("--" + boundary).equals(line)) {
        line = reader.readLine();/* w  w  w .  ja va2s.  c o  m*/
    }

    assertEquals("Expected content to start with boundary", "--" + boundary, line);
    assertEntityHeaders(reader, "text/plain", "bytes 0-9/79");
    assertEquals("The quick ", reader.readLine());

    assertEquals("Expected content to start with boundary", "--" + boundary, reader.readLine());
    assertEntityHeaders(reader, "text/plain", "bytes 69-78/79");
    assertEquals("corpus sic", reader.readLine());

    char[] buf = new char[boundary.length() + 4];
    reader.read(buf);
    assertEquals("Expected content to start with boundary", "--" + boundary + "--", new String(buf));
}

From source file:org.eclipse.orion.internal.server.servlets.xfer.ClientImport.java

private byte[] readMultiPartChunk(ServletInputStream requestStream, String contentType) throws IOException {
    //fast forward stream past multi-part header
    int boundaryOff = contentType.indexOf("boundary="); //$NON-NLS-1$
    String boundary = contentType.substring(boundaryOff + 9);
    BufferedReader reader = new BufferedReader(new InputStreamReader(requestStream, "ISO-8859-1")); //$NON-NLS-1$
    StringBuffer out = new StringBuffer();
    //skip headers up to the first blank line
    String line = reader.readLine();
    while (line != null && line.length() > 0)
        line = reader.readLine();//  w  w w.j a  v  a2s  . co  m
    //now process the file

    char[] buf = new char[1000];
    int read;
    while ((read = reader.read(buf)) > 0) {
        out.append(buf, 0, read);
    }
    //remove the boundary from the output (end of input is \r\n--<boundary>--\r\n)
    out.setLength(out.length() - (boundary.length() + 8));
    return out.toString().getBytes("ISO-8859-1"); //$NON-NLS-1$
}

From source file:nz.co.gregs.dbvolution.datatypes.DBByteArray.java

private byte[] getFromCharacterReader(ResultSet resultSet, String fullColumnName)
        throws SQLException, IOException {
    byte[] decodeBuffer = new byte[] {};
    Reader inputReader = null;//from   w  ww.  j  a  v  a  2 s.  c o m
    try {
        inputReader = resultSet.getCharacterStream(fullColumnName);
    } catch (NullPointerException nullEx) {
        ;// NullPointerException is thrown by a SQLite-JDBC bug sometimes.
    }
    if (inputReader != null) {
        if (resultSet.wasNull()) {
            this.setToNull();
        } else {
            BufferedReader input = new BufferedReader(inputReader);
            List<byte[]> byteArrays = new ArrayList<byte[]>();

            int totalBytesRead = 0;
            try {
                char[] resultSetBytes;
                resultSetBytes = new char[100000];
                int bytesRead = input.read(resultSetBytes);
                while (bytesRead > 0) {
                    totalBytesRead += bytesRead;
                    byteArrays.add(String.valueOf(resultSetBytes).getBytes());
                    resultSetBytes = new char[100000];
                    bytesRead = input.read(resultSetBytes);
                }
            } catch (IOException ex) {
                Logger.getLogger(DBByteArray.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                input.close();
            }
            byte[] bytes = new byte[totalBytesRead];
            int bytesAdded = 0;
            for (byte[] someBytes : byteArrays) {
                System.arraycopy(someBytes, 0, bytes, bytesAdded,
                        Math.min(someBytes.length, bytes.length - bytesAdded));
                bytesAdded += someBytes.length;
            }
            decodeBuffer = Base64.decodeBase64(bytes);
            //            this.setValue(decodeBuffer);
        }
    }
    return decodeBuffer;
}

From source file:fsi_admin.JPacConn.java

private void ingresarRegistroFallido(String IP, String host, String servidor, String usuario, String password,
        HttpServletRequest request, String error, int nivelError) {
    StringBuffer sb = new StringBuffer();
    BufferedReader bufferedReader = null;
    try {//  ww  w  .j a  va  2s . c o  m
        bufferedReader = request.getReader();
        char[] charBuffer = new char[128];
        int bytesRead;
        while ((bytesRead = bufferedReader.read(charBuffer)) != -1) {
            sb.append(charBuffer, 0, bytesRead);
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    //System.out.println(sb.toString());
    Calendar cal = GregorianCalendar.getInstance();
    String SQL = "INSERT INTO TBL_PAC_REGISTROS_FALLIDOS\n";
    SQL += "VALUES(default,'" + JUtil.q(IP) + "','" + JUtil.q(host) + "','" + JUtil.obtFechaHoraSQL(cal) + "','"
            + (servidor != null ? JUtil.q(servidor) : "nulo") + "','"
            + (usuario != null ? JUtil.q(usuario) : "nulo") + "','"
            + (password != null ? JUtil.q(password) : "nulo") + "','" + JUtil.q(sb.toString()) + "','"
            + JUtil.q(error) + "','" + nivelError + "','PAC')";
    try {
        Connection con = JAccesoBD.getConexion();
        Statement s = con.createStatement();
        s.executeUpdate(SQL);
        s.close();
        JAccesoBD.liberarConexion(con);
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

From source file:nz.co.gregs.dbvolution.datatypes.DBByteArray.java

private byte[] getFromCLOB(ResultSet resultSet, String fullColumnName) throws SQLException {
    byte[] bytes = new byte[] {};
    Clob clob = resultSet.getClob(fullColumnName);
    if (resultSet.wasNull() || clob == null) {
        this.setToNull();
    } else {/*from   w w w  . j  a v  a2 s .c  om*/
        final Reader characterStream = clob.getCharacterStream();
        try {
            BufferedReader input = new BufferedReader(characterStream);
            List<byte[]> byteArrays = new ArrayList<byte[]>();

            int totalBytesRead = 0;
            try {
                char[] resultSetBytes;
                resultSetBytes = new char[100000];
                try {
                    int bytesRead = input.read(resultSetBytes);
                    while (bytesRead > 0) {
                        totalBytesRead += bytesRead;
                        byteArrays.add(String.valueOf(resultSetBytes).getBytes());
                        resultSetBytes = new char[100000];
                        bytesRead = input.read(resultSetBytes);
                    }
                } finally {
                    input.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(DBByteArray.class.getName()).log(Level.SEVERE, null, ex);
            }
            bytes = new byte[totalBytesRead];
            int bytesAdded = 0;
            for (byte[] someBytes : byteArrays) {
                System.arraycopy(someBytes, 0, bytes, bytesAdded,
                        Math.min(someBytes.length, bytes.length - bytesAdded));
                bytesAdded += someBytes.length;
            }
        } finally {
            try {
                characterStream.close();
            } catch (IOException ex) {
                Logger.getLogger(DBByteArray.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        //         this.setValue(bytes);
    }
    return bytes;
}

From source file:org.voota.api.VootaApi.java

/**
 * Convert InputStream object to String object. Method is used by other VootaApi
 * methods to convert content of server reply to String.
 *
 * @param  istream    object to convert//from  w  ww .  j  ava 2s . c o m
 * @return            String object contains the same content as parameter
 */
private String convertIStreamToString(InputStream istream) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(istream));
    StringBuilder strBuilder = new StringBuilder();

    char[] chBuffer = new char[1024];
    int nActualBytes = 0;
    try {
        while ((nActualBytes = reader.read(chBuffer)) != -1) {
            strBuilder.append(chBuffer, 0, nActualBytes);
        }
    } catch (Throwable e) {
    } finally {
        try {
            istream.close();
        } catch (IOException e) {
        }
    }

    return strBuilder.toString();
}

From source file:com.wordnik.swaggersocket.server.SwaggerSocketProtocolInterceptor.java

@Override
public Action inspect(final AtmosphereResource r) {

    final AtmosphereRequest request = r.getRequest();
    r.addEventListener(new AtmosphereResourceEventListenerAdapter() {
        /**/*from ww w  . ja  v a 2  s. c  om*/
         * {@inheritDoc}
         */
        @Override
        public void onSuspend(AtmosphereResourceEvent event) {
            AsyncIOWriter writer = event.getResource().getResponse().getAsyncIOWriter();
            if (writer == null) {
                writer = new AtmosphereInterceptorWriter();
                r.getResponse().asyncIOWriter(writer);
            }

            if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) {
                AtmosphereInterceptorWriter.class.cast(writer).interceptor(interceptor);
            }
        }
    });

    boolean ok = false;
    if (request.getHeader("SwaggerSocket") != null) {
        ok = true;
    }

    if (ok && request.attributes().get(SWAGGER_SOCKET_DISPATCHED) == null) {

        AtmosphereResponse response = new WrappedAtmosphereResponse(r.getResponse(), request);

        logger.debug("Method {} Transport {}", request.getMethod(), r.transport());
        // Suspend to keep the connection OPEN.
        if (request.getMethod() == "GET" && r.transport().equals(AtmosphereResource.TRANSPORT.LONG_POLLING)) {
            r.resumeOnBroadcast(true).suspend();

            BlockingQueue<AtmosphereResource> queue = (BlockingQueue<AtmosphereResource>) getContextValue(
                    request, SUSPENDED_RESPONSE);
            if (queue == null) {
                queue = new LinkedBlockingQueue<AtmosphereResource>();
                request.getSession().setAttribute(SUSPENDED_RESPONSE, queue);
            }
            queue.offer(r);

            String identity = (String) getContextValue(request, IDENTITY);
            schedule(r, identity);

            return Action.SUSPEND;
        }

        AtmosphereFramework framework = r.getAtmosphereConfig().framework();
        StringBuilder d = new StringBuilder();
        try {
            InputStreamReader isr = new InputStreamReader(request.getInputStream());
            BufferedReader bufReader = new BufferedReader(isr);
            char[] charBuffer = new char[8192];

            for (int readCount = bufReader.read(charBuffer); readCount > -1; readCount = bufReader
                    .read(charBuffer)) {
                d.append(charBuffer, 0, readCount);
            }

            String data = d.toString();

            if (data.length() == 0) {
                return Action.CANCELLED;
            }

            String message = data.substring(0, 20).replaceAll(" ", "");
            logger.debug(data);
            if (message.startsWith("{\"handshake\"")) {
                // This will fail if the message is not well formed.
                HandshakeMessage handshakeMessage = mapper.readValue(data, HandshakeMessage.class);

                // If we missed the CloseReason for whatever reason (IE is a good candidate), make sure we swap the previous session anyway.
                String identity = (String) getContextValue(request, IDENTITY);
                if (identity == null) {
                    identity = UUID.randomUUID().toString();
                } else {
                    logger.debug("Client disconnected {}, cleaning session {}", identity);
                    try {
                        Enumeration<String> e = request.getSession().getAttributeNames();
                        while (e.hasMoreElements()) {
                            request.getSession().removeAttribute(e.nextElement());
                        }
                    } catch (Exception ex) {
                        logger.warn("", ex);
                    }
                }
                addContextValue(request, IDENTITY, identity);

                StatusMessage statusMessage = new StatusMessage.Builder()
                        .status(new StatusMessage.Status(200, "OK")).identity(identity).build();
                response.setContentType("application/json");
                response.getOutputStream().write(mapper.writeValueAsBytes(statusMessage));

                if (r.transport() == AtmosphereResource.TRANSPORT.WEBSOCKET) {
                    schedule(r, identity);
                }
            } else if (message.startsWith("{\"close\"")) {
                CloseMessage c = mapper.readValue(data, CloseMessage.class);

                logger.debug("Client disconnected {} with reason {}", c.getClose().getIdentity(),
                        c.getClose().getReason());
                try {
                    request.getSession().invalidate();
                } catch (Exception ex) {
                    logger.warn("", ex);
                }
                return Action.CANCELLED;
            } else {
                Message swaggerSocketMessage = mapper.readValue(data, Message.class);
                swaggerSocketMessage.transactionID(UUID.randomUUID().toString());

                String identity = (String) getContextValue(request, IDENTITY);

                if (!swaggerSocketMessage.getIdentity().equals(identity)) {
                    StatusMessage statusMessage = new StatusMessage.Builder()
                            .status(new StatusMessage.Status(503, "Not Allowed"))
                            .identity(swaggerSocketMessage.getIdentity()).build();
                    response.getOutputStream().write(mapper.writeValueAsBytes(statusMessage));
                    return Action.CANCELLED;
                }

                transactionIdentity.set(swaggerSocketMessage.transactionID());

                List<Request> requests = swaggerSocketMessage.getRequests();
                addContextValue(request, swaggerSocketMessage.transactionID() + RESPONSE_COUNTER,
                        new AtomicInteger(requests.size()));

                AtmosphereRequest ar;
                for (Request req : requests) {
                    ar = toAtmosphereRequest(request, req);
                    try {
                        ar.attributes().put(SWAGGER_SOCKET_DISPATCHED, "true");

                        // This is a new request, we must clean the Websocket AtmosphereResource.
                        request.removeAttribute(INJECTED_ATMOSPHERE_RESOURCE);
                        response.request(ar);
                        attachWriter(r);
                        ssRequest.set(req);
                        request.setAttribute("swaggerSocketRequest", req);

                        Action action = framework.doCometSupport(ar, response);
                        if (action.type() == Action.TYPE.SUSPEND) {
                            ar.destroyable(false);
                            response.destroyable(false);
                        }
                    } catch (Exception e) {
                        logger.warn("", e);
                        //REVISIT might want to optionally return the body entity?
                        response.setStatus(500, "Server Error");
                        ResponseMessage responseMessage = new ResponseMessage(identity,
                                createResponseBuilder(response, null).build());
                        response.getOutputStream().write(mapper.writeValueAsBytes(responseMessage));
                    }
                }
            }
            return Action.CANCELLED;
        } catch (IOException e) {
            logger.warn("", e);
            return Action.CONTINUE;
        }

    } else {
        if (!ok) {
            request.setAttribute(TrackMessageSizeInterceptor.SKIP_INTERCEPTOR, "true");
        }
    }
    return Action.CONTINUE;
}