Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

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

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

From source file:com.liferay.mobile.android.async.FileDownloadAsyncTest.java

@Test
public void download() throws Exception {
    BasicAuthentication basic = (BasicAuthentication) session.getAuthentication();

    DigestAuthentication digest = new DigestAuthentication(basic.getUsername(), basic.getPassword());

    session.setAuthentication(digest);/*from   w  w  w  . ja va2  s.  c  om*/

    String url = session.getServer() + "/webdav/guest/document_library/"
            + _file.getString(DLAppServiceTest.TITLE);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final CountDownLatch lock = new CountDownLatch(1);

    FileProgressCallback fileProgressCallback = new FileProgressCallback() {

        @Override
        public void onBytes(byte[] bytes) {
            try {
                baos.write(bytes);
            } catch (IOException ioe) {
                fail(ioe.getMessage());
            }
        }

        @Override
        public void onProgress(int totalBytes) {
            if (totalBytes == 5) {
                try {
                    baos.flush();
                } catch (IOException ioe) {
                    fail(ioe.getMessage());
                }
            }
        }

    };

    session.setCallback(new Callback() {

        @Override
        public void inBackground(Response response) {
            assertEquals(Status.OK, response.getStatusCode());
            lock.countDown();
        }

        @Override
        public void doFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    HttpUtil.download(session, url, fileProgressCallback);
    lock.await(500, TimeUnit.MILLISECONDS);
    assertEquals(5, baos.size());
}

From source file:org.apache.axis2.addressing.EndpointReference.java

/**
 * Write the EPR to the specified OutputStream.  Because of potential
 * OMElements/Attributes, we need to actually serialize the OM structures
 * (at least in some cases.)/*from   w  ww  .  ja  va  2s. c  om*/
 */
public synchronized void writeExternal(java.io.ObjectOutput o) throws IOException {
    SafeObjectOutputStream out = SafeObjectOutputStream.install(o);

    // revision ID
    out.writeInt(revisionID);

    // Correlation ID
    String logCorrelationIDString = getLogCorrelationIDString();

    // String object id
    out.writeObject(logCorrelationIDString);

    // Write out the content as xml
    out.writeUTF("start xml"); // write marker
    OMElement om = EndpointReferenceHelper.toOM(OMAbstractFactory.getOMFactory(), this,
            new QName("urn:axis2", "omepr", "ser"), AddressingConstants.Final.WSA_NAMESPACE);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        om.serialize(baos);
    } catch (Exception e) {
        IOException ioe = new IOException("Unable to serialize the EndpointReference with logCorrelationID ["
                + logCorrelationIDString + "]");
        ioe.initCause(e);

        if (log.isDebugEnabled()) {
            log.debug("writeObject(): Unable to serialize the EPR with logCorrelationID ["
                    + logCorrelationIDString + "]   original error [" + e.getClass().getName() + "]  message ["
                    + e.getMessage() + "]", e);
        }

        throw ioe;
    }

    out.writeInt(baos.size());
    out.write(baos.toByteArray());
    out.writeUTF("end xml"); // write marker

    if (log.isDebugEnabled()) {
        byte[] buffer = baos.toByteArray();
        String content = new String(buffer);

        log.debug("writeObject(): EPR logCorrelationID [" + logCorrelationIDString + "] "
                + "    EPR content size [" + baos.size() + "]" + "    EPR content [" + content + "]");
    }

}

From source file:com.penbase.dma.Dalyo.HTTPConnection.DmaHttpClient.java

/**
 * Manages post services//from  w  w  w . j  ava 2  s.  co m
 * @param parameters
 * @return
 */
public byte[] sendPost(String parameters) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    HttpClient httpClient = new DefaultHttpClient();
    // HttpPost httpPost = new HttpPost(Constant.SECUREDSERVER +
    // parameters);
    HttpPost httpPost = new HttpPost(Constant.SERVER + parameters);
    try {
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        int c;
        byte[] readByte = new byte[32 * 1024];
        while ((c = in.read(readByte)) > 0) {
            bos.write(readByte, 0, c);
        }
        in.close();
        httpPost.abort();
        httpClient.getConnectionManager().shutdown();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (bos.size() > 0) {
        byte[] data = bos.toByteArray();
        String codeStr = "";
        int i = 0;
        int length = data.length;
        while (i < length && data[i] != (int) '\n') {
            codeStr += (char) data[i];
            i++;
        }
        mErrorCode = Integer.valueOf(codeStr);
        if (mErrorCode != ErrorCode.OK) {
            return null;
        } else {
            int newLength = data.length - codeStr.length() - 1;
            byte[] result = new byte[newLength];
            System.arraycopy(data, codeStr.length() + 1, result, 0, result.length);
            return result;
        }
    } else {
        return null;
    }
}

From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java

/**
 * Write the pdf to the given response// w  ww. ja  va2  s  .  co m
 */
@SuppressWarnings("unchecked")
public static void generateOutputForIdentifiers(IdcardsTemplate card, String baseURL,
        HttpServletResponse response, List<String> identifiers, String password)
        throws ServletException, IOException {

    Properties props = new Properties();
    props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class");
    props.setProperty("class.resource.loader.description", "VelocityClasspathResourceLoader");
    props.setProperty("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
            "org.apache.velocity.runtime.log.NullLogSystem");

    // do the velocity magic
    Writer writer = new StringWriter();
    try {
        // Allow images to be served from Unix servers.
        try {
            java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();
        } catch (Throwable t) {
            log.warn(
                    "Unable to get graphics environment.  "
                            + "Make sure that -Djava.awt.headless=true is defined as a JAVA OPT during startup",
                    t);
        }
        Velocity.init(props);
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("locale", Context.getLocale());
        velocityContext.put("identifiers", identifiers);
        velocityContext.put("baseURL", baseURL);
        Velocity.evaluate(velocityContext, writer, PrintEmptyIdcardsServlet.class.getName(), card.getXml());
    } catch (ParseErrorException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (MethodInvocationException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (ResourceNotFoundException e) {
        throw new ServletException("Error parsing template: ", e);
    } catch (Exception e) {
        throw new ServletException("Error initializing Velocity engine", e);
    } finally {
        System.gc();
    }

    try {
        //Setup a buffer to obtain the content length
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        FopFactory fopFactory = FopFactory.newInstance();

        //fopFactory supports customization with a config file
        //Load the config file before creating the user agent.
        String userConfigFile = Context.getAdministrationService()
                .getGlobalProperty("idcards.fopConfigFilePath");
        if (userConfigFile != null) {
            try {
                fopFactory.setUserConfig(new java.io.File(userConfigFile));
                log.debug("Successfully loaded config file |" + userConfigFile + "|");
            } catch (Exception e) {
                log.error("Could not initialize fopFactory user config with file at " + userConfigFile
                        + ". Error message:" + e.getMessage());
            }
        }

        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        foUserAgent.getRendererOptions().put("encryption-params",
                new PDFEncryptionParams(password, null, true, false, false, false));

        //Setup FOP
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        //Setup Transformer
        Source xsltSrc = new StreamSource(new StringReader(card.getXslt()));
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(xsltSrc);

        //Make sure the XSL transformation's result is piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Setup input
        String xml = writer.toString();
        Source src = new StreamSource(new StringReader(xml));

        //Start the transformation and rendering process
        transformer.transform(src, res);

        //Prepare response
        String time = new SimpleDateFormat("yyyy-MM-dd_Hms").format(new Date());
        String filename = card.getName().replace(" ", "_") + "-" + time + ".pdf";
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        response.setContentType("application/pdf");
        response.setContentLength(out.size());

        //Send content to Browser
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(out.toByteArray());
        outputStream.flush();
    } catch (FOPException e) {
        throw new ServletException("Error generating report", e);
    } catch (TransformerConfigurationException e) {
        throw new ServletException("Error generating report", e);
    } catch (TransformerException e) {
        throw new ServletException("Error generating report", e);
    }
}

From source file:com.gameminers.mav.firstrun.TeachSphinxThread.java

@Override
public void run() {
    try {//  w w  w. ja  v a  2s . com
        File training = new File(Mav.configDir, "training-data");
        training.mkdirs();
        while (Mav.silentFrames < 30) {
            sleep(100);
        }
        Mav.listening = true;
        InputStream prompts = ClassLoader.getSystemResourceAsStream("resources/sphinx/train/arcticAll.prompts");
        List<String> arctic = IOUtils.readLines(prompts);
        IOUtils.closeQuietly(prompts);
        Mav.audioManager.playClip("listen1");
        byte[] buf = new byte[2048];
        int start = 0;
        int end = 21;
        AudioInputStream in = Mav.audioManager.getSource().getAudioInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (true) {
            for (int i = start; i < end; i++) {
                baos.reset();
                String prompt = arctic.get(i);
                RenderState.setText("\u00A7LRead this aloud:\n" + Fonts.wrapStringToFit(
                        prompt.substring(prompt.indexOf(':') + 1), Fonts.base[1], Display.getWidth()));
                File file = new File(training, prompt.substring(0, prompt.indexOf(':')) + ".wav");
                file.createNewFile();
                int read = 0;
                while (Mav.silentListenFrames > 0) {
                    read = Mav.audioManager.getSource().getAudioInputStream().read(buf);
                }
                baos.write(buf, 0, read);
                while (Mav.silentListenFrames < 60) {
                    in.read(buf);
                    if (read == -1) {
                        RenderState.setText(
                                "\u00A7LAn error occurred\nUnexpected end of stream\nPlease restart Mav");
                        RenderState.targetHue = 0;
                        return;
                    }
                    baos.write(buf, 0, read);
                }
                AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(baos.toByteArray()),
                        in.getFormat(), baos.size() / 2), AudioFileFormat.Type.WAVE, file);
                Mav.audioManager.playClip("notif2");
            }
            Mav.ttsInterface.say(Mav.phoneticUserName
                    + ", that should be enough for now. Do you want to keep training anyway?");
            RenderState.setText("\u00A7LOkay, " + Mav.userName
                    + "\nI think that should be\nenough. Do you want to\nkeep training anyway?\n\u00A7s(Say 'Yes' or 'No' out loud)");
            break;
            //start = end+1;
            //end += 20;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.openlmis.report.exporter.JasperReportExporter.java

/**
 *
 * @param jasperPrint//from   w w  w .j  a  v a  2s  .  c  o m
 * @param response
 * @param byteArrayOutputStream
 * @return
 */
public HttpServletResponse exportCsv(JasperPrint jasperPrint, String outputFileName,
        HttpServletResponse response, ByteArrayOutputStream byteArrayOutputStream) {

    JRCsvExporter exporter = new JRCsvExporter();

    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, byteArrayOutputStream);

    exporter.setParameter(JRXlsAbstractExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
    exporter.setParameter(JRXlsAbstractExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
    exporter.setParameter(JRXlsAbstractExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
    exporter.setParameter(JRXlsAbstractExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
    exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_GRAPHICS, Boolean.FALSE);

    try {
        exporter.exportReport();

    } catch (JRException e) {
        throw new RuntimeException(e);
    }

    String fileName = outputFileName.isEmpty() ? "openlmisReport.csv" : outputFileName + ".csv";
    response.setHeader(CONTENT_DISPOSITION, INLINE_FILENAME + fileName);

    response.setContentType(Constants.MEDIA_TYPE_EXCEL);
    response.setContentLength(byteArrayOutputStream.size());

    return response;
}

From source file:org.commoncrawl.util.CompressedURLFPList.java

public static void validateURLFPSerializationSingleSubDomain() {

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    Builder firstBuilder = new Builder(FLAG_ARCHIVE_SEGMENT_ID);

    TreeMultimap<Integer, URLFP> sourceMap = TreeMultimap.create();
    TreeMultimap<Integer, URLFP> destMap = TreeMultimap.create();
    ;/*from w  w  w .j  a va 2  s . c  o m*/

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "0", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "1", 1);

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "2", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "3", 1);

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "4", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "5", 1);

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "6", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "7", 1);

    // single top level domain with one sub domain an two urls
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_1 + "8", 1);
    insertURLFPItem(sourceMap, DOMAIN_1_SUBDOMAIN_1_URL_2 + "9", 1);

    addMapToBuilder(firstBuilder, sourceMap);

    try {
        // flush to byte stream ...
        firstBuilder.flush(byteStream);
        // now set up to read the stream
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray(), 0,
                byteStream.size());
        Reader reader = new Reader(inputStream);

        while (reader.hasNext()) {
            URLFP fp = reader.next();
            destMap.put(fp.getRootDomainHash(), fp);
        }
        reader.close();

        // dump both lists
        for (Integer rootDomain : sourceMap.keySet()) {
            for (URLFP urlfp : sourceMap.get(rootDomain)) {
                System.out.println("SourceFP Root:" + urlfp.getRootDomainHash() + " Domain:"
                        + urlfp.getDomainHash() + " URL:" + urlfp.getUrlHash());
            }
        }
        for (Integer rootDomain : destMap.keySet()) {
            for (URLFP urlfp : destMap.get(rootDomain)) {
                System.out.println("DestFP Root:" + urlfp.getRootDomainHash() + " Domain:"
                        + urlfp.getDomainHash() + " URL:" + urlfp.getUrlHash());
            }
        }

        Assert.assertTrue(sourceMap.equals(destMap));

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.apache.pig.piggybank.storage.GAMultiStorage.java

@Override
public void putNext(Tuple t) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream(BUF_SIZE);

    // this magical limit is related to memory size of reducer to prevent OOM while trying
    // to write data for big games
    int limit = 67108864 / 8;
    boolean partialSave = false;

    try {//from www  . jav  a2s  .c om
        DataBag bag = (DataBag) t.get(1);
        String gameId = String.valueOf(((Tuple) t.get(0)).get(0));

        if (this.statsOnly) {
            // produces debug memory/size stats in CSV format
            writer.write(gameId, new Text(
                    gameId + ";" + String.valueOf(bag.size()) + ";" + String.valueOf(t.getMemorySize())));
        } else {
            Iterator<Tuple> iterator = bag.iterator();
            while (iterator.hasNext()) {
                Tuple t1 = (Tuple) iterator.next();
                String line = t1.get(2).toString();

                // we are using multiple files together and collectors
                // do not append end line
                if (!line.endsWith("\n")) {
                    line += "\n";
                }
                baos.write(line.getBytes(Charset.forName("UTF-8")));

                // save partial result to prevent VM array limit exceptions
                if (baos.size() >= limit) {
                    writer.write(String.valueOf(gameId), RemoveLastByte(baos.toByteArray()));
                    baos.reset();
                    partialSave = true;
                } else {
                    partialSave = false;
                }
            }

            if (!partialSave) {
                writer.write(String.valueOf(gameId), RemoveLastByte(baos.toByteArray()));
            }
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.kuali.ole.module.purap.document.web.struts.PrintAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    //get parameters
    String poDocNumber = request.getParameter("poDocNumber");
    Integer vendorQuoteId = new Integer(request.getParameter("vendorQuoteId"));
    if (StringUtils.isEmpty(poDocNumber) || StringUtils.isEmpty(poDocNumber)) {
        throw new RuntimeException();
    }/* www  .jav  a  2s  .  co  m*/

    // doc service - get this doc
    PurchaseOrderDocument po = (PurchaseOrderDocument) SpringContext.getBean(DocumentService.class)
            .getByDocumentHeaderId(poDocNumber);
    DocumentAuthorizer documentAuthorizer = SpringContext.getBean(DocumentHelperService.class)
            .getDocumentAuthorizer(po);

    if (!documentAuthorizer.canInitiate(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER,
            GlobalVariables.getUserSession().getPerson())) {
        throw new DocumentInitiationException(OLEKeyConstants.AUTHORIZATION_ERROR_DOCUMENT, new String[] {
                GlobalVariables.getUserSession().getPerson().getPrincipalName(), "print", "Purchase Order" });
    }

    // get the vendor quote
    PurchaseOrderVendorQuote poVendorQuote = null;
    for (PurchaseOrderVendorQuote vendorQuote : po.getPurchaseOrderVendorQuotes()) {
        if (vendorQuote.getPurchaseOrderVendorQuoteIdentifier().equals(vendorQuoteId)) {
            poVendorQuote = vendorQuote;
            break;
        }
    }

    if (poVendorQuote == null) {
        throw new RuntimeException();
    }

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    poVendorQuote.setTransmitPrintDisplayed(false);
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_QUOTE_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // call the print service
        boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po,
                poVendorQuote, baosPDF);

        if (!success) {
            poVendorQuote.setTransmitPrintDisplayed(true);
            if (baosPDF != null) {
                baosPDF.reset();
            }
            return mapping.findForward(OLEConstants.MAPPING_BASIC);
        }
        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        // sbContentDispValue.append("inline");
        sbContentDispValue.append("attachment");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.apache.fineract.infrastructure.scheduledemail.service.EmailCampaignWritePlatformCommandHandlerImpl.java

/**
 * This generates the the report and converts it to a file by passing the parameters below
 * @param emailCampaign//from   www.j  a v a 2  s. c  om
 * @param emailAttachmentFileFormat
 * @param reportParams
 * @param reportName
 * @param errorLog
 * @return
 */
private File generateAttachments(final EmailCampaign emailCampaign,
        final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat,
        final Map<String, String> reportParams, final String reportName, final StringBuilder errorLog) {

    try {
        final ByteArrayOutputStream byteArrayOutputStream = this.readReportingService
                .generatePentahoReportAsOutputStream(reportName, emailAttachmentFileFormat.getValue(),
                        reportParams, null, emailCampaign.getApprovedBy(), errorLog);

        final String fileLocation = FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator + "";
        final String fileNameWithoutExtension = fileLocation + File.separator + reportName;

        // check if file directory exists, if not create directory
        if (!new File(fileLocation).isDirectory()) {
            new File(fileLocation).mkdirs();
        }

        if (byteArrayOutputStream.size() == 0) {
            errorLog.append("Pentaho report processing failed, empty output stream created");
        } else if (errorLog.length() == 0 && (byteArrayOutputStream.size() > 0)) {
            final String fileName = fileNameWithoutExtension + "." + emailAttachmentFileFormat.getValue();

            final File file = new File(fileName);
            final FileOutputStream outputStream = new FileOutputStream(file);
            byteArrayOutputStream.writeTo(outputStream);

            return file;
        }

    } catch (IOException | PlatformDataIntegrityException e) {
        errorLog.append(
                "The ReportMailingJobWritePlatformServiceImpl.executeReportMailingJobs threw an IOException "
                        + "exception: " + e.getMessage() + " ---------- ");
    }
    return null;
}