Example usage for java.io BufferedInputStream read

List of usage examples for java.io BufferedInputStream read

Introduction

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

Prototype

public synchronized int read() throws IOException 

Source Link

Document

See the general contract of the read method of InputStream.

Usage

From source file:cc.creativecomputing.io.CCIOUtil.java

static public byte[] loadBytes(InputStream input) {
    try {//from  w  w w  .  ja v  a2  s. co  m
        BufferedInputStream bis = new BufferedInputStream(input);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int c = bis.read();
        while (c != -1) {
            out.write(c);
            c = bis.read();
        }
        return out.toByteArray();

    } catch (IOException e) {
        e.printStackTrace();
        //throw new RuntimeException("Couldn't load bytes from stream");
    }
    return null;
}

From source file:com.wandisco.s3hdfs.rewrite.filter.S3HdfsTestUtil.java

String readInputStream(InputStream inputStream) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(inputStream);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    int result = bis.read();
    while (result != -1) {
        byte b = (byte) result;
        buf.write(b);// w  w  w  . j av a 2s. c o  m
        result = bis.read();
    }
    return buf.toString();
}

From source file:fedora.server.rest.RestUtil.java

/**
 * Retrieves the contents of the HTTP Request.
 * @return InputStream from the request//from w  ww .ja va 2s . com
 */
public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception {
    RequestContent rContent = null;

    // See if the request is a multi-part file upload request
    if (ServletFileUpload.isMultipartContent(request)) {

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request, use the first available File item
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                rContent = new RequestContent();
                rContent.contentStream = item.openStream();
                rContent.mimeType = item.getContentType();

                FileItemHeaders itemHeaders = item.getHeaders();
                if (itemHeaders != null) {
                    String contentLength = itemHeaders.getHeader("Content-Length");
                    if (contentLength != null) {
                        rContent.size = Integer.parseInt(contentLength);
                    }
                }

                break;
            }
        }
    } else {
        // If the content stream was not been found as a multipart,
        // try to use the stream from the request directly
        if (rContent == null) {
            if (request.getContentLength() > 0) {
                rContent = new RequestContent();
                rContent.contentStream = request.getInputStream();
                rContent.size = request.getContentLength();
            } else {
                String transferEncoding = request.getHeader("Transfer-Encoding");
                if (transferEncoding != null && transferEncoding.contains("chunked")) {
                    BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
                    bis.mark(2);
                    if (bis.read() > 0) {
                        bis.reset();
                        rContent = new RequestContent();
                        rContent.contentStream = bis;
                    }
                }
            }
        }
    }

    // Attempt to set the mime type and size if not already set
    if (rContent != null) {
        if (rContent.mimeType == null) {
            MediaType mediaType = headers.getMediaType();
            if (mediaType != null) {
                rContent.mimeType = mediaType.toString();
            }
        }

        if (rContent.size == 0) {
            List<String> lengthHeaders = headers.getRequestHeader("Content-Length");
            if (lengthHeaders != null && lengthHeaders.size() > 0) {
                rContent.size = Integer.parseInt(lengthHeaders.get(0));
            }
        }
    }

    return rContent;
}

From source file:de.betterform.agent.web.servlet.XFormsRequestURIServlet.java

/**
 * This servlet uses the requestURI to locate and parse a XForms document for processing. The actual processing
 * is done by XFormsFilter. The parsed DOM of the document is passed as a request param to the filter.
 *
 * @param request  servlet request//from w  ww.  j ava  2s .com
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOGGER.debug("hit XFormsRequestURIServlet");

    request.setCharacterEncoding("UTF-8");
    WebUtil.nonCachingResponse(response);

    Document doc;

    //locate it
    String formRequestURI = request.getRequestURI().substring(request.getContextPath().length() + 1);
    String realPath = null;
    try {
        realPath = WebFactory.getRealPath(formRequestURI, getServletContext());
    } catch (XFormsConfigException e) {
        throw new ServletException(e);
    }
    File xfDoc = new File(realPath);

    if (request.getHeader("betterform-internal") != null) {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(xfDoc));
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

        int read;
        while ((read = in.read()) > -1) {
            out.write(read);
        }
        out.flush();
    } else {
        try {
            //parse it
            doc = DOMUtil.parseXmlFile(xfDoc, true, false);
        } catch (ParserConfigurationException e) {
            throw new ServletException(e);
        } catch (SAXException e) {
            throw new ServletException(e);
        }

        request.setAttribute(WebFactory.XFORMS_NODE, doc);
        //do the Filter twist
        response.getOutputStream().close();
    }
}

From source file:backend.translator.GTranslator.java

private File downloadFile(String url) throws IOException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);
    request.addHeader("User-Agent", "Mozilla/5.0");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    BufferedInputStream bis = new BufferedInputStream(entity.getContent());
    File f = new File(R.TRANS_RESULT_PATH);
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
    int inByte;//from www.  jav  a  2 s.  co  m
    while ((inByte = bis.read()) != -1)
        bos.write(inByte);

    bis.close();
    bos.close();
    return f;
}

From source file:com.norconex.collector.http.fetch.impl.GenericDocumentFetcher.java

@Override
public CrawlState fetchDocument(HttpClient httpClient, HttpDocument doc) {
    //TODO replace signature with Writer class.
    LOG.debug("Fetching document: " + doc.getReference());
    HttpRequestBase method = null;//from ww  w . j a  v  a 2  s. c om
    try {
        method = createUriRequest(doc);

        // Execute the method.
        HttpResponse response = httpClient.execute(method);
        int statusCode = response.getStatusLine().getStatusCode();

        InputStream is = response.getEntity().getContent();

        if (ArrayUtils.contains(validStatusCodes, statusCode)) {
            //--- Fetch headers ---
            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Header header = headers[i];
                String name = header.getName();
                if (StringUtils.isNotBlank(headersPrefix)) {
                    name = headersPrefix + name;
                }
                if (doc.getMetadata().getString(name) == null) {
                    doc.getMetadata().addString(name, header.getValue());
                }
            }

            //--- Fetch body
            doc.setContent(doc.getContent().newInputStream(is));

            //read a copy to force caching and then close the HTTP stream
            IOUtils.copy(doc.getContent(), new NullOutputStream());
            return HttpCrawlState.NEW;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Rejected response content: " + IOUtils.toString(is));
            IOUtils.closeQuietly(is);
        } else {
            // read response anyway to be safer, but ignore content
            BufferedInputStream bis = new BufferedInputStream(is);
            int result = bis.read();
            while (result != -1) {
                result = bis.read();
            }
            IOUtils.closeQuietly(bis);
        }
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return HttpCrawlState.NOT_FOUND;
        }
        LOG.debug("Unsupported HTTP Response: " + response.getStatusLine());
        return CrawlState.BAD_STATUS;
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.error("Cannot fetch document: " + doc.getReference() + " (" + e.getMessage() + ")", e);
        } else {
            LOG.error("Cannot fetch document: " + doc.getReference() + " (" + e.getMessage() + ")");
        }
        throw new CollectorException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.leapfrog.springFramework.Controller.UserDashBoardController.java

@RequestMapping(value = "/display", method = RequestMethod.GET)
public void displayImage(HttpServletRequest request, HttpServletResponse response) {
    try {/*w  w  w. ja v  a 2 s  . c o m*/
        String fileName = request.getParameter("image");
        FileInputStream fis = null;
        if (fileName != null) {
            fis = new FileInputStream(new File(fileName));
            BufferedInputStream bis = new BufferedInputStream(fis);
            response.setContentType("text/html");
            BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
            for (int data; (data = bis.read()) > -1;) {
                output.write(data);
            }
        }
    } catch (IOException e) {

    } finally {
        // close the streams
    }
}

From source file:fedora.test.integration.TestLargeDatastreams.java

private long exportAPIALite(String dsId) throws Exception {
    String url = apia.describeRepository().getRepositoryBaseURL() + "/get/" + pid + "/" + dsId;
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.setDoAuthentication(true);
    httpMethod.getParams().setParameter("Connection", "Keep-Alive");

    HttpClient client = fedoraClient.getHttpClient();
    client.executeMethod(httpMethod);// www .j  av a2 s . c o m
    BufferedInputStream dataStream = new BufferedInputStream(httpMethod.getResponseBodyAsStream());

    long bytesRead = 0;
    while (dataStream.read() >= 0) {
        ++bytesRead;
    }

    return bytesRead;
}

From source file:org.andicar.service.UpdateCheckService.java

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    if (getSharedPreferences(StaticValues.GLOBAL_PREFERENCE_NAME, Context.MODE_MULTI_PROCESS)
            .getBoolean("SendCrashReport", true))
        Thread.setDefaultUncaughtExceptionHandler(
                new AndiCarExceptionHandler(Thread.getDefaultUncaughtExceptionHandler(), this));

    try {//from   w ww.  j  a va  2s . com
        Bundle extras = intent.getExtras();
        if (extras == null || extras.getBoolean("setJustNextRun") || !extras.getBoolean("AutoUpdateCheck")) {
            setNextRun();
            stopSelf();
        }

        URL updateURL = new URL(StaticValues.VERSION_FILE_URL);
        URLConnection conn = updateURL.openConnection();
        if (conn == null)
            return;
        InputStream is = conn.getInputStream();
        if (is == null)
            return;
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        String s = new String(baf.toByteArray());
        /* Get current Version Number */
        int curVersion = getPackageManager().getPackageInfo("org.andicar.activity", 0).versionCode;
        int newVersion = Integer.valueOf(s);

        /* Is a higher version than the current already out? */
        if (newVersion > curVersion) {
            //get the whats new message
            updateURL = new URL(StaticValues.WHATS_NEW_FILE_URL);
            conn = updateURL.openConnection();
            if (conn == null)
                return;
            is = conn.getInputStream();
            if (is == null)
                return;
            bis = new BufferedInputStream(is);
            baf = new ByteArrayBuffer(50);
            current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            /* Convert the Bytes read to a String. */
            s = new String(baf.toByteArray());

            mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notification = null;
            Intent i = new Intent(this, WhatsNewDialog.class);
            i.putExtra("UpdateMsg", s);
            PendingIntent contentIntent = PendingIntent.getActivity(UpdateCheckService.this, 0, i, 0);

            CharSequence title = getText(R.string.Notif_UpdateTitle);
            String message = getString(R.string.Notif_UpdateMsg);
            notification = new Notification(R.drawable.icon_sys_info, message, System.currentTimeMillis());
            notification.flags |= Notification.DEFAULT_LIGHTS;
            notification.flags |= Notification.DEFAULT_SOUND;
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.setLatestEventInfo(UpdateCheckService.this, title, message, contentIntent);
            mNM.notify(StaticValues.NOTIF_UPDATECHECK_ID, notification);
            setNextRun();
        }
        stopSelf();
    } catch (Exception e) {
        Log.i("UpdateService", "Service failed.");
        e.printStackTrace();
    }
}

From source file:org.caboclo.clients.ApiClient.java

protected void downloadURL(String url, File file, Map<String, String> headers)
        throws IllegalStateException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    for (String key : headers.keySet()) {
        String value = headers.get(key);

        httpget.setHeader(key, value);/*from  ww  w  .ja  v  a2 s. c o m*/
    }

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        try {
            InputStream instream = entity.getContent();
            BufferedInputStream bis = new BufferedInputStream(instream);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            int inByte;
            while ((inByte = bis.read()) != -1) {
                bos.write(inByte);
            }
            bis.close();
            bos.close();
        } catch (IOException ex) {
            throw ex;
        } catch (IllegalStateException ex) {
            httpget.abort();
            throw ex;
        }
        httpclient.getConnectionManager().shutdown();
    }
}