Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

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

Usage

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

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

From source file:com.zacwolf.commons.email.Email.java

private void prepareImgs(final org.jsoup.nodes.Document doc, final Multipart htmlmultipart) {
    final Map<String, EmailAttachment> attachments = getAttachments();
    final org.jsoup.select.Elements imgs = doc.getElementsByTag("img");
    for (org.jsoup.nodes.Element img : imgs) {
        final String src = img.attr("src");
        final String cid = !src.startsWith("cid:") ? null : src.substring(4);
        try {/*from   w w  w.j ava  2  s. co m*/
            EmailAttachment attachment;
            ByteArrayOutputStream baos;
            if (cid != null) {
                attachment = attachments.get(cid);
                img.attr("alt", attachment.getDescription());
                if (!img.attr("style").contains("display:"))//all inline images need the display:block; added for GMail compatability
                    img.attr("style", img.attr("style") + (!img.attr("style").endsWith(";") ? ";" : "")
                            + "display:block;");
                if (cid.toLowerCase().contains("_banner")
                        && doc.select("#banner").attr("style").contains("-radius")) {
                    BufferedImage image = makeRoundedBanner(
                            ImageIO.read(new ByteArrayInputStream(attachment.data)), 20);
                    doc.select("#contenttable").attr("style",
                            "width:" + image.getWidth() + "px;" + doc.select("#contenttable").attr("style"));
                    baos = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(image, EmailAttachment.CONTENT_MIMETYPES.get(attachment.contenttype),
                                baos);
                    } finally {
                        baos.flush();
                    }
                    attachment = new EmailAttachment(attachment.filename, attachment.contenttype,
                            baos.toByteArray(), cid, "Rounded banner image");
                    if (htmlmultipart == null)
                        dataurlEncode(img, attachment);
                    if (doc.select("#footer").size() == 1
                            && doc.select("#footer").first().attr("style").contains("-radius")) {
                        Color bgcolor = Color.WHITE;
                        Color border = null;
                        String newstyle = "";
                        String[] styles = doc.select("#footer").first().attr("style").split(";");
                        for (String style : styles) {
                            if (style.startsWith("border"))
                                border = getColorFromStyle(style, null);
                            else if (style.startsWith("background-color:"))
                                bgcolor = getColorFromStyle(style, Color.WHITE);
                            else
                                newstyle += style + ";";
                        }
                        baos = new ByteArrayOutputStream();
                        try {
                            ImageIO.write(makeRoundedFooter(image.getWidth(), 20, bgcolor, border), "png",
                                    baos);
                        } finally {
                            baos.flush();
                        }
                        doc.select("#footer").first().parent()
                                .html("<td style=\"margin:0px;padding:0px;\" valign=\"top\" style=\"" + newstyle
                                        + "\"><img id=\"footer\" alt=\"rounded footer image\" src=\"cid:"
                                        + getREFID() + "_rounded_footer\" style=\"display:block;\" /></td>");
                    }
                    if (htmlmultipart == null)
                        dataurlEncode(doc.select("#footer").first(),
                                new EmailAttachment("footer.png", "image/png", baos.toByteArray(),
                                        getREFID() + "_rounded_footer", "Rounded footer image"));
                    else
                        htmlmultipart.addBodyPart(new EmailAttachment("footer.png", "image/png",
                                baos.toByteArray(), getREFID() + "_rounded_footer", "Rounded footer image"));
                } else if (htmlmultipart == null) {
                    dataurlEncode(img, attachment);
                }
                if (htmlmultipart != null)
                    htmlmultipart.addBodyPart(attachment);
            }
        } catch (Exception e) {
            throw new NullPointerException(
                    "Problem with embedding images into content.\nContact the content owner.\n\nERROR:" + e);
        }
    }
}

From source file:it.cnr.icar.eric.server.common.Utility.java

/**
 * Removes the <?xml version="1.0"?> decalaration from XML bytes
 *    @return the bytes of the XML document
 *///from  www  .j  a  v a 2 s.c  om
public byte[] removeXMLDeclaration(byte[] bytes) throws IOException {
    java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
    int declEndIndex = 0;

    // Get the end index of declaration
    if (bytes[0] == '<') {
        boolean hasDecl = false;

        for (int i = 1; i < bytes.length; i++) {
            if (bytes[1] == ' ') {
                //Skip spaces after '<'
                declEndIndex++;
            } else if (bytes[i] == '?') {
                // It has declaration
                hasDecl = true;
            }

            if (hasDecl) {
                if (bytes[i] != '>') {
                    declEndIndex++;
                } else {
                    declEndIndex++;

                    break;
                }
            }
        }
    }

    // skip all spaces after the xml declaration
    for (int i = declEndIndex; i < bytes.length; i++) {
        declEndIndex++;

        if (bytes[i] != ' ') {
            break;
        }
    }

    // System.err.println(declEndIndex + "!!!!!");
    bos.write(bytes, declEndIndex, bytes.length - declEndIndex);
    bos.flush();
    bos.close();

    //System.err.println(new String(bos.toByteArray()));
    return bos.toByteArray();
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Enwrapps the data into a signed MIME message structure and returns it*/
private void enwrappInMessageAndSign(AS2Message message, Part contentPart, Partner sender, Partner receiver)
        throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeMessage messagePart = new MimeMessage(Session.getInstance(System.getProperties(), null));
    //sign message if this is requested
    if (info.getSignType() != AS2Message.SIGNATURE_NONE) {
        MimeMultipart signedPart = this.signContentPart(contentPart, sender, receiver);
        if (this.logger != null) {
            String signAlias = this.signatureCertManager.getAliasByFingerprint(sender.getSignFingerprintSHA1());
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.signed",
                            new Object[] { info.getMessageId(), signAlias,
                                    this.rbMessage.getResourceString("signature." + receiver.getSignType()) }),
                    info);/*from   w ww .j ava  2 s  .com*/
        }
        messagePart.setContent(signedPart);
        messagePart.saveChanges();
    } else {
        //unsigned message
        if (contentPart instanceof MimeBodyPart) {
            MimeMultipart unsignedPart = new MimeMultipart();
            unsignedPart.addBodyPart((MimeBodyPart) contentPart);
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.notsigned", new Object[] { info.getMessageId() }),
                        info);
            }
            messagePart.setContent(unsignedPart);
        } else if (contentPart instanceof MimeMultipart) {
            messagePart.setContent((MimeMultipart) contentPart);
        } else if (contentPart instanceof MimeMessage) {
            messagePart = (MimeMessage) contentPart;
        } else {
            throw new IllegalArgumentException("enwrappInMessageAndSign: Unable to set the content of a "
                    + contentPart.getClass().getName());
        }
        messagePart.saveChanges();
    }
    //store signed or unsigned data
    ByteArrayOutputStream signedOut = new ByteArrayOutputStream();
    //normally the content type header is folded (which is correct but some products are not able to parse this properly)
    //Now take the content-type, unfold it and write it
    Enumeration headerLines = messagePart.getMatchingHeaderLines(new String[] { "Content-Type" });
    LineOutputStream los = new LineOutputStream(signedOut);
    while (headerLines.hasMoreElements()) {
        //requires java mail API >= 1.4
        String nextHeaderLine = MimeUtility.unfold((String) headerLines.nextElement());
        //write the line only if the as2 message is encrypted. If the as2 message is unencrypted this header is added later
        //in the class MessageHttpUploader
        if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) {
            los.writeln(nextHeaderLine);
        }
        //store the content line in the as2 message object, this value is required later in MessageHttpUploader
        message.setContentType(nextHeaderLine.substring(nextHeaderLine.indexOf(':') + 1));
    }
    messagePart.writeTo(signedOut, new String[] { "Message-ID", "Mime-Version", "Content-Type" });
    signedOut.flush();
    signedOut.close();
    message.setDecryptedRawData(signedOut.toByteArray());
}

From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java

/**
 * //www.  ja va  2s . c  o  m
 * @param post {@link HttpPost}
 * @return String posted body if computable
 * @throws IOException if sending the data fails due to I/O
 */
@Override
protected String sendPostData(HttpPost post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    FileContentServer contentServer = FileContentServer.getServer();
    HTTPFileArg staticFiles[] = getHTTPFiles();
    HTTPFileArg dynFiles[] = testElement.getDynamicFiles();
    VariableFileArg variableFiles[] = testElement.getVariableFiles();
    String[] attachmentsNumber = null;
    boolean thresholdCheck = testElement.getRecordType() >= testElement.getThreshold();

    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;
    boolean hasContent = false;

    // If a content encoding is specified, we use that as the
    // encoding of any parameter values
    Charset charset = null;
    if (haveContentEncoding) {
        charset = Charset.forName(contentEncoding);
    }

    // Write the request to our own stream
    MultipartEntity multiPart = new MultipartEntity(
            getDoBrowserCompatibleMultipart() ? HttpMultipartMode.BROWSER_COMPATIBLE : HttpMultipartMode.STRICT,
            null, charset);
    // Create the parts
    // Add any parameters
    PropertyIterator args = getArguments().iterator();
    while (args.hasNext()) {
        HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
        String parameterName = arg.getName();
        if (arg.isSkippable(parameterName)) {
            continue;
        }
        FormBodyPart formPart;
        StringBody stringBody = new StringBody(arg.getValue(), charset);
        formPart = new FormBodyPart(arg.getName(), stringBody);
        multiPart.addPart(formPart);
        hasContent = true;
    }
    /*
     * set parameters controlled by threshold
     */
    if (!testElement.getArgumentThreshold() || thresholdCheck) {
        args = testElement.getOwnArguments().iterator();
        while (args.hasNext()) {
            HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            FormBodyPart formPart;
            StringBody stringBody = new StringBody(arg.getValue(), charset);
            formPart = new FormBodyPart(arg.getName(), stringBody);
            multiPart.addPart(formPart);
            hasContent = true;
        }
    }

    // Add all files
    // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
    ViewableByteBody[] viewableByteBodies = new ViewableByteBody[variableFiles.length + staticFiles.length
            + dynFiles.length];

    int i = 0;

    //Variable Files
    if (!testElement.getVariableThreshold() || thresholdCheck)
        for (int j = 0; j < variableFiles.length; j++, i++) {
            VariableFileArg file = variableFiles[j];

            viewableByteBodies[i] = new ViewableByteBody(file.getContent().getBytes(), file.getMimeType(),
                    file.getName());
            multiPart.addPart(file.getParamName(), viewableByteBodies[i]);
            hasContent = true;
        }

    //Static Files
    if (!testElement.getStaticThreshold() || thresholdCheck)
        for (i = 0; i < staticFiles.length; i++) {
            HTTPFileArg file = staticFiles[i];

            viewableByteBodies[i] = new ViewableByteBody(contentServer.getFileContent(file.getPath()),
                    file.getMimeType(), new File(file.getPath()).getName());
            multiPart.addPart(file.getParamName(), viewableByteBodies[i]);
            hasContent = true;
        }

    //Dynamic Files
    if (!testElement.getDynamicThreshold() || thresholdCheck) {

        attachmentsNumber = testElement.getAttachmentNumbers().split(",");

        for (int j = 0; j < attachmentsNumber.length && !attachmentsNumber[j].isEmpty(); i++, j++) {
            int fileNum = Integer.parseInt(attachmentsNumber[j]) - 1;
            if (fileNum >= dynFiles.length) {
                log.warn("trying to send file out of dynamic files range (" + Integer.toString(fileNum + 1)
                        + " of " + Integer.toString(dynFiles.length) + ")\nfile was skipped");
                i--;
                continue;
            }
            HTTPFileArg file = dynFiles[fileNum];

            viewableByteBodies[i] = new ViewableByteBody(contentServer.getFileContent(file.getPath()),
                    file.getMimeType(), new File(file.getPath()).getName());
            multiPart.addPart(file.getParamName(), viewableByteBodies[i]);
            hasContent = true;
        }
    }

    post.setEntity(multiPart);
    if (!hasContent)
        log.warn("POST has no content!");

    if (multiPart.isRepeatable()) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        //stop the content from appearing in sampler result
        if (!testElement.getLogFiles()) {
            for (ViewableByteBody fileBody : viewableByteBodies) {
                if (fileBody != null)
                    fileBody.hideFileData = true;
                else
                    break;
            }
        }

        multiPart.writeTo(bos);

        //Set it back, in order for the content to be sent
        if (!testElement.getLogFiles()) {
            for (ViewableByteBody fileBody : viewableByteBodies) {
                if (fileBody != null)
                    fileBody.hideFileData = false;
                else
                    break;
            }
        }
        bos.flush();
        // We get the posted bytes using the encoding used to create it
        postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                : contentEncoding));
        bos.close();
    } else {
        postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
    }

    return postedBody.toString();
}

From source file:com.aspose.showcase.qrcodegen.web.api.controller.QRCodeManagementController.java

/**
 * generateQRCode - Main API to generate QR Code
 * /*w  w  w .  j  a  v  a 2s. c  o  m*/
 * @throws Exception
 * 
 * 
 */
@RequestMapping(value = "generate", method = RequestMethod.GET, produces = { MediaType.IMAGE_JPEG_VALUE,
        MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_GIF_VALUE, MEDIATYPE_IMAGE_TIFF_VALUE,
        MEDIATYPE_IMAGE_BMP_VALUE })
@ApiOperation(value = "Generate QR Code.")
public ResponseEntity<byte[]> generateQRCode(
        @ApiParam(value = "data", name = "data", required = true) @RequestParam("data") String data,
        @ApiParam(value = "A user-chosen password that can be used with password-based encryption (PBE) Algo PBEWITHMD5AND128BITAES-CBC-OPENSSL)", name = "passKey", required = false) @RequestParam(required = false, value = "passKey") String passKey,
        @ApiParam(value = "ForeColor e.g #000000 (Black - RGB(hex))", name = "foreColor", required = false) @RequestParam(required = false, value = "foreColor") String foreColor,
        @ApiParam(value = "BackgroundColor e.g #FFFFFF (White - RGB(hex))", name = "bgColor", required = false) @RequestParam(required = false, value = "bgColor") String bgColor,
        @ApiParam(value = "L|M|Q|H - Reed-Solomon error correctionCode Level(from low to high) default=Low", name = "ecc", required = false) @RequestParam(required = false, value = "ecc") String ecc,
        @ApiParam(value = "Image Size e.g #150x150", name = "size", required = false) @RequestParam(required = false, value = "size") String size,
        @ApiParam(value = "jpeg|tiff|gif|png|bmp - default=png", name = "format", required = false) @RequestParam(required = false, value = "format") String format,
        @ApiParam(value = "true|false default=false", name = "download", required = false) @RequestParam(required = false, value = "download") boolean download,
        @ApiIgnore @Value("#{request.getHeader('" + ACCEPT_HEADER + "')}") String acceptHeaderValue)
        throws Exception {

    Assert.isTrue(StringUtils.isNotEmpty(data), "Please provide valid data param.");

    LOGGER.debug("Accept Header::" + acceptHeaderValue);

    HttpHeaders responseHeaders = new HttpHeaders();

    if (!(StringUtils.isBlank(passKey))) {
        builder.setCodeText(StringEncryptor.encrypt(data, passKey));
    } else {
        builder.setCodeText(data);
    }

    builder.setImageQuality(ImageQualityMode.Default);
    builder.setSymbologyType(Symbology.QR);
    builder.setCodeLocation(CodeLocation.None);

    builder.setForeColor(getColorValue(foreColor, "#000000"));

    builder.setBackColor(getColorValue(bgColor, "#FFFFFF"));

    builder.setQRErrorLevel(getErrorCorrectCode(ecc, QRErrorLevel.LevelL));

    Dimension imageDimention = geCustomImageSizeDimention(size);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageFormatDTO responseImageTypeDto = getRequestedImageFormat(responseHeaders, acceptHeaderValue, format);

    long startTime = System.currentTimeMillis();

    LOGGER.debug("builder.save Start @  " + startTime);
    byte[] imageInByte;

    if (imageDimention != null) {

        // Set graphics unit
        builder.setGraphicsUnit(GraphicsUnit.Millimeter);

        // Set margins
        builder.getMargins().set(0);

        builder.setForeColor(getColorValue(foreColor, "#000000"));

        builder.setBackColor(getColorValue(bgColor, "#FFFFFF"));

        LOGGER.debug("builder.getGraphicsUnit() ::" + builder.getGraphicsUnit());

        // Get BufferedImage with exact bar code only
        BufferedImage img = builder.getOnlyBarCodeImage();

        LOGGER.debug("img.getWidth() : :" + img.getWidth());
        LOGGER.debug("img.getHeight() :: " + img.getHeight());

        if (imageDimention.getWidth() < img.getWidth()) {
            imageDimention.width = img.getWidth();
        }

        if (imageDimention.getHeight() < img.getHeight()) {
            imageDimention.height = img.getHeight();
        }

        BufferedImage img2 = builder.getCustomSizeBarCodeImage(imageDimention, true);

        MediaType responseType = responseImageTypeDto.getMediaType();
        ImageIO.write(img2, responseType.getSubtype(), baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();

    } else {

        builder.setxDimension(1.0f);
        builder.setyDimension(1.0f);

        builder.save(baos, responseImageTypeDto.getBarCodeImageFormat());
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();
    }

    long endTime = System.currentTimeMillis();

    LOGGER.debug("builder.save took " + (endTime - startTime) + " milliseconds");

    if (download) {

        MediaType responseType = responseImageTypeDto.getMediaType();
        responseHeaders.setContentType(responseType);
        responseHeaders.add("Content-Disposition",
                "attachment; filename=" + "Aspose_BarCode_QRCodeGen." + responseType.getSubtype());
    }

    return new ResponseEntity<byte[]>(imageInByte, responseHeaders, HttpStatus.CREATED);

}

From source file:org.apache.jsp.fileUploader_jsp.java

private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId,
        Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request,
        HttpServletResponse response) {/* w w  w . j  ava2s.c om*/
    String charset = "UTF-8";
    String url = "";
    try {
        if (isJson) {
            //first check if bytes are actually json
            try {
                new JsonParser().parse(new String(bytes));
            } catch (Exception ex) {
                return "Failed, file was not valid JSON";
            }
            if (newShare)
                url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
            else
                url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset)
                        + "/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
        } else {
            if (newShare)
                url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
            else
                url = API_ROOT + "social/share/update/binary/" + prevId + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
        }

        if (localCookie)
            CookieHandler.setDefault(cm);
        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", charset);
        String cookieVal = getBrowserInfiniteCookie(request);
        if (cookieVal != null) {
            connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept-Charset", "UTF-8");
        }
        if (mimeType != null && mimeType.length() > 0)
            connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset);
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.write(bytes);
        DataInputStream responseStream = new DataInputStream(connection.getInputStream());

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = responseStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        String json = buffer.toString();
        String newCookie = getConnectionInfiniteCookie(connection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }
        buffer.flush();
        buffer.close();
        output.close();
        responseStream.close();

        if (isJson) {
            jsonResponse jr = new Gson().fromJson(json, jsonResponse.class);
            if (jr == null) {
                return "Failed: " + json;
            }
            if (jr.response.success == true) {
                if (jr.data != null && jr.data._id != null) {
                    addRemoveCommunities(jr.data._id, communities, request, response);
                    return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload
                }
            }
            return "Upload Failed: " + jr.response.message;
        } else {
            modResponse mr = new Gson().fromJson(json, modResponse.class);
            if (mr == null) {
                return "Failed: " + json;
            }
            if (mr.response.success == true) {
                if (prevId != null && mr.data == null) {
                    addRemoveCommunities(prevId, communities, request, response);
                    return prevId;
                } else {
                    addRemoveCommunities(mr.data, communities, request, response);
                    return mr.data; //When a new upload, mr.data contains the ShareID for the upload
                }
            } else {
                return "Upload Failed: " + mr.response.message;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        return "Upload Failed: " + e.getMessage();
    }
}

From source file:it.govpay.web.rs.dars.anagrafica.domini.DominiHandler.java

@Override
public Dominio creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    Dominio entry = null;//from ww  w . j a v a2s.  co m
    String segregationCodeId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".segregationCode.id");
    String logoId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".logo.id");

    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di scrittura
        this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita);

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

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

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

        String segregationCode = jsonObjectDominio.getString(segregationCodeId);
        jsonObjectDominio.remove(segregationCodeId);

        JSONArray jsonArrayFile = jsonObjectDominio.getJSONArray(logoId);
        jsonObjectDominio.remove(logoId);

        jsonConfig.setRootClass(Dominio.class);
        entry = (Dominio) JSONObject.toBean(jsonObjectDominio, jsonConfig);

        if (StringUtils.isNotEmpty(segregationCode)) {
            entry.setSegregationCode(Integer.parseInt(segregationCode));
        }

        if (jsonArrayFile != null && jsonArrayFile.size() == 1) {
            JSONObject jsonObjectFile = jsonArrayFile.getJSONObject(0);
            //            String fileName = jsonObjectFile.getString(InputFile.FILENAME);
            String data64 = jsonObjectFile.getString(InputFile.DATA);
            entry.setLogo(Base64.decodeBase64(data64));
        }

        entry.setTabellaControparti(DominioUtils.buildInformativaControparte(entry, true));
        entry.setContiAccredito(
                DominioUtils.buildInformativaContoAccredito(entry, new ArrayList<IbanAccredito>()));
        this.log.info("Esecuzione " + methodName + " completata.");
        return entry;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:it.govpay.web.rs.dars.anagrafica.domini.DominiHandler.java

public List<Object> creaDominioEAnagrafica(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaDominioEAnagrafica " + this.titoloServizio;
    List<Object> list = new ArrayList<Object>();
    String segregationCodeId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".segregationCode.id");
    String logoId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".logo.id");
    String abilitaModificaLogoId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".abilitaModificaLogo.id");
    try {/*from ww w  . j  a va 2  s  .c  om*/
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di scrittura
        this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita);

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

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

        JSONObject jsonObjectDominio = JSONObject.fromObject(baos.toString());
        //         String ragioneSocialeId = Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(this.nomeServizio + ".ragioneSociale.id");
        //         JSONArray jsonArray = jsonObjectDominio.getJSONArray(ragioneSocialeId);
        //
        //         String ragSocDominio = jsonArray.getString(0);
        //         String ragSocAnagrafica = jsonArray.getString(1);
        //
        //         jsonObjectDominio.remove(ragioneSocialeId);

        String segregationCode = jsonObjectDominio.getString(segregationCodeId);
        jsonObjectDominio.remove(segregationCodeId);

        Boolean abilitaModificaLogo = false;
        JSONArray jsonArrayFile = null;
        if (jsonObjectDominio.getBoolean(abilitaModificaLogoId)) {
            jsonArrayFile = jsonObjectDominio.getJSONArray(logoId);
            abilitaModificaLogo = true;
        }

        jsonObjectDominio.remove(logoId);
        jsonObjectDominio.remove(abilitaModificaLogoId);

        jsonConfig.setRootClass(Dominio.class);

        Dominio entry = (Dominio) JSONObject.toBean(jsonObjectDominio, jsonConfig);
        entry.setTabellaControparti(DominioUtils.buildInformativaControparte(entry, true));
        entry.setContiAccredito(
                DominioUtils.buildInformativaContoAccredito(entry, new ArrayList<IbanAccredito>()));

        // azzero l'id applicazione default se ho selezionato nessuna.
        if (entry.getIdApplicazioneDefault() != null && entry.getIdApplicazioneDefault().longValue() == -1l) {
            entry.setIdApplicazioneDefault(null);
        }

        if (StringUtils.isNotEmpty(segregationCode)) {
            entry.setSegregationCode(Integer.parseInt(segregationCode));
        }

        if (jsonArrayFile != null && jsonArrayFile.size() == 1) {
            JSONObject jsonObjectFile = jsonArrayFile.getJSONObject(0);
            //            String fileName = jsonObjectFile.getString(InputFile.FILENAME);
            String data64 = jsonObjectFile.getString(InputFile.DATA);
            entry.setLogo(Base64.decodeBase64(data64));
        }

        jsonConfig.setRootClass(Anagrafica.class);
        Anagrafica anagrafica = (Anagrafica) JSONObject.toBean(jsonObjectDominio, jsonConfig);
        String ragSocAnagrafica = anagrafica.getRagioneSociale();
        entry.setRagioneSociale(ragSocAnagrafica);
        anagrafica.setRagioneSociale(null);

        String uoIdId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".uoId.id");
        String uoId = jsonObjectDominio.getString(uoIdId);
        Long uoIdLong = null;
        if (StringUtils.isNotEmpty(uoId)) {
            try {
                uoIdLong = Long.parseLong(uoId);
            } catch (Exception e) {
                uoIdLong = null;
            }
        }

        UnitaOperativa uo = new UnitaOperativa();
        uo.setAbilitato(true);
        uo.setAnagrafica(anagrafica);
        uo.setCodUo(it.govpay.model.Dominio.EC);
        anagrafica.setCodUnivoco(uo.getCodUo());
        if (entry.getId() != null) {
            uo.setIdDominio(entry.getId());
        }
        uo.setId(uoIdLong);

        list.add(entry);
        list.add(uo);
        list.add(abilitaModificaLogo);

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

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

/**
 * //w  w w .  ja va  2  s .  co m
 * @param post {@link HttpPost}
 * @return String posted body if computable
 * @throws IOException if sending the data fails due to I/O
 */
protected String sendPostData(HttpPost post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();

    final String contentEncoding = getContentEncodingOrNull();
    final boolean haveContentEncoding = contentEncoding != null;

    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        Charset charset = null;
        if (haveContentEncoding) {
            charset = Charset.forName(contentEncoding);
        } else {
            charset = MIME.DEFAULT_CHARSET;
        }

        if (log.isDebugEnabled()) {
            log.debug("Building multipart with:getDoBrowserCompatibleMultipart():"
                    + getDoBrowserCompatibleMultipart() + ", with charset:" + charset + ", haveContentEncoding:"
                    + haveContentEncoding);
        }
        // Write the request to our own stream
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setCharset(charset);
        if (getDoBrowserCompatibleMultipart()) {
            multipartEntityBuilder.setLaxMode();
        } else {
            multipartEntityBuilder.setStrictMode();
        }
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringBody stringBody = new StringBody(arg.getValue(), ContentType.create("text/plain", charset));
            FormBodyPart formPart = FormBodyPartBuilder.create(parameterName, stringBody).build();
            multipartEntityBuilder.addPart(formPart);
        }

        // Add any files
        // Cannot retrieve parts once added to the MultiPartEntity, so have to save them here.
        ViewableFileBody[] fileBodies = new ViewableFileBody[files.length];
        for (int i = 0; i < files.length; i++) {
            HTTPFileArg file = files[i];

            File reservedFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            fileBodies[i] = new ViewableFileBody(reservedFile, file.getMimeType());
            multipartEntityBuilder.addPart(file.getParamName(), fileBodies[i]);
        }

        HttpEntity entity = multipartEntityBuilder.build();
        post.setEntity(entity);

        if (entity.isRepeatable()) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = true;
            }
            entity.writeTo(bos);
            for (ViewableFileBody fileBody : fileBodies) {
                fileBody.hideFileData = false;
            }
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }

        //            // Set the content type TODO - needed?
        //            String multiPartContentType = multiPart.getContentType().getValue();
        //            post.setHeader(HEADER_CONTENT_TYPE, multiPartContentType);

    } else { // not multipart
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getFirstHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileEntity fileRequestEntity = new FileEntity(new File(file.getPath()), (ContentType) null);// TODO is null correct?
            post.setEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            if (haveContentEncoding) {
                post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, contentEncoding);
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // Note: if "Encoded?" is not selected, arg.getEncodedValue is equivalent to arg.getValue
                    if (haveContentEncoding) {
                        postBody.append(arg.getEncodedValue(contentEncoding));
                    } else {
                        postBody.append(arg.getEncodedValue());
                    }
                }
                // Let StringEntity perform the encoding
                StringEntity requestEntity = new StringEntity(postBody.toString(), contentEncoding);
                post.setEntity(requestEntity);
                postedBody.append(postBody.toString());
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                PropertyIterator args = getArguments().iterator();
                List<NameValuePair> nvps = new ArrayList<>();
                String urlContentEncoding = contentEncoding;
                if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                    // Use the default encoding for urls
                    urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                }
                while (args.hasNext()) {
                    HTTPArgument arg = (HTTPArgument) args.next().getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    nvps.add(new BasicNameValuePair(parameterName, parameterValue));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, urlContentEncoding);
                post.setEntity(entity);
                if (entity.isRepeatable()) {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    post.getEntity().writeTo(bos);
                    bos.flush();
                    // We get the posted bytes using the encoding used to create it
                    if (contentEncoding != null) {
                        postedBody.append(new String(bos.toByteArray(), contentEncoding));
                    } else {
                        postedBody.append(new String(bos.toByteArray(), SampleResult.DEFAULT_HTTP_ENCODING));
                    }
                    bos.close();
                } else {
                    postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
                }
            }
        }
    }
    return postedBody.toString();
}