Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:io.aino.agents.core.Sender.java

private byte[] getRequestContent() {
    if (!agentConfig.isGzipEnabled()) {
        return stringToSend.getBytes();
    }//from  ww  w .j a  v a  2 s .c o m

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzipStream = new GZIPOutputStream(baos);
        gzipStream.write(stringToSend.getBytes());

        gzipStream.finish();
        baos.flush();
        byte[] returnBytes = baos.toByteArray();
        baos.close();
        gzipStream.close();

        return returnBytes;
    } catch (IOException e) {
        throw new AgentCoreException("Failed to compress Aino log message using gzip.");
    }
}

From source file:com.patrolpro.servlet.UploadFileServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w w. j  ava  2 s .  com*/
 *
 * @param request servlet request
 * @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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        String companyId = request.getParameter("companyId");

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> fields = upload.parseRequest(request);

        FileItem fileData = null;
        Integer employeeId = null;
        for (int f = 0; f < fields.size(); f++) {
            if (fields.get(f).getFieldName().equals("file_data")) {
                fileData = fields.get(f);
            } else if (fields.get(f).getFieldName().equals("employeeId")) {
                employeeId = Integer.parseInt(fields.get(f).getString());
            }
        }

        InputStream iStream = fileData.getInputStream();

        String beanName = request.getParameter("beanName");

        FacesContext context = FacesServletContextFactory.getInstance().getFacesContext(request, response);
        UploadFileInterface reportHolderBean = context.getApplication().evaluateExpressionGet(context,
                "#{" + beanName + "}", UploadFileInterface.class);

        ByteArrayOutputStream bOutput = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        int bufCount = 0;
        while ((bufCount = iStream.read(buffer)) > -1) {
            bOutput.write(buffer, 0, bufCount);
        }
        bOutput.flush();
        String responseStr = reportHolderBean.processFileUpload(companyId, bOutput.toByteArray(), employeeId);
        if (responseStr.equals("success")) {
            out.write("{}");
            out.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:apiserver.model.Document.java

public void setFile(Object file) throws IOException {
    // if byte[] write to tmp file and then cache that.
    if (file instanceof FileByteWrapper) {
        String[] nameParts = ((FileByteWrapper) file).getName().split("\\.");
        File tmpFile = File.createTempFile(nameParts[0], "." + nameParts[1]);
        //convert array of bytes into file
        FileOutputStream fs = new FileOutputStream(tmpFile);
        fs.write(((FileByteWrapper) file).getBytes());
        fs.close();//from   w ww  . ja  v  a  2 s .  co  m
        tmpFile.deleteOnExit();
        file = tmpFile;
    }

    if (file instanceof File) {
        if (!((File) file).exists() || ((File) file).isDirectory()) {
            throw new IOException("Invalid File Reference");
        }

        fileName = ((File) file).getName();
        this.file = file;
        this.setFileName(fileName);
        this.contentType = MimeType.getMimeType(fileName);

        byte[] bytes = FileUtils.readFileToByteArray(((File) file));
        this.setFileBytes(bytes);
        this.setSize(new Integer(bytes.length).longValue());
    } else if (file instanceof MultipartFile) {
        fileName = ((MultipartFile) file).getOriginalFilename();
        this.setContentType(MimeType.getMimeType(((MultipartFile) file).getContentType()));
        this.setFileName(((MultipartFile) file).getOriginalFilename());
        this.setFileBytes(((MultipartFile) file).getBytes());
        this.setSize(new Integer(this.getFileBytes().length).longValue());
    } else if (file instanceof BufferedImage) {
        if (fileName == null) {
            fileName = UUID.randomUUID().toString();
        }

        // Convert buffered reader to byte array
        String _mime = this.getContentType().name();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write((BufferedImage) file, _mime, byteArrayOutputStream);
        byteArrayOutputStream.flush();
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        this.setFileBytes(imageBytes);
    }

}

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

protected byte[] readStream(InputStream is) throws IOException {
    if (is == null) {
        fail("Null InputStream");
    }//from  www.  jav  a 2  s  .  com
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        final byte[] buffer = new byte[4096];
        int n = 0;
        while ((n = is.read(buffer, 0, buffer.length)) > 0) {
            bos.write(buffer, 0, n);
        }
    } finally {
        is.close();
        bos.flush();
        bos.close();
    }
    return bos.toByteArray();
}

From source file:info.track_mate.util.DefaultFTPClient.java

/** {@inheritDoc} */
public FileData download(String remoteFileName) throws Exception {
    byte[] dataBytes;
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    try {//from  w  w  w  . ja va2 s .co m
        downloadFile(remoteFileName, bytesOut);
        dataBytes = bytesOut.toByteArray();
    } catch (Exception e) {
        throw new Exception("Failed to download file", e);
    } finally {
        bytesOut.flush();
        bytesOut.close();
    }

    DefaultFileData fileData = new DefaultFileData();
    fileData.setName(remoteFileName);
    fileData.setData(dataBytes);

    return fileData;
}

From source file:javarestart.WebClassLoader.java

private Class<?> tryToLoadClass(InputStream in) throws IOException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    Utils.copy(in, buffer);//w ww.  j  av  a 2  s .  co  m
    buffer.flush();

    byte buf[] = buffer.toByteArray();
    return defineClass(null, buf, 0, buf.length);
}

From source file:org.deegree.securityproxy.authentication.wass.AddParameterAnonymousAuthenticationFilter.java

private void applyPostStrategy(HttpServletRequestBodyWrapper requestWrapper, String parameterValue)
        throws ServletException, IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ServletInputStream requestAsStream = requestWrapper.getInputStream();
    try {/*from   ww  w. ja v a  2 s .c  om*/
        postStrategy.modifyPostRequest(requestAsStream, outputStream, parameterValue);
        outputStream.flush();
        ByteArrayInputStream modifiedRequest = new ByteArrayInputStream(outputStream.toByteArray());
        requestWrapper.renewInputStream(modifiedRequest);
    } catch (XMLStreamException e) {
        throw new ServletException(e);
    } finally {
        closeQuietly(outputStream);
        closeQuietly(requestAsStream);
    }
}

From source file:etc.CloudStorage.java

private byte[] getByteFromStream(InputStream input) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {//from   w  w w . j av a2  s  .  c  om
        int nRead;
        byte[] data = new byte[16384];

        while ((nRead = input.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        buffer.flush();
    } finally {
        //  input.close();
    }

    return buffer.toByteArray();
}

From source file:de.scoopgmbh.copper.test.versioning.compatibility.TestJavaSerializer.java

private String serialize(final Object o) throws IOException {
    if (o == null)
        return null;
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    final ObjectOutputStream oos = new ObjectOutputStream(baos);

    oos.writeObject(o);/*from   ww  w . j  av a  2 s  .c om*/
    oos.close();
    baos.close();
    byte[] data = baos.toByteArray();
    final ByteArrayOutputStream baos2 = new ByteArrayOutputStream(1024);
    baos2.write(data, 0, 8);
    baos2.write(classNameReplacement.getBytes("UTF-8"));
    int offset = classNameReplacement.length() + 8;
    baos2.write(data, offset, data.length - offset);
    baos2.flush();
    baos2.close();
    data = baos2.toByteArray();
    boolean isCompressed = false;
    if (compress && compressThresholdSize <= data.length && data.length <= compressorMaxSize) {
        data = compressorTL.get().compress(data);
        isCompressed = true;
    }
    final String encoded = new Base64().encodeToString(data);
    final StringBuilder sb = new StringBuilder(encoded.length() + 4);
    sb.append(isCompressed ? 'C' : 'U').append(encoded);
    return sb.toString();
}

From source file:com.restqueue.framework.client.results.ResultsFactory.java

public String extractStringBody(InputStream bodyStream) {
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int nextChar;
    byte[] buffer = new byte[100];
    try {//w  w w .j  a v  a2 s .co m
        while ((nextChar = bodyStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, (char) nextChar);
        }
        byteArrayOutputStream.flush();
        byteArrayOutputStream.close();
    } catch (IOException e) {
        throw new ChannelClientException("Unknown exception getting content from the response:", e,
                ChannelClientException.ExceptionType.UNKNOWN);
    }
    return new String(byteArrayOutputStream.toByteArray());
}