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.esri.ArcGISController.java

@RequestMapping(value = "/rest/services/InfoUSA/MapServer/export", method = { RequestMethod.GET,
        RequestMethod.POST })/*from   www  .j  a  v  a2  s  . c  o  m*/
public void doExport(@RequestParam("bbox") final String bbox,
        @RequestParam(value = "size", required = false) final String size,
        @RequestParam(value = "layerDefs", required = false) final String layerDefs,
        @RequestParam(value = "transparent", required = false) final String transparent,
        final HttpServletResponse response) throws IOException {
    double xmin = -1.0, ymin = -1.0, xmax = 1.0, ymax = 1.0;
    if (bbox != null && bbox.length() > 0) {
        final String[] tokens = m_patternComma.split(bbox);
        if (tokens.length == 4) {
            xmin = Double.parseDouble(tokens[0]);
            ymin = Double.parseDouble(tokens[1]);
            xmax = Double.parseDouble(tokens[2]);
            ymax = Double.parseDouble(tokens[3]);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "bbox is not in the form xmin,ymin,xmax,ymax");
            return;
        }
    } else {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "bbox is null or empty");
        return;
    }

    final double xdel = xmax - xmin;
    final double ydel = ymax - ymin;

    int imageWidth = 400;
    int imageHeight = 400;
    if (size != null && size.length() > 0) {
        final String[] tokens = m_patternComma.split(size);
        if (tokens.length == 2) {
            imageWidth = Integer.parseInt(tokens[0], 10);
            imageHeight = Integer.parseInt(tokens[1], 10);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "size is not in the form width,height");
            return;
        }
    }
    String where = null;
    double lo = Double.NaN;
    double hi = Double.NaN;
    int[] ramp = null;
    if (layerDefs != null) {
        final String[] tokens = m_patternSemiColon.split(layerDefs);
        for (final String token : tokens) {
            final String[] keyval = m_patternEqual.split(token.substring(2));
            if (keyval.length == 2) {
                final String key = keyval[0];
                final String val = keyval[1];
                if ("lo".equalsIgnoreCase(key)) {
                    lo = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val);
                } else if ("hi".equalsIgnoreCase(key)) {
                    hi = "NaN".equalsIgnoreCase(val) ? Double.NaN : Double.parseDouble(val);
                } else if ("ramp".equalsIgnoreCase(key)) {
                    ramp = parseRamp(val);
                } else if ("where".equalsIgnoreCase(key)) {
                    where = val;
                }
            }
        }
    }
    if (ramp == null) {
        ramp = new int[] { 0xFFFFFF, 0x000000 };
    }

    final Range range = new Range();
    final Map<Long, Double> map = query(where, xmin, ymin, xmax, ymax, range);
    if (!Double.isNaN(lo)) {
        range.lo = lo;
    }
    if (!Double.isNaN(hi)) {
        range.hi = hi;
    }
    range.dd = range.hi - range.lo;

    final int typeIntRgb = "true".equalsIgnoreCase(transparent) ? BufferedImage.TYPE_INT_ARGB
            : BufferedImage.TYPE_INT_RGB;
    BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight, typeIntRgb);
    final Graphics2D graphics = bufferedImage.createGraphics();
    try {
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        graphics.setBackground(new Color(0, 0, 0, 0));

        drawCells(graphics, imageWidth, imageHeight, xmin, ymin, xdel, ydel, range, ramp, map.entrySet());
    } finally {
        graphics.dispose();
    }

    // bufferedImage = m_op.filter(bufferedImage, null);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream(10 * 1024);
    ImageIO.write(bufferedImage, "PNG", baos);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("image/png");
    response.setContentLength(baos.size());
    baos.writeTo(response.getOutputStream());
    response.getOutputStream().flush();
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

private boolean handleSerialEventWithoutTimeout(SerialPortEvent event, InputStream in,
        ByteArrayOutputStream sink, byte[] magicBytes, int readLength) {
    int sinkSize = sink.size();
    boolean append = sinkSize > 0;
    byte[] buf = new byte[Math.min(readLength, 1024)];
    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
    }//from   ww w.j av a  2s.  c  o m
    try {
        int len = -1;
        final int max = Math.min(in.available(), buf.length);
        eventLog.trace("Attempting to read {} bytes from serial port", max);
        while (max > 0 && (len = in.read(buf, 0, max)) > 0) {
            sink.write(buf, 0, len);
            sinkSize += len;

            if (append) {
                // if we've collected at least desiredSize bytes, we're done
                if (sinkSize >= readLength) {
                    if (eventLog.isDebugEnabled()) {
                        eventLog.debug("Got desired {}  bytes of data: {}", readLength,
                                asciiDebugValue(sink.toByteArray()));
                    }
                    return true;
                }
                eventLog.debug("Looking for {} more bytes of data", (readLength - sinkSize));
                return false;
            } else {
                eventLog.trace("Looking for {} magic bytes 0x{}", magicBytes.length,
                        Hex.encodeHexString(magicBytes));
            }

            // look for magic in the buffer
            int magicIdx = 0;
            byte[] sinkBuf = sink.toByteArray();
            boolean found = false;
            for (; magicIdx < (sinkBuf.length - magicBytes.length + 1); magicIdx++) {
                found = true;
                for (int j = 0; j < magicBytes.length; j++) {
                    if (sinkBuf[magicIdx + j] != magicBytes[j]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    break;
                }
            }

            if (found) {
                // magic found!
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Found magic bytes " + asciiDebugValue(magicBytes) + " at buffer index "
                            + magicIdx);
                }

                // skip over magic bytes
                magicIdx += magicBytes.length;

                int count = readLength;
                count = Math.min(readLength, sinkBuf.length - magicIdx);
                sink.reset();
                sink.write(sinkBuf, magicIdx, count);
                sinkSize = count;
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
                }
                if (sinkSize >= readLength) {
                    // we got all the data here... we're done
                    return true;
                }
                eventLog.trace("Need {} more bytes of data", (readLength - sinkSize));
                append = true;
            } else if (sinkBuf.length > magicBytes.length) {
                // haven't found the magic yet, and the sink is larger than magic size, so 
                // trim sink down to just magic size
                sink.reset();
                sink.write(sinkBuf, sinkBuf.length - magicBytes.length - 1, magicBytes.length);
                sinkSize = magicBytes.length;
            }
        }
    } catch (IOException e) {
        log.error("Error reading from serial port: {}", e.getMessage());
        throw new RuntimeException(e);
    }

    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Need {} more bytes of data, buffer: {}", (readLength - sinkSize),
                asciiDebugValue(sink.toByteArray()));
    }
    return false;
}

From source file:org.kie.guvnor.services.backend.file.upload.AbstractFileServlet.java

protected void processAttachmentDownload(final String path, final HttpServletResponse response)
        throws IOException {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();

    try {/*  w w  w .ja v a  2  s .  c o  m*/
        final Path sourcePath = convertPath(path);
        IOUtils.copy(doLoad(sourcePath), output);
        // String fileName = m2RepoService.getJarName(path);
        final String fileName = sourcePath.getFileName();

        response.setContentType("application/x-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
        response.setContentLength(output.size());
        response.getOutputStream().write(output.toByteArray());
        response.getOutputStream().flush();

    } catch (Exception e) {
        throw new org.kie.commons.java.nio.IOException(e.getMessage());
    }
}

From source file:Highcharts.ExportController.java

@RequestMapping(value = "/test/{fileName}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> staticImagesDownload(@PathVariable("fileName") String fileName)
            throws IOException {

        String imageLoc = servletContext.getRealPath("WEB-INF/benchmark");
        FileInputStream fis = new FileInputStream(imageLoc + "/" + fileName + ".png");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {/*  ww w .j a  va 2  s  .  com*/
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
        } catch (IOException ex) {
            // nothing here
        } finally {
            fis.close();
        }

        HttpHeaders responseHeaders = httpHeaderAttachment("TEST-" + fileName, MimeType.PNG, bos.size());
        return new ResponseEntity<byte[]>(bos.toByteArray(), responseHeaders, HttpStatus.OK);
    }

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

/**
 * Generates Electronic Invoice xml file from a Purchase Order, for testing purpose only.
 *///  www .  ja  v  a  2s  . co m
public ActionForward generate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    checkAuthorization(form, "");

    ElectronicInvoiceTestForm testForm = (ElectronicInvoiceTestForm) form;
    String poDocNumber = testForm.getPoDocNumber();
    LOG.info("Generating Electronic Invoice XML file for Purchase Order Document " + poDocNumber);
    PurchaseOrderService poService = SpringContext.getBean(PurchaseOrderService.class);
    PurchaseOrderDocument po = null;

    if (StringUtils.isBlank(poDocNumber)) {
        GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_DOCUMENT_NUMBER,
                PurapKeyConstants.ERROR_ELECTRONIC_INVOICE_GENERATION_PURCHASE_ORDER_NUMBER_EMPTY,
                new String[] { poDocNumber });
        return mapping.findForward(RiceConstants.MAPPING_BASIC);
    }
    if (!getDocumentService().documentExists(poDocNumber)) {
        GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_DOCUMENT_NUMBER,
                PurapKeyConstants.ERROR_ELECTRONIC_INVOICE_GENERATION_PURCHASE_ORDER_DOES_NOT_EXIST,
                poDocNumber);
        return mapping.findForward(RiceConstants.MAPPING_BASIC);
    }

    try {
        po = poService.getPurchaseOrderByDocumentNumber(poDocNumber);
    } catch (Exception e) {
        throw e;
    }

    response.setHeader("Cache-Control", "max-age=30");
    response.setContentType("application/xml");
    StringBuffer sbContentDispValue = new StringBuffer();
    String useJavascript = request.getParameter("useJavascript");
    if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
        sbContentDispValue.append("attachment");
    } else {
        sbContentDispValue.append("inline");
    }
    StringBuffer sbFilename = new StringBuffer();
    sbFilename.append("PO_");
    sbFilename.append(poDocNumber);
    sbFilename.append(".xml");
    sbContentDispValue.append("; filename=");
    sbContentDispValue.append(sbFilename);
    response.setHeader("Content-disposition", sbContentDispValue.toString());

    // lookup the PO and fill in the XML with valid data
    if (po != null) {
        String duns = "";
        if (po.getVendorDetail() != null) {
            duns = StringUtils.defaultString(po.getVendorDetail().getVendorDunsNumber());
        }

        DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
        String currDate = ElectronicInvoiceUtils.getDateDisplayText(dateTimeService.getCurrentDate()); // getting date in ole format
        String vendorNumber = po.getVendorDetail().getVendorNumber();

        String eInvoiceFile = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "\n<!-- ******Testing tool generated XML****** Version 1.2." + "\n\n  Generated On "
                + currDate + " for PO " + po.getPurapDocumentIdentifier() + " (Doc# " + poDocNumber
                + ") -->\n\n" + "<!-- All the cXML attributes are junk values -->\n"
                + "<cXML payloadID=\"200807260401062080.964@eai002\"\n"
                + "    timestamp=\"2008-07-26T04:01:06-08:00\"\n" + "    version=\"1.2.014\" xml:lang=\"en\" \n"
                + "    xmlns=\"http://www.kuali.org/ole/purap/electronicInvoice\" \n"
                + "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" + "  <Header>\n"
                + "      <From>\n" + "          <Credential domain=\"DUNS\">\n" + "              <Identity>"
                + duns + "</Identity> <!-- DUNS number from PO Vendor " + vendorNumber + "-->\n"
                + "          </Credential>\n" + "      </From>\n" + "      <To>\n"
                + "          <Credential domain=\"NetworkId\">\n" + "              <Identity>" + "IU"
                + "</Identity> <!-- Hardcoded --> \n" + "          </Credential>\n" + "      </To>\n"
                + "      <Sender>\n" + "          <Credential domain=\"DUNS\">\n" + "              <Identity>"
                + duns + "</Identity> <!-- DUNS number from PO Vendor " + vendorNumber + "-->\n"
                + "          </Credential>\n" + "          <UserAgent/>\n" + "      </Sender>\n"
                + "  </Header>\n" + "  <Request deploymentMode=\"production\">\n"
                + "      <InvoiceDetailRequest>\n" + "          <InvoiceDetailRequestHeader\n"
                + "              invoiceDate=\"" + currDate + "\" invoiceID=\"" + RandomUtils.nextInt()
                + "\" operation=\"new\" purpose=\"standard\"> <!-- invoiceID=Random unique Id, invoiceDate=Curr date -->\n"
                + "              <InvoiceDetailHeaderIndicator/>\n"
                + "              <InvoiceDetailLineIndicator/>\n" + "              <InvoicePartner>\n"
                + getContactXMLChunk("billTo", po) + "              </InvoicePartner>\n"
                + "              <InvoicePartner>\n" + "                  <Contact addressID=\""
                + RandomUtils.nextInt() + "\" role=\"remitTo\"> <!-- Vendor address -->\n"
                + "                      <Name xml:lang=\"en\">\n" + "                          "
                + po.getVendorName() + "\n" + "                      </Name>\n"
                + "                      <PostalAddress>\n" + "                          <Street>"
                + StringUtils.defaultString(po.getVendorLine1Address()) + "</Street>\n"
                + "                          <Street>" + StringUtils.defaultString(po.getVendorLine2Address())
                + "</Street>\n" + "                          <City>"
                + StringUtils.defaultString(po.getVendorCityName()) + "</City>\n"
                + "                          <State>" + StringUtils.defaultString(po.getVendorStateCode())
                + "</State>\n" + "                          <PostalCode>"
                + StringUtils.defaultString(po.getVendorPostalCode()) + "</PostalCode>\n"
                + "                          <Country isoCountryCode=\""
                + StringUtils.defaultString(po.getVendorCountryCode()) + "\">\n"
                + "                              " + StringUtils.defaultString(po.getVendorCountry().getName())
                + "\n" + "                          </Country>\n" + "                      </PostalAddress>\n"
                + "                  </Contact>\n" + "              </InvoicePartner>\n"
                + getDeliveryAddressXMLChunk("shipTo", po) + getPaymentTermXML(po)
                + "          </InvoiceDetailRequestHeader>\n" + "          <InvoiceDetailOrder>\n"
                + "              <InvoiceDetailOrderInfo>\n" + "                  <OrderReference\n"
                + "                      orderDate=\""
                + ElectronicInvoiceUtils.getDateDisplayText(dateTimeService.getCurrentDate()) + "\" orderID=\""
                + po.getPurapDocumentIdentifier() + "\"> <!--orderDate=Curr date,orderID=PO#-->\n"
                + "                      <DocumentReference payloadID=\"NA\" /> <!--HardCoded-->\n"
                + "                  </OrderReference>\n" + "              </InvoiceDetailOrderInfo>\n"
                + "              <!-- No junk values in Items-->\n";

        for (int i = 0; i < po.getItems().size(); i++) {
            List items = po.getItems();
            PurchaseOrderItem item = (PurchaseOrderItem) items.get(i);
            if (!item.getItemType().isAdditionalChargeIndicator()) {
                eInvoiceFile = eInvoiceFile + getPOItemXMLChunk(item);
            }
        }

        KualiDecimal totalDollarAmt = po.getTotalDollarAmount() == null ? KualiDecimal.ZERO
                : po.getTotalDollarAmount();
        eInvoiceFile = eInvoiceFile +

                "          </InvoiceDetailOrder>\n" + "          <InvoiceDetailSummary>\n"
                + "              <SubtotalAmount>\n" + "                  <Money currency=\"USD\">"
                + po.getTotalPreTaxDollarAmount() + "</Money>\n" + "              </SubtotalAmount>\n"
                + "              <Tax>\n" + "                  <Money currency=\"USD\">"
                + po.getTotalTaxAmount() + "</Money>\n"
                + "                  <Description xml:lang=\"en\">Total Tax</Description>\n"
                + "              </Tax>\n" + "              <SpecialHandlingAmount>\n"
                + "                  <Money currency=\"USD\">0.00</Money>\n"
                + "              </SpecialHandlingAmount>\n" + "              <ShippingAmount>\n"
                + "                  <Money currency=\"USD\">0.00</Money>\n"
                + "              </ShippingAmount>\n" + "              <GrossAmount>\n"
                + "                  <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n"
                + "              </GrossAmount>\n" + "              <InvoiceDetailDiscount>\n"
                + "                  <Money currency=\"USD\">0.00</Money>\n"
                + "                  </InvoiceDetailDiscount>\n" + "              <NetAmount>\n"
                + "                  <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n"
                + "              </NetAmount>\n" + "              <DepositAmount>\n"
                + "                  <Money currency=\"USD\">0.00</Money>\n"
                + "              </DepositAmount>\n" + "              <DueAmount>\n"
                + "                  <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n"
                + "              </DueAmount>\n" + "          </InvoiceDetailSummary>\n"
                + "      </InvoiceDetailRequest>\n" + "  </Request>\n" + "</cXML>";

        ServletOutputStream sos;
        sos = response.getOutputStream();
        ByteArrayOutputStream baOutStream = new ByteArrayOutputStream();
        StringBufferInputStream inStream = new StringBufferInputStream(eInvoiceFile);
        convert(baOutStream, inStream);
        response.setContentLength(baOutStream.size());
        baOutStream.writeTo(sos);
        sos.flush();
    }

    return mapping.findForward(OLEConstants.MAPPING_BASIC);
}

From source file:org.nuxeo.ecm.core.opencmis.impl.CmisSuiteSession2.java

private void doTestContentStream(HttpUriRequest request) throws Exception {
    assumeTrue(isAtomPub || isBrowser);//from ww w . j a  va 2 s. c om

    String contentMD5Hex = DigestUtils.md5Hex(FILE1_CONTENT);
    String contentMD5Base64 = NuxeoPropertyData.transcodeHexToBase64(contentMD5Hex);

    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        request.setHeader("Authorization", BASIC_AUTH);
        boolean isHeadRequest = request instanceof HttpHead;
        request.setHeader("Want-Digest", isHeadRequest ? "contentMD5" : "md5");
        harness.deployContrib("org.nuxeo.ecm.core.opencmis.tests.tests",
                "OSGI-INF/download-listener-contrib.xml");
        DownloadListener.clearMessages();
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Header lengthHeader = response.getFirstHeader("Content-Length");
            assertNotNull(lengthHeader);
            byte[] expectedBytes = FILE1_CONTENT.getBytes("UTF-8");
            int expectedLength = expectedBytes.length;
            assertEquals(String.valueOf(expectedLength), lengthHeader.getValue());
            List<String> downloadMessages = DownloadListener.getMessages();
            if (isHeadRequest) {
                Header contentMD5Header = response.getFirstHeader("Content-MD5");
                assertEquals(contentMD5Base64, contentMD5Header.getValue());
                assertNull(response.getEntity());
                assertEquals(0, downloadMessages.size());
            } else {
                Header digestHeader = response.getFirstHeader("Digest");
                assertEquals("MD5=" + contentMD5Base64, digestHeader.getValue());
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                try (InputStream in = response.getEntity().getContent()) {
                    IOUtils.copy(in, out);
                }
                assertEquals(expectedLength, out.size());
                assertTrue(Arrays.equals(expectedBytes, out.toByteArray()));
                assertEquals(Arrays.asList("download:comment=testfile.txt,downloadReason=cmis"),
                        downloadMessages);
            }
        }
    } finally {
        harness.undeployContrib("org.nuxeo.ecm.core.opencmis.tests.tests",
                "OSGI-INF/download-listener-contrib.xml");
    }
}

From source file:org.kuali.kfs.module.purap.document.web.struts.ElectronicInvoiceTestAction.java

/**
 * Generates Electronic Invoice xml file from a Purchase Order, for testing purpose only.     
 *///www . j  a v a2  s. c o  m
public ActionForward generate(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    checkAuthorization(form, "");

    ElectronicInvoiceTestForm testForm = (ElectronicInvoiceTestForm) form;
    String poDocNumber = testForm.getPoDocNumber();
    LOG.info("Generating Electronic Invoice XML file for Purchase Order Document " + poDocNumber);
    PurchaseOrderService poService = SpringContext.getBean(PurchaseOrderService.class);
    PurchaseOrderDocument po = null;

    if (StringUtils.isBlank(poDocNumber)) {
        GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_DOCUMENT_NUMBER,
                PurapKeyConstants.ERROR_ELECTRONIC_INVOICE_GENERATION_PURCHASE_ORDER_NUMBER_EMPTY,
                new String[] { poDocNumber });
        return mapping.findForward(RiceConstants.MAPPING_BASIC);
    }
    if (!getDocumentService().documentExists(poDocNumber)) {
        GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_DOCUMENT_NUMBER,
                PurapKeyConstants.ERROR_ELECTRONIC_INVOICE_GENERATION_PURCHASE_ORDER_DOES_NOT_EXIST,
                poDocNumber);
        return mapping.findForward(RiceConstants.MAPPING_BASIC);
    }

    try {
        po = poService.getPurchaseOrderByDocumentNumber(poDocNumber);
    } catch (Exception e) {
        throw e;
    }

    response.setHeader("Cache-Control", "max-age=30");
    response.setContentType("application/xml");
    StringBuffer sbContentDispValue = new StringBuffer();
    String useJavascript = request.getParameter("useJavascript");
    if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) {
        sbContentDispValue.append("attachment");
    } else {
        sbContentDispValue.append("inline");
    }
    StringBuffer sbFilename = new StringBuffer();
    sbFilename.append("PO_");
    sbFilename.append(poDocNumber);
    sbFilename.append(".xml");
    sbContentDispValue.append("; filename=");
    sbContentDispValue.append(sbFilename);
    response.setHeader("Content-disposition", sbContentDispValue.toString());

    // lookup the PO and fill in the XML with valid data
    if (po != null) {
        String duns = "";
        if (po.getVendorDetail() != null) {
            duns = StringUtils.defaultString(po.getVendorDetail().getVendorDunsNumber());
        }

        DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
        String currDate = ElectronicInvoiceUtils.getDateDisplayText(dateTimeService.getCurrentDate()); // getting date in kfs format
        String vendorNumber = po.getVendorDetail().getVendorNumber();

        String eInvoiceFile = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + "\n<!-- ******Testing tool generated XML****** Version 1.2." + "\n\n  Generated On "
                + currDate + " for PO " + po.getPurapDocumentIdentifier() + " (Doc# " + poDocNumber
                + ") -->\n\n" + "<!-- All the cXML attributes are junk values -->\n"
                + "<cXML payloadID=\"200807260401062080.964@eai002\"\n"
                + "    timestamp=\"2008-07-26T04:01:06-08:00\"\n" + "    version=\"1.2.014\" xml:lang=\"en\" \n"
                + "    xmlns=\"http://www.kuali.org/kfs/purap/electronicInvoice\" \n"
                + "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" + "  <Header>\n"
                + "      <From>\n" + "          <Credential domain=\"DUNS\">\n" + "              <Identity>"
                + duns + "</Identity> <!-- DUNS number from PO Vendor " + vendorNumber + "-->\n"
                + "          </Credential>\n" + "      </From>\n" + "      <To>\n"
                + "          <Credential domain=\"NetworkId\">\n" + "              <Identity>" + "IU"
                + "</Identity> <!-- Hardcoded --> \n" + "          </Credential>\n" + "      </To>\n"
                + "      <Sender>\n" + "          <Credential domain=\"DUNS\">\n" + "              <Identity>"
                + duns + "</Identity> <!-- DUNS number from PO Vendor " + vendorNumber + "-->\n"
                + "          </Credential>\n" + "          <UserAgent/>\n" + "      </Sender>\n"
                + "  </Header>\n" + "  <Request deploymentMode=\"production\">\n"
                + "      <InvoiceDetailRequest>\n" + "          <InvoiceDetailRequestHeader\n"
                + "              invoiceDate=\"" + currDate + "\" invoiceID=\"" + RandomUtils.nextInt()
                + "\" operation=\"new\" purpose=\"standard\"> <!-- invoiceID=Random unique Id, invoiceDate=Curr date -->\n"
                + "              <InvoiceDetailHeaderIndicator/>\n"
                + "              <InvoiceDetailLineIndicator/>\n" + "              <InvoicePartner>\n"
                + getContactXMLChunk("billTo", po) + "              </InvoicePartner>\n"
                + "              <InvoicePartner>\n" + "                  <Contact addressID=\""
                + RandomUtils.nextInt() + "\" role=\"remitTo\"> <!-- Vendor address -->\n"
                + "                      <Name xml:lang=\"en\">\n" + "                          "
                + po.getVendorName() + "\n" + "                      </Name>\n"
                + "                      <PostalAddress>\n" + "                          <Street>"
                + StringUtils.defaultString(po.getVendorLine1Address()) + "</Street>\n"
                + "                          <Street>" + StringUtils.defaultString(po.getVendorLine2Address())
                + "</Street>\n" + "                          <City>"
                + StringUtils.defaultString(po.getVendorCityName()) + "</City>\n"
                + "                          <State>" + StringUtils.defaultString(po.getVendorStateCode())
                + "</State>\n" + "                          <PostalCode>"
                + StringUtils.defaultString(po.getVendorPostalCode()) + "</PostalCode>\n"
                + "                          <Country isoCountryCode=\""
                + StringUtils.defaultString(po.getVendorCountryCode()) + "\">\n"
                + "                              " + StringUtils.defaultString(po.getVendorCountry().getName())
                + "\n" + "                          </Country>\n" + "                      </PostalAddress>\n"
                + "                  </Contact>\n" + "              </InvoicePartner>\n"
                + getDeliveryAddressXMLChunk("shipTo", po) + getPaymentTermXML(po)
                + "          </InvoiceDetailRequestHeader>\n" + "          <InvoiceDetailOrder>\n"
                + "              <InvoiceDetailOrderInfo>\n" + "                  <OrderReference\n"
                + "                      orderDate=\""
                + ElectronicInvoiceUtils.getDateDisplayText(dateTimeService.getCurrentDate()) + "\" orderID=\""
                + po.getPurapDocumentIdentifier() + "\"> <!--orderDate=Curr date,orderID=PO#-->\n"
                + "                      <DocumentReference payloadID=\"NA\" /> <!--HardCoded-->\n"
                + "                  </OrderReference>\n" + "              </InvoiceDetailOrderInfo>\n"
                + "              <!-- No junk values in Items-->\n";

        for (int i = 0; i < po.getItems().size(); i++) {
            List items = po.getItems();
            PurchaseOrderItem item = (PurchaseOrderItem) items.get(i);
            if (!item.getItemType().isAdditionalChargeIndicator()) {
                eInvoiceFile = eInvoiceFile + getPOItemXMLChunk(item);
            }
        }

        KualiDecimal totalDollarAmt = po.getTotalDollarAmount() == null ? KualiDecimal.ZERO
                : po.getTotalDollarAmount();
        eInvoiceFile = eInvoiceFile +

                "          </InvoiceDetailOrder>\n" + "          <InvoiceDetailSummary>\n"
                + "              <SubtotalAmount>\n" + "                  <Money currency=\"USD\">"
                + po.getTotalPreTaxDollarAmount() + "</Money>\n" + "              </SubtotalAmount>\n"
                + "              <Tax>\n" + "                  <Money currency=\"USD\">"
                + po.getTotalTaxAmount() + "</Money>\n"
                + "                  <Description xml:lang=\"en\">Total Tax</Description>\n"
                + "              </Tax>\n" + "              <SpecialHandlingAmount>\n"
                + "                  <Money currency=\"USD\">0.00</Money>\n"
                + "              </SpecialHandlingAmount>\n" + "              <ShippingAmount>\n"
                + "                  <Money currency=\"USD\">0.00</Money>\n"
                + "              </ShippingAmount>\n" + "              <GrossAmount>\n"
                + "                  <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n"
                + "              </GrossAmount>\n" + "              <InvoiceDetailDiscount>\n"
                + "                  <Money currency=\"USD\">0.00</Money>\n"
                + "                  </InvoiceDetailDiscount>\n" + "              <NetAmount>\n"
                + "                  <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n"
                + "              </NetAmount>\n" + "              <DepositAmount>\n"
                + "                  <Money currency=\"USD\">0.00</Money>\n"
                + "              </DepositAmount>\n" + "              <DueAmount>\n"
                + "                  <Money currency=\"USD\">" + totalDollarAmt + "</Money>\n"
                + "              </DueAmount>\n" + "          </InvoiceDetailSummary>\n"
                + "      </InvoiceDetailRequest>\n" + "  </Request>\n" + "</cXML>";

        ServletOutputStream sos;
        sos = response.getOutputStream();
        ByteArrayOutputStream baOutStream = new ByteArrayOutputStream();
        StringBufferInputStream inStream = new StringBufferInputStream(eInvoiceFile);
        convert(baOutStream, inStream);
        response.setContentLength(baOutStream.size());
        baOutStream.writeTo(sos);
        sos.flush();
    }

    return mapping.findForward(KFSConstants.MAPPING_BASIC);
}

From source file:org.dataconservancy.dcs.integration.bootstrap.MetadataFormatRegistryBootstrap.java

public void bootstrapFormats() throws InterruptedException, IOException {

    if (isDisabled) {
        log.info("MetadataFormatRegistryBootstrap is disabled; not executing bootstrapping process.");
        return;/*  w ww  .j a  va 2s.c o m*/
    }

    long bootStart = System.currentTimeMillis();
    log.info("Bootstrapping the DCS... ");
    MetadataSchemeMapper schemeMapper = new MetadataSchemeMapper();

    MetadataFormatMapper mapper = new MetadataFormatMapper(schemeMapper);

    Iterator<RegistryEntry<DcsMetadataFormat>> iter = memoryRegistry.iterator();

    List<DepositInfo> depositStatus = new ArrayList<DepositInfo>();

    while (iter.hasNext()) {
        RegistryEntry<DcsMetadataFormat> registryEntry = iter.next();

        try {
            if (queryService.lookup(registryEntry.getId()) != null) {
                // The archive already has the entry
                log.debug("Not bootstrapping registry entry {}: it is already in the archive.",
                        registryEntry.getId());
                continue;
            }
        } catch (QueryServiceException e) {
            log.warn("Error depositing DCP (skipping it): " + e.getMessage(), e);
            continue;
        }

        final Dcp entryDcp = mapper.to(registryEntry, null);

        for (DcsFile dcsFile : entryDcp.getFiles()) {
            final Resource r;
            if (dcsFile.getSource().startsWith(FILE_PREFIX)) {
                r = new FileSystemResource(new URL(dcsFile.getSource()).getPath());
            } else if (dcsFile.getSource().startsWith(CLASSPATH_PREFIX)) {
                r = new ClassPathResource(dcsFile.getSource().substring(CLASSPATH_PREFIX.length()));
            } else {
                throw new RuntimeException(
                        "Unknown file source " + dcsFile.getSource() + " for file name " + dcsFile.getName());
            }

            if (!r.exists()) {
                throw new RuntimeException("Resource " + r.getFilename() + " doesn't exist.");
            }

            Map<String, String> metadata = new HashMap<String, String>();
            HttpHeaderUtil.addDigest("SHA-1", calculateChecksum("SHA-1", r), metadata);
            metadata.put(HttpHeaderUtil.CONTENT_TYPE, APPLICATION_XML);
            metadata.put(HttpHeaderUtil.CONTENT_DISPOSITION, "filename=" + r.getFilename());
            metadata.put(HttpHeaderUtil.CONTENT_LENGTH, Long.toString(r.contentLength()));
            DepositInfo info = fileManager.deposit(r.getInputStream(), APPLICATION_XML, null, metadata);
            dcsFile.setSource(info.getMetadata().get(SRC_HEADER));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        modelBuilder.buildSip(entryDcp, baos);
        try {
            Map<String, String> metadata = new HashMap<String, String>();
            metadata.put(HttpHeaderUtil.CONTENT_TYPE, APPLICATION_XML);
            metadata.put(HttpHeaderUtil.CONTENT_LENGTH, Integer.toString(baos.size()));
            final ByteArrayInputStream byteIn = new ByteArrayInputStream(baos.toByteArray());
            depositStatus.add(manager.deposit(byteIn, APPLICATION_XML, DCP_PACKAGING, metadata));
        } catch (PackageException e) {
            log.warn("Error depositing DCP: " + e.getMessage(), e);
            continue;
        }
    }

    Iterator<DepositInfo> statusItr = depositStatus.iterator();

    while (statusItr.hasNext()) {
        DepositInfo info = statusItr.next();
        try {
            if (!checkStatusUntilTimeout(info, 600000)) {
                File f;
                FileOutputStream fos = null;
                try {
                    f = File.createTempFile("bootstrap-", ".xml");
                    fos = new FileOutputStream(f);
                    IOUtils.copy(info.getDepositStatus().getInputStream(), fos);
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
                log.warn(
                        "Error bootstrapping the DCS; error depositing package {}: see {} for more information.",
                        info.getDepositID(), f.getAbsolutePath());
            }
        } catch (Exception e) {
            log.warn("Error bootstrapping the DCS; error depositing package {}: {}",
                    new Object[] { info.getDepositID(), e.getMessage(), e });
        }
    }

    log.info("Bootstrap complete in {} ms", System.currentTimeMillis() - bootStart);
}

From source file:com.microsoft.tfs.core.httpclient.methods.multipart.Part.java

/**
 * Return the full length of all the data. If you override this method make
 * sure to override #send(OutputStream) as well
 *
 * @return long The length.//from  w w  w .j a v a  2s .c om
 * @throws IOException
 *         If an IO problem occurs
 */
public long length() throws IOException {
    LOG.trace("enter length()");
    if (lengthOfData() < 0) {
        return -1;
    }
    final ByteArrayOutputStream overhead = new ByteArrayOutputStream();
    sendStart(overhead);
    sendDispositionHeader(overhead);
    sendContentTypeHeader(overhead);
    sendTransferEncodingHeader(overhead);
    sendEndOfHeader(overhead);
    sendEnd(overhead);
    return overhead.size() + lengthOfData();
}

From source file:com.juick.android.Utils.java

public static BINResponse streamToByteArray(InputStream is, Notification progressNotification) {
    try {/* w ww  .j  av a 2  s  .co  m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        long l = System.currentTimeMillis();
        byte[] buf = new byte[1024];
        while (true) {
            int len = is.read(buf);
            if (len <= 0)
                break;
            baos.write(buf, 0, len);
            if (System.currentTimeMillis() - l > 100) {
                l = System.currentTimeMillis();
                if (progressNotification instanceof DownloadProgressNotification)
                    ((DownloadProgressNotification) progressNotification).notifyDownloadProgress(baos.size());
            }
        }
        return new BINResponse(null, false, baos.toByteArray());
    } catch (Exception e) {
        if (progressNotification instanceof DownloadErrorNotification)
            ((DownloadErrorNotification) progressNotification).notifyDownloadError(e.toString());
        Log.e("streamReader", e.toString());
        return new BINResponse(e.toString(), true, null);
    }
}