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:com.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the images with input device ids from cache and stores it in zip
 * output stream.//from   w  ww .  j a  v  a 2s  .c  om
 *
 * @param capturedImageIds
 *            Ids of captures images
 * @param deviceMacs
 *            Mac address of selected devices
 * @param response
 *            http servelet response
 * @param session
 *            http session.
 */
public void addImagesToZipFile(String[] capturedImageIds, String[] deviceMacs, HttpServletResponse response,
        HttpSession session) {

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + "Images_" + getCurrentDateAndTime() + ".zip\"");
    response.setContentType("application/zip");

    ServletOutputStream serveletOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        serveletOutputStream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        BufferedImage image;
        ZipEntry zipEntry;
        ByteArrayOutputStream imgByteArrayOutputStream = null;

        for (int i = 0; i < deviceMacs.length; i++) {
            // Check whether id of captured image is null or not
            if (!StringUtils.isEmpty(capturedImageIds[i])) {
                image = imgCache.getItem(capturedImageIds[i]);
                zipEntry = new ZipEntry(deviceMacs[i].toUpperCase() + "." + IMG_FORMAT);
                zipOutputStream.putNextEntry(zipEntry);
                imgByteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_FORMAT, imgByteArrayOutputStream);
                imgByteArrayOutputStream.flush();
                zipOutputStream.write(imgByteArrayOutputStream.toByteArray());
                zipOutputStream.closeEntry();
            }
        }

        zipOutputStream.flush();
        zipOutputStream.close();
        serveletOutputStream.write(byteArrayOutputStream.toByteArray());
    } catch (IOException ioe) {
        LOGGER.error("Image zipping failed !!!", ioe);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

protected byte[] readBytes(InputStream is, long size) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(size > 0 ? (int) size : 1000);
    byte[] bytes = new byte[1000];
    int ln = 0;/*from   w  w  w. j  a  v  a2s.  c o m*/
    try {
        while ((ln = is.read(bytes)) > 0) {
            baos.write(bytes, 0, ln);
        }
        baos.flush();
    } finally {
        try {
            baos.close();
        } catch (IOException e) {
        }
    }
    return baos.toByteArray();
}

From source file:eionet.meta.exports.ods.Ods.java

/**
 * Reads file content into string./* w w w.  j  av  a 2 s .c  om*/
 *
 * @param file
 *            file to be read
 * @return file content
 * @throws java.lang.Exception
 *             if operation fails
 */
private String fileToString(File file) throws Exception {

    String result = null;

    int i = 0;
    byte[] buf = new byte[BUF_SIZE];
    FileInputStream in = null;
    ByteArrayOutputStream out = null;

    try {
        in = new FileInputStream(file);
        out = new ByteArrayOutputStream();
        while ((i = in.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, i);
        }

        out.flush();
        result = out.toString();
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }

    return result;
}

From source file:it.govpay.web.rs.dars.anagrafica.intermediari.IntermediariHandler.java

@Override
public Intermediario creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    Intermediario entry = null;//from   ww w. j  a v a  2s  .  c  o  m
    String principalId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".principal.id");
    String tipoSslId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + "." + CONNETTORE_PDD + ".tipoSsl.id");
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di scrittura
        this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita);

        JsonConfig jsonConfig = new JsonConfig();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(is, baos);

        baos.flush();
        baos.close();

        JSONObject jsonObjectIntermediario = JSONObject.fromObject(baos.toString());

        String principal = jsonObjectIntermediario.getString(principalId);
        jsonObjectIntermediario.remove(principalId);

        String tipoSsl = jsonObjectIntermediario.containsKey(tipoSslId)
                ? jsonObjectIntermediario.getString(tipoSslId)
                : null;
        if (tipoSsl != null) {
            jsonObjectIntermediario.remove(tipoSslId);
        }

        jsonConfig.setRootClass(Intermediario.class);
        entry = (Intermediario) JSONObject.toBean(jsonObjectIntermediario, jsonConfig);

        //jsonObjectIntermediario = JSONObject.fromObject( baos.toString() );  
        jsonConfig.setRootClass(Connettore.class);
        Connettore c = (Connettore) JSONObject.toBean(jsonObjectIntermediario, jsonConfig);

        if (StringUtils.isNotEmpty(tipoSsl)) {
            c.setTipoSsl(EnumSslType.valueOf(tipoSsl));
        }

        c.setPrincipal(principal);
        entry.setConnettorePdd(c);

        this.log.info("Esecuzione " + methodName + " completata.");
        return entry;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **//*from  w  ww  . j ava 2 s. com*/

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}

From source file:it.govpay.web.rs.dars.anagrafica.iban.IbanHandler.java

@Override
public IbanAccredito creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    IbanAccredito entry = null;//  w  w w.j  a v a 2s  .co  m
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di scrittura
        this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita);

        JsonConfig jsonConfig = new JsonConfig();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(is, baos);

        baos.flush();
        baos.close();

        JSONObject jsonObjectIBAN = JSONObject.fromObject(baos.toString());
        jsonConfig.setRootClass(IbanAccredito.class);
        entry = (IbanAccredito) JSONObject.toBean(jsonObjectIBAN, jsonConfig);

        this.log.info("Esecuzione " + methodName + " completata.");
        return entry;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:graphene.rest.ws.impl.ExportGraphRSImpl.java

@Override
public Response exportGraphAsJSON(@QueryParam("fileName") final String fileName,
        @QueryParam("fileExt") final String fileExt, @QueryParam("username") final String username,
        @QueryParam("timeStamp") final String timeStamp, // this is the
        // client
        // timestamp in
        // millisecs as a string
        final String graphJSONdata) {

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(outputStream);

    // DEBUG/*w  w w. j  a  v  a2  s. c  o  m*/
    logger.debug("exportGraphAsJSON: fileName = " + fileName + ", fileExt = " + fileExt
            + ", graphJSONdata length = " + graphJSONdata.length());

    try {
        writer.write(graphJSONdata);
    } catch (final IOException e) {
        logger.error("exportGraphAsJSON: Exception writing JSON");
        logger.error(e.getMessage());
    }

    try {
        writer.close();
        outputStream.flush();
        outputStream.close();
    } catch (final java.io.IOException ioe) {
        logger.error("exportGraphAsJSON: I/O Exception when attempting to close output. Details "
                + ioe.getMessage());
    }

    // Create the file on the Web Server
    File file = null;
    ServletContext servletContext = null;

    try {
        servletContext = globals.getServletContext();
    } catch (final Exception se) {
        logger.error("exportGraphAsJSON: ServletContext is null.");
    }

    String path = null;
    final String serverfileName = "GraphExport" + "_" + username + "_" + timeStamp + "_" + fileName + fileExt;

    if (servletContext != null) {
        path = servletContext.getRealPath("/");
    }
    // TODO - get the path from the servlerContext or the request param
    // TODO the file should be placed under the webserver's dir
    if (path == null) {
        // TODO - handle case if the Server is Linux instead of Windows
        path = "C:/Windows/Temp"; // Temp hack
    }

    // DEBUG
    logger.debug("exportGraphAsJSON: file path = " + path);

    try {
        file = new File(path, serverfileName);

        // file.mkdirs();
        final FileOutputStream fout = new FileOutputStream(file);
        fout.write(outputStream.toByteArray());
        fout.close();
        String finalPath = file.toURI().toString();
        finalPath = finalPath.replace("file:/", ""); // remove leading

        // DEBUG
        // logger.debug("exportGraphAsJSON: file toURI = " + finalPath);

        final ResponseBuilder response = Response.ok(finalPath);
        response.type("text/plain");
        final Response responseOut = response.build();
        return responseOut;
    } catch (final Exception fe) {
        logger.error(
                "exportGraphAsJSON: Failed to create file for export. Details: " + fe.getLocalizedMessage());
    }
    return null;

}

From source file:business.services.ExcerptListService.java

/**
 * Write the excerpt list as a file.//from w w  w . j  a v  a  2  s.  c o m
 * @param list - the list
 * @param selectedOnly - writes only selected excerpts if true; all excerpts otherwise.
 * @return the resource holding selected excerpts or all (depends on the value of {@value selected}
 * in CSV format.
 */
public HttpEntity<InputStreamResource> writeExcerptList(ExcerptList list, boolean selectedOnly) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out, EXCERPT_LIST_CHARACTER_ENCODING);
        CSVWriter csvwriter = new CSVWriter(writer, ';', '"');
        csvwriter.writeNext(list.getCsvColumnNames());
        for (ExcerptEntry entry : list.getEntries()) {
            if (!selectedOnly || entry.isSelected()) {
                csvwriter.writeNext(entry.getCsvValues());
            }
        }
        csvwriter.flush();
        writer.flush();
        out.flush();
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        csvwriter.close();
        writer.close();
        out.close();
        InputStreamResource resource = new InputStreamResource(in);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("text/csv;charset=" + EXCERPT_LIST_CHARACTER_ENCODING));
        String filename = (selectedOnly ? "selection" : "excerpts") + "_" + list.getProcessInstanceId()
                + ".csv";
        headers.set("Content-Disposition", "attachment; filename=" + filename);
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        log.info("Returning reponse.");
        return response;
    } catch (IOException e) {
        log.error(e.getStackTrace());
        log.error(e.getMessage());
        throw new ExcerptListDownloadError();
    }
}

From source file:com.jrestless.aws.gateway.handler.GatewayRequestObjectHandlerIntTest.java

private byte[] toBytes(InputStream is) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;/*  w ww. j a v a  2 s.c o m*/
    byte[] data = new byte[1024];
    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    buffer.flush();
    return buffer.toByteArray();
}

From source file:com.agilejava.maven.docbkx.GeneratorMojo.java

/**
 * Returns a {@link Collection} of all parameter names defined in the
 * stylesheet or in one of the stylesheets imported or included in the
 * stylesheet./*  w w  w. jav  a2 s .  c o m*/
 *
 * @param url
 *            The location of the stylesheet to analyze.
 * @return A {@link Collection} of all parameter names found in the
 *         stylesheet pinpointed by the <code>url</code> argument.
 *
 * @throws MojoExecutionException
 *             If the operation fails to detect parameter names.
 */
private Collection getParameterNames(String url) throws MojoExecutionException {
    ByteArrayOutputStream out = null;

    try {
        Transformer transformer = createParamListTransformer();
        Source source = new StreamSource(url);
        out = new ByteArrayOutputStream();

        Result result = new StreamResult(out);
        transformer.transform(source, result);
        out.flush();
        if (out.size() != 0) {
            // at least one param has been found, because the split with return an empty string if there is no data
            String[] paramNames = new String(out.toByteArray()).split("\n");
            return new HashSet(Arrays.asList(paramNames));
        } else {
            // else no param found
            return new HashSet();
        }
    } catch (IOException ioe) {
        // Impossible, but let's satisfy PMD and FindBugs
        getLog().warn("Failed to flush ByteArrayOutputStream.");
    } catch (TransformerConfigurationException tce) {
        throw new MojoExecutionException("Failed to create Transformer for retrieving parameter names", tce);
    } catch (TransformerException te) {
        throw new MojoExecutionException("Failed to apply Transformer for retrieving parameter names.", te);
    } finally {
        IOUtils.closeQuietly(out);
    }

    return Collections.EMPTY_SET;
}