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 int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:gash.router.app.DemoApp.java

private ArrayList<ByteString> divideFileChunks(File file) throws IOException {
    ArrayList<ByteString> chunkedFile = new ArrayList<ByteString>();
    int sizeOfFiles = 1024 * 1024; // equivalent to 1 Megabyte
    byte[] buffer = new byte[sizeOfFiles];

    try {/*  www .  ja va 2s  .  c om*/
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int tmp = 0;
        while ((tmp = bis.read(buffer)) > 0) {
            ByteString byteString = ByteString.copyFrom(buffer, 0, tmp);
            chunkedFile.add(byteString);
        }
        return chunkedFile;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.cloudseal.spring.client.namespace.CloudSealLogoutImageFilter.java

public void writeContent(HttpServletResponse response, String contentType, InputStream content)
        throws IOException {
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {// www. j ava2 s .  co  m
        input = new BufferedInputStream(content, DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length = 0;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        output.close();
        input.close();
    }
}

From source file:com.cubusmail.gwtui.server.services.RetrieveAttachmentServlet.java

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

    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(request.getSession().getServletContext());

    try {//www. j  av a2 s .  c o m
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean view = "1".equals(request.getParameter("view"));

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
            int index = Integer.valueOf(attachmentIndex);

            MimePart retrievePart = attachmentList.get(index);

            ContentType contentType = new ContentType(retrievePart.getContentType());

            String fileName = retrievePart.getFileName();
            if (StringUtils.isEmpty(fileName)) {
                fileName = context.getMessage("message.unknown.attachment", null,
                        SessionManager.get().getLocale());
            }
            StringBuffer contentDisposition = new StringBuffer();
            if (!view) {
                contentDisposition.append("attachment; filename=\"");
                contentDisposition.append(fileName).append("\"");
            }

            response.setHeader("cache-control", "no-store");
            response.setHeader("pragma", "no-cache");
            response.setIntHeader("max-age", 0);
            response.setIntHeader("expires", 0);

            if (!StringUtils.isEmpty(contentDisposition.toString())) {
                response.setHeader("Content-disposition", contentDisposition.toString());
            }
            response.setContentType(contentType.getBaseType());
            // response.setContentLength(
            // MessageUtils.calculateSizeFromPart( retrievePart ) );

            BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
                outputStream.write(inBuf, 0, len);
                total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();

        }
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:com.cubusmail.server.services.RetrieveAttachmentServlet.java

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

    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(request.getSession().getServletContext());

    try {//from   w w  w  .jav  a 2 s  . c  om
        String messageId = request.getParameter("messageId");
        String attachmentIndex = request.getParameter("attachmentIndex");
        boolean view = "1".equals(request.getParameter("view"));

        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            List<MimePart> attachmentList = MessageUtils.attachmentsFromPart(msg);
            int index = Integer.valueOf(attachmentIndex);

            MimePart retrievePart = attachmentList.get(index);

            ContentType contentType = new ContentType(retrievePart.getContentType());

            String fileName = retrievePart.getFileName();
            if (StringUtils.isEmpty(fileName)) {
                fileName = context.getMessage("message.unknown.attachment", null,
                        SessionManager.get().getLocale());
            }
            StringBuffer contentDisposition = new StringBuffer();
            if (!view) {
                contentDisposition.append("attachment; filename=\"");
                contentDisposition.append(fileName).append("\"");
            }

            response.setHeader("cache-control", "no-store");
            response.setHeader("pragma", "no-cache");
            response.setIntHeader("max-age", 0);
            response.setIntHeader("expires", 0);

            if (!StringUtils.isEmpty(contentDisposition.toString())) {
                response.setHeader("Content-disposition", contentDisposition.toString());
            }
            response.setContentType(contentType.getBaseType());
            // response.setContentLength(
            // MessageUtils.calculateSizeFromPart( retrievePart ) );

            BufferedInputStream bufInputStream = new BufferedInputStream(retrievePart.getInputStream());
            OutputStream outputStream = response.getOutputStream();

            byte[] inBuf = new byte[1024];
            int len = 0;
            int total = 0;
            while ((len = bufInputStream.read(inBuf)) > 0) {
                outputStream.write(inBuf, 0, len);
                total += len;
            }

            bufInputStream.close();
            outputStream.flush();
            outputStream.close();

        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:gsn.wrappers.GPSGenerator.java

public boolean initialize() {
    AddressBean addressBean = getActiveAddressBean();
    if (addressBean.getPredicateValue("rate") != null) {
        samplingRate = ParamParser.getInteger(addressBean.getPredicateValue("rate"), DEFAULT_SAMPLING_RATE);
        if (samplingRate <= 0) {
            logger.warn(/*from   w w  w.j a va2  s.co m*/
                    "The specified >sampling-rate< parameter for the >MemoryMonitoringWrapper< should be a positive number.\nGSN uses the default rate ("
                            + DEFAULT_SAMPLING_RATE + "ms ).");
            samplingRate = DEFAULT_SAMPLING_RATE;
        }
    }
    if (addressBean.getPredicateValue("picture") != null) {
        String picture = addressBean.getPredicateValue("picture");
        File pictureF = new File(picture);
        if (!pictureF.isFile() || !pictureF.canRead()) {
            logger.warn("The GPSGenerator can't access the specified picture file. Initialization failed.");
            return false;
        }
        try {
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(pictureF));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4 * 1024];
            while (fis.available() > 0)
                outputStream.write(buffer, 0, fis.read(buffer));
            fis.close();
            this.picture = outputStream.toByteArray();
            outputStream.close();
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage(), e);
            return false;
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
    } else {
        logger.warn("The >picture< parameter is missing from the GPSGenerator wrapper.");
        return false;
    }
    ArrayList<DataField> output = new ArrayList<DataField>();
    for (int i = 0; i < FIELD_NAMES.length; i++)
        output.add(new DataField(FIELD_NAMES[i], FIELD_TYPES_STRING[i], FIELD_DESCRIPTION[i]));
    outputStrcture = output.toArray(new DataField[] {});
    return true;
}

From source file:com.aionengine.gameserver.cache.HTMLCache.java

public String loadFile(File file) {
    if (isLoadable(file)) {
        BufferedInputStream bis = null;
        try {//from  www.j a  v a2s.c  o  m
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] raw = new byte[bis.available()];
            bis.read(raw);

            String content = new String(raw, HTMLConfig.HTML_ENCODING);
            String relpath = getRelativePath(HTML_ROOT, file);

            size += content.length();

            String oldContent = cache.get(relpath);
            if (oldContent == null)
                loadedFiles++;
            else
                size -= oldContent.length();

            cache.put(relpath, content);

            return content;
        } catch (Exception e) {
            log.warn("Problem with htm file:", e);
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }

    return null;
}

From source file:com.orange.labs.sdk.RestUtils.java

public void uploadRequest(URL url, File file, String folderIdentifier, final Map<String, String> headers,
        final OrangeListener.Success<JSONObject> success, final OrangeListener.Progress progress,
        final OrangeListener.Error failure) {

    // open a URL connection to the Server
    FileInputStream fileInputStream = null;
    try {//from   w  ww  .  j  a v  a2 s  .com
        fileInputStream = new FileInputStream(file);

        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpsURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Don't use a Cached Copy
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");

        //
        // Define headers
        //

        // Create an unique boundary
        String boundary = "UploadBoundary";

        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key.toString(), headers.get(key));
        }

        //
        // Write body part
        //
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        int bytesAvailable = fileInputStream.available();

        String marker = "\r\n--" + boundary + "\r\n";

        dos.writeBytes(marker);
        dos.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");

        // Create JSonObject :
        JSONObject params = new JSONObject();
        params.put("name", file.getName());
        params.put("size", String.valueOf(bytesAvailable));
        params.put("folder", folderIdentifier);

        dos.writeBytes(params.toString());

        dos.writeBytes(marker);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
        dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");

        int progressValue = 0;
        int bytesRead = 0;
        byte buf[] = new byte[1024];
        BufferedInputStream bufInput = new BufferedInputStream(fileInputStream);
        while ((bytesRead = bufInput.read(buf)) != -1) {
            // write output
            dos.write(buf, 0, bytesRead);
            dos.flush();
            progressValue += bytesRead;
            // update progress bar
            progress.onProgress((float) progressValue / bytesAvailable);
        }

        dos.writeBytes(marker);

        //
        // Responses from the server (code and message)
        //
        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        if (serverResponseCode == 200 || serverResponseCode == 201) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Response: " + line);
                response += line;
            }
            rd.close();
            JSONObject object = new JSONObject(response);
            success.onResponse(object);
        } else {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Error: " + line);
                response += line;
            }
            rd.close();
            JSONObject errorResponse = new JSONObject(response);
            failure.onErrorResponse(new CloudAPIException(serverResponseCode, errorResponse));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:nu.nethome.home.items.web.proxy.HomeCloudConnection.java

private HttpResponse performLocalRequest(HttpRequest request) throws IOException {
    HttpResponse httpResponse;//from w  ww . ja v  a  2  s .  c  o  m
    HttpURLConnection connection = (HttpURLConnection) new URL(localURL + request.url).openConnection();
    for (String header : request.headers) {
        String parts[] = header.split(":");
        connection.setRequestProperty(parts[0].trim(), parts[1].trim());
    }
    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    try (InputStream response = connection.getInputStream()) {
        BufferedInputStream bis = new BufferedInputStream(response);
        int read;
        int bufSize = 512;
        byte[] buffer = new byte[bufSize];
        while (true) {
            read = bis.read(buffer);
            if (read == -1) {
                break;
            }
            baf.append(buffer, 0, read);
        }
    } catch (IOException e) {
        return new HttpResponse(systemId, "", new String[0], CHALLENGE);
    }

    Map<String, List<String>> map = connection.getHeaderFields();
    String headers[] = new String[map.size()];
    int i = 0;
    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
        headers[i++] = entry.getKey() + ":" + entry.getValue().get(0);
    }
    httpResponse = new HttpResponse(systemId, new String(Base64.encodeBase64(baf.toByteArray())), headers,
            CHALLENGE);
    return httpResponse;
}

From source file:com.aionemu.gameserver.cache.HTMLCache.java

public String loadFile(File file) {
    if (isLoadable(file)) {
        BufferedInputStream bis = null;
        try {/*  ww w  .j  a v  a2  s.c  o  m*/
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] raw = new byte[bis.available()];
            bis.read(raw);

            String content = new String(raw, HTMLConfig.HTML_ENCODING);
            String relpath = getRelativePath(HTML_ROOT, file);

            size += content.length();

            String oldContent = cache.get(relpath);
            if (oldContent == null) {
                loadedFiles++;
            } else {
                size -= oldContent.length();
            }

            cache.put(relpath, content);

            return content;
        } catch (Exception e) {
            log.warn("Problem with htm file:", e);
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }

    return null;
}

From source file:jp.co.opentone.bsol.linkbinder.view.logo.ProjectLogoManager.java

/**
 * ??(??)??.//w w w .  j ava  2 s.c  om
 *
 * @param logoFile ??
 * @return (??)
 */
private ProjectLogo getLogoData(String logoFile) {
    ProjectLogo result = null;
    BufferedInputStream bis = null;

    try {
        File f = new File(logoFile);
        long lastModifiled = f.lastModified();
        byte[] imageData = new byte[(int) f.length()];
        bis = new BufferedInputStream(new FileInputStream(logoFile));
        bis.read(imageData);

        result = new ProjectLogo();
        result.setImage(imageData);
        result.setLastModified(lastModifiled);
    } catch (FileNotFoundException e) {
        log.warn("????? [" + logoFile + "]");
    } catch (IOException e) {
        log.error("File I/O error[" + logoFile + "]", e);
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                log.error("File close error.[" + logoFile + "]", e);
            }
        }
    }
    return result;
}