Example usage for java.io ByteArrayOutputStream writeTo

List of usage examples for java.io ByteArrayOutputStream writeTo

Introduction

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

Prototype

public synchronized void writeTo(OutputStream out) throws IOException 

Source Link

Document

Writes the complete contents of this ByteArrayOutputStream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count) .

Usage

From source file:org.springframework.flex.http.AmfHttpMessageConverter.java

private void writeActionMessage(ActionMessage message, HttpOutputMessage outputMessage, AmfTrace trace)
        throws IOException {
    AmfMessageSerializer serializer = new AmfMessageSerializer();
    ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
    serializer.setVersion(message.getVersion());
    serializer.initialize(new SerializationContext(), outBuffer, trace);

    try {/*  ww  w . j  a  v a 2 s  . c o m*/
        ActionContext context = new ActionContext();
        context.setVersion(message.getVersion());
        context.setResponseMessage(message);
        serializer.writeMessage(message);
        outBuffer.flush();
        outBuffer.close();
        outputMessage.getHeaders().setContentLength(outBuffer.size());
        outBuffer.writeTo(outputMessage.getBody());
    } catch (SerializationException se) {
        throw new HttpMessageNotWritableException("Could not write " + message + " as AMF message.", se);
    }
}

From source file:OutSimplePdf.java

public void makePdf(HttpServletRequest request, HttpServletResponse response, String methodGetPost)
        throws ServletException, IOException {
    try {/* w w w. java2 s .co  m*/

        String msg = "your message";

        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();
        document.add(new Paragraph(msg));
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("a paragraph"));
        document.close();

        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");

        response.setContentType("application/pdf");

        response.setContentLength(baos.size());

        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (Exception e2) {
        System.out.println("Error in " + getClass().getName() + "\n" + e2);
    }
}

From source file:com.esri.ArcGISController.java

@RequestMapping(value = "/rest/services/InfoUSA/MapServer/export", method = { RequestMethod.GET,
        RequestMethod.POST })//  w ww  . j  a  v a 2s.  co 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:org.kuali.ole.module.purap.document.web.struts.ElectronicInvoiceTestAction.java

/**
 * Generates Electronic Invoice xml file from a Purchase Order, for testing purpose only.
 *//*w w w .  ja  v a 2 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 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.kuali.kfs.module.purap.document.web.struts.ElectronicInvoiceTestAction.java

/**
 * Generates Electronic Invoice xml file from a Purchase Order, for testing purpose only.     
 *///from   ww w  .  ja va  2  s . c om
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.jactr.tools.async.message.ast.BaseASTMessage.java

private void writeObject(java.io.ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();/*  w  w w .j  a v a2  s.  c o m*/
    if (_ast != null) {
        out.writeBoolean(true);
        out.writeBoolean(_compress);

        if (_compress) {
            /*
             * go to a GZIPOutputStream
             */
            ByteArrayOutputStream baos = _localBAOS.get();
            if (baos == null) {
                baos = new ByteArrayOutputStream();
                _localBAOS.set(baos);
            }
            baos.reset();

            DataOutputStream zip = new DataOutputStream(new GZIPOutputStream(baos));
            Serializer.write(_ast, zip);
            zip.flush();
            zip.close();
            // byte[] bytes = baos.toByteArray();

            if (LOGGER.isDebugEnabled())
                LOGGER.debug(String.format("Writing %d compressed bytes", baos.size()));

            out.writeInt(baos.size());
            baos.writeTo(out);

            // if (LOGGER.isDebugEnabled())
            // LOGGER.debug("Compressed AST to "+bytes.length);
            // out.writeInt(bytes.length);
            // out.write(bytes);
        } else
            Serializer.write(_ast, out);
    } else
        out.writeBoolean(false);
}

From source file:Transcriber.java

public String process(ByteArrayOutputStream wav) throws Exception {
    // Create connection
    URL url = new URL(uri);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "audio/l16; rate=16000");
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36");

    //connection.setUseCaches(false);
    connection.setDoOutput(true);/*from  ww w .ja v a  2  s. c  o  m*/

    // Write wav to request body
    OutputStream out = connection.getOutputStream();
    //InputStream in = new FileInputStream("hello.wav");
    wav.writeTo(out);
    out.close();

    //Get Response
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = null;

    String ignore = in.readLine(); // skip first empty results line
    //System.out.println("ignore = " + ignore);

    StringBuilder responseData = new StringBuilder();
    while ((line = in.readLine()) != null) {
        responseData.append(line);
    }

    String result = responseData.toString();

    if (!result.isEmpty()) {
        JSONObject obj = new JSONObject(result);
        String text = obj.getJSONArray("result").getJSONObject(0).getJSONArray("alternative").getJSONObject(0)
                .getString("transcript");
        return text;
    }

    return "";
}

From source file:org.archive.wayback.replay.swf.SWFReplayRenderer.java

@Override
public void renderResource(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        WaybackRequest wbRequest, CaptureSearchResult result, Resource httpHeadersResource,
        Resource payloadResource, ResultURIConverter uriConverter, CaptureSearchResults results)
        throws ServletException, IOException, WaybackException {

    try {//  w  ww  .j a v a 2  s .  co m

        // copy HTTP response code:
        HttpHeaderOperation.copyHTTPMessageHeader(httpHeadersResource, httpResponse);

        // load and process original headers:
        Map<String, String> headers = HttpHeaderOperation.processHeaders(httpHeadersResource, result,
                uriConverter, httpHeaderProcessor);

        // The URL of the resource, for resolving embedded relative URLs:
        URL url = null;
        try {
            url = new URL(result.getOriginalUrl());
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            throw new IOException(e1.getMessage());
        }
        // the date to associate with the embedded, rewritten URLs:
        String datespec = result.getCaptureTimestamp();
        SWFUrlRewriter rw = new SWFUrlRewriter(uriConverter, url, datespec);

        // OK, try to read the input movie:
        Movie movie = getRobustMovie(RobustMovieDecoder.DECODE_RULE_NULLS);

        try {
            movie.decodeFromStream(payloadResource);
        } catch (DataFormatException e1) {
            throw new BadContentException(e1.getLocalizedMessage());
        }
        Movie outMovie = new Movie(movie);

        List<MovieTag> inTags = movie.getObjects();
        ArrayList<MovieTag> outTags = new ArrayList<MovieTag>();
        for (MovieTag tag : inTags) {
            outTags.add(rewriteTag(rw, tag));
        }
        outMovie.setObjects(outTags);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            outMovie.encodeToStream(baos);
        } catch (DataFormatException e) {
            throw new BadContentException(e.getLocalizedMessage());
        }

        // put the new corrected length:
        headers.put(HttpHeaderOperation.HTTP_LENGTH_HEADER, String.valueOf(baos.size()));

        // send the new headers:
        HttpHeaderOperation.sendHeaders(headers, httpResponse);

        // and copy the stored up byte-stream:
        baos.writeTo(httpResponse.getOutputStream());
    } catch (Exception e) {

        // Redirect to identity if there are any issues
        throw new BetterRequestException(UrlOperations.computeIdentityUrl(wbRequest));
    }
}

From source file:hydrograph.ui.engine.util.ConverterUtil.java

/**
 * Store file into local file system.//from www  . j  a v  a 2 s .co  m
 *
 * @param graph
 * @param externalOutputFile
 * @param out
 * @throws CoreException the core exception
 * @throws JAXBException the JAXB exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void storeFileIntoLocalFileSystem(Graph graph, boolean validate, IFileStore externalOutputFile,
        ByteArrayOutputStream out) throws CoreException, JAXBException, IOException {

    File externalFile = externalOutputFile.toLocalFile(0, null);
    OutputStream outputStream = new FileOutputStream(externalFile.getAbsolutePath().replace(".job", ".xml"));

    JAXBContext jaxbContext = JAXBContext.newInstance(graph.getClass());
    Marshaller marshaller = jaxbContext.createMarshaller();
    out = new ByteArrayOutputStream();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(graph, out);
    out = ComponentXpath.INSTANCE.addParameters(out);
    out.writeTo(outputStream);
    outputStream.close();
}

From source file:com.gst.infrastructure.reportmailingjob.service.ReportMailingJobWritePlatformServiceImpl.java

/** 
 * send report file to email recipients/*from w ww  .jav a  2  s . c o m*/
 * 
 * @param reportMailingJob
 * @param fileName
 * @param byteArrayOutputStream
 * @param errorLog
 */
private void sendReportFileToEmailRecipients(final ReportMailingJob reportMailingJob, final String fileName,
        final ByteArrayOutputStream byteArrayOutputStream, final StringBuilder errorLog) {
    final Set<String> emailRecipients = this.reportMailingJobValidator
            .validateEmailRecipients(reportMailingJob.getEmailRecipients());

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

        for (String emailRecipient : emailRecipients) {
            final ReportMailingJobEmailData reportMailingJobEmailData = new ReportMailingJobEmailData(
                    emailRecipient, reportMailingJob.getEmailMessage(), reportMailingJob.getEmailSubject(),
                    file);

            this.reportMailingJobEmailService.sendEmailWithAttachment(reportMailingJobEmailData);
        }

        outputStream.close();

    } catch (IOException e) {
        errorLog.append(
                "The ReportMailingJobWritePlatformServiceImpl.sendReportFileToEmailRecipients method threw an IOException "
                        + "exception: " + e + " ---------- ");
    }
}