Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

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

Usage

From source file:com.magnet.mmx.server.plugin.mmxmgmt.servlet.AppResource.java

@Path("{appId}/apnscert")
@POST/*from ww  w . j a  v a 2 s .  c o m*/
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response updateAppAPNsCertificateWithPassword(@PathParam("appId") String appId,
        MultipartFormDataInput input) {
    LOGGER.debug("Executing certificate upload with password");
    LOGGER.info("App ID :" + appId);
    try {
        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get(APNS_CERT_FILE);
        InputStream certificateFileStream = null;
        for (InputPart inputPart : inputParts) {
            certificateFileStream = inputPart.getBody(InputStream.class, null);
        }
        List<InputPart> passwordParts = uploadForm.get(APNS_CERT_PASSWORD);
        if (passwordParts == null || passwordParts.isEmpty() || passwordParts.get(0) == null
                || passwordParts.get(0).getBodyAsString().isEmpty()) {
            ErrorResponse error = new ErrorResponse();
            error.setMessage(ErrorMessages.ERROR_APNS_CERT_PASSWORD_MISSING);
            error.setCode(Integer.toString(ErrorCode.APNS_PASSWORD_MISSING.getCode()));
            throw new WebApplicationException(
                    Response.status(Response.Status.BAD_REQUEST).entity(error).build());
        }
        String password = passwordParts.get(0).getBodyAsString();
        ByteArrayOutputStream bufferStream = new ByteArrayOutputStream(WebConstants.APNS_CERT_MAX_SIZE);
        byte[] buffer = new byte[1024];
        int read = -1;
        int totalRead = 0;
        boolean tooBig = false;
        while ((read = certificateFileStream.read(buffer, 0, buffer.length)) != -1 && !tooBig) {
            if (totalRead + read > WebConstants.APNS_CERT_MAX_SIZE) {
                tooBig = true;
            } else {
                totalRead = totalRead + read;
                bufferStream.write(buffer, 0, read);
            }
        }
        bufferStream.flush();
        bufferStream.close();
        if (tooBig) {
            ErrorResponse error = new ErrorResponse();
            error.setMessage(APNS_CERT_SIZE_TOO_BIG);
            error.setCode(APNS_CERT_SIZE_TOO_BIG_CODE);
            throw new WebApplicationException(
                    Response.status(Response.Status.BAD_REQUEST).entity(error).build());
        }
        AppDAO dao = new AppDAOImpl(new OpenFireDBConnectionProvider());
        AppEntity appEntity = dao.getAppForAppKey(appId);
        if (appEntity == null) {
            throw build(AppErrorCode.INVALID_APP_ID.name(), APP_NOT_FOUND, Response.Status.NOT_FOUND);
        }

        byte[] certificate = bufferStream.toByteArray();
        if (password != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Validating APNS certificate");
            }
            APNSCertificateValidator.validate(new ByteArrayInputStream(certificate), password.toCharArray());
        }
        String md5String = DigestUtils.md5Hex(certificate);
        LOGGER.info("MD5 for apns cert for is {}", md5String);
        dao.updateAPNsCertificateAndPassword(appId, certificate, password);
        /*
         * if there are any connections established we need to purge them
         */
        APNSConnectionPool connectionPool = APNSConnectionPoolImpl.getInstance();
        LOGGER.info("Clearing open APNS connections");
        connectionPool.remove(appId, appEntity.isApnsCertProduction());
        return Response.ok().status(Response.Status.OK).build();
    } catch (WebApplicationException e) {
        throw e;
    } catch (APNSCertificateValidator.APNSCertificationValidationException e) {
        LOGGER.warn("APNS cert validation exception", e);
        ErrorResponse error = new ErrorResponse();
        error.setMessage(INVALID_APNS_CERTIFICATE);
        error.setCode(AppErrorCode.INVALID_APNS_CERT.name());
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity(error).build());
    } catch (Throwable t) {
        LOGGER.warn("Bad stuff happened", t);
        ErrorResponse error = new ErrorResponse();
        error.setCode(WebConstants.STATUS_ERROR);
        error.setMessage(t.getMessage());
        throw new WebApplicationException(
                Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build());
    }
}

From source file:com.glaf.core.util.FtpUtils.java

/**
 * //w  ww.  j  av  a2 s .c  o  m
 * 
 * @param remoteFile
 *            FTP"/"
 */
public static byte[] getBytes(String remoteFile) {
    byte[] bytes = null;
    InputStream in = null;
    ByteArrayOutputStream out = null;
    BufferedOutputStream bos = null;
    try {
        if (remoteFile.startsWith("/") && remoteFile.indexOf("/") > 0) {
            changeToDirectory(remoteFile);
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf("/") + 1, remoteFile.length());
        }
        // ?
        getFtpClient().enterLocalPassiveMode();
        // ?
        getFtpClient().setFileType(FTP.BINARY_FILE_TYPE);
        FTPFile[] files = getFtpClient().listFiles(new String(remoteFile.getBytes("GBK"), "ISO-8859-1"));
        if (files.length != 1) {
            logger.warn("remote file is not exists");
            return null;
        }
        long lRemoteSize = files[0].getSize();

        out = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(out);
        in = getFtpClient().retrieveFileStream(new String(remoteFile.getBytes("GBK"), "ISO-8859-1"));
        byte[] buff = new byte[4096];
        long step = lRemoteSize / 100;
        if (step == 0) {
            step = 1;
        }
        long progress = 0;
        long localSize = 0L;
        int c;
        while ((c = in.read(buff)) != -1) {
            out.write(buff, 0, c);
            localSize += c;
            long nowProgress = localSize / step;
            if (nowProgress > progress) {
                progress = nowProgress;
                if (progress % 10 == 0) {
                    logger.debug("download progress:" + progress);
                }
            }
        }
        out.flush();
        bos.flush();
        bytes = out.toByteArray();
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error("download error", ex);
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(in);
        IOUtils.closeStream(out);
    }
    return bytes;
}

From source file:com.bgh.myopeninvoice.jsf.jsfbeans.InvoiceBean.java

public String getImageAttachment(AttachmentEntity attachmentEntity) throws IOException, ImageReadException {
    if (attachmentEntity != null && attachmentEntity.getContent().length > 0) {
        if (attachmentEntity.getLoadProxy()) {
            return "/images/" + attachmentEntity.getFileExtension() + ".png";
        } else {/* www  .ja  v a  2 s.co  m*/

            selectedAttachmentEntity = attachmentEntity;

            ImageFormat mimeType = Sanselan.guessFormat(attachmentEntity.getContent());
            if (mimeType != null && !"UNKNOWN".equalsIgnoreCase(mimeType.name)) {
                return "data:image/" + mimeType.extension.toLowerCase() + ";base64,"
                        + Base64.getEncoder().encodeToString(attachmentEntity.getContent());

            } else if (attachmentEntity.getImageData() != null && attachmentEntity.getImageData().length > 0) {
                return "data:image/png;base64,"
                        + Base64.getEncoder().encodeToString(attachmentEntity.getImageData());

            } else if ("pdf".equalsIgnoreCase(attachmentEntity.getFileExtension())) {
                ByteArrayOutputStream baos = null;
                PDDocument document = null;
                try {
                    document = PDDocument.load(attachmentEntity.getContent());
                    final PDPage page = document.getPage(0);
                    PDFRenderer pdfRenderer = new PDFRenderer(document);
                    final BufferedImage bufferedImage = pdfRenderer.renderImage(0);
                    baos = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "png", baos);
                    baos.flush();
                    attachmentEntity.setImageData(baos.toByteArray());
                } finally {
                    if (document != null) {
                        document.close();
                    }
                    if (baos != null) {
                        baos.close();
                    }
                }
                return "data:image/png;base64,"
                        + Base64.getEncoder().encodeToString(attachmentEntity.getImageData());
            } else {
                return null;
            }
        }
    } else if (selectedAttachmentEntity != null && selectedAttachmentEntity.getImageData() != null
            && selectedAttachmentEntity.getImageData().length > 0) {
        return "data:image/png;base64,"
                + Base64.getEncoder().encodeToString(selectedAttachmentEntity.getImageData());

    } else {
        return null;
    }
}

From source file:com.cloudbase.CBHelperRequest.java

public void run() {
    HttpConnection hc = null;//from   w w  w . j  a va2s.c  o  m
    InputStream is = null;

    try {
        hc = (HttpConnection) Connector.open(url + ";deviceside=true");
        hc.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + CBHelperRequest.FIELD_BOUNDARY);

        hc.setRequestMethod(HttpConnection.POST);

        ByteArrayOutputStream request = new ByteArrayOutputStream();//hc.openOutputStream();

        // Add your data
        Enumeration params = this.postData.keys();
        while (params.hasMoreElements()) {
            String curKey = (String) params.nextElement();
            request.write(this.getParameterPostData(curKey, (String) this.postData.get(curKey)));
            //entity.addPart(new CBStringPart(curKey, this.postData.get(curKey)));
        }
        // if we have file attachments then add each file to the multipart request
        if (this.files != null && this.files.size() > 0) {

            for (int i = 0; i < this.files.size(); i++) {
                CBHelperAttachment curFile = (CBHelperAttachment) this.files.elementAt(i);
                String name = curFile.getFileName();

                request.write(this.getFilePostData(i, name, curFile.getFileData()));
            }
        }
        request.flush();
        hc.setRequestProperty("Content-Length", "" + request.toByteArray().length);
        OutputStream requestStream = hc.openOutputStream();
        requestStream.write(request.toByteArray());
        requestStream.close();

        is = hc.openInputStream();

        // if we have a responder then parse the response data into the global CBHelperResponse object
        if (this.responder != null) {
            try {
                resp = new CBHelperResponse();
                resp.setFunction(this.function);

                int ch;
                ByteArrayOutputStream response = new ByteArrayOutputStream();

                while ((ch = is.read()) != -1) {
                    response.write(ch);
                }

                // if it's a download then we need to save the file content into a temporary file in
                // application cache folder. Then return that file to the responder
                if (this.function.equals("download")) {
                    String filePath = "file:///store/home/user/" + this.fileId;
                    FileConnection fconn = (FileConnection) Connector.open(filePath);
                    if (fconn.exists()) {
                        fconn.delete();
                    }
                    fconn.create();

                    DataOutputStream fs = fconn.openDataOutputStream();
                    fs.write(response.toByteArray());
                    fs.close();
                    fconn.close();
                    resp.setDownloadedFile(filePath);
                } else {

                    // if it's not a download parse the JSON response and set all 
                    // the variables in the CBHelperResponse object
                    String responseString = new String(response.toByteArray());//EntityUtils.toString(response.getEntity());

                    //System.out.println("Received response string: " + responseString);
                    resp.setResponseDataString(responseString);

                    JSONTokener tokener = new JSONTokener(responseString);
                    JSONObject jsonOutput = new JSONObject(tokener);

                    // Use the cloudbase.io deserializer to get the data in a Map<String, Object>
                    // format.
                    JSONObject outputData = jsonOutput.getJSONObject(this.function);

                    resp.setData(outputData.get("message"));
                    resp.setErrorMessage((String) outputData.get("error"));
                    resp.setSuccess(((String) outputData.get("status")).equals("OK"));
                }
                //Application.getApplication().enterEventDispatcher();
                responder.handleResponse(resp);
            } catch (Exception e) {
                System.out.println("Error while parsing response: " + e.getMessage());
                e.printStackTrace();
            }
        }

    } catch (Exception e) {
        System.out.println("Error while opening connection and sending data: " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:nl.surfsara.newsreader.pipeline.modules.GenericNewsreaderModule.java

@Override
public Module call() throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ByteArrayOutputStream bes = new ByteArrayOutputStream();

    File f = new File(pipelineStep.getModulePath() + "/run.sh.hadoop");
    File component = new File(pipelineStep.getModulePath());
    File scratch = new File(getLocalDirectory());

    super.setCommandLine("/bin/bash " + f.getAbsolutePath() + " " + component.getAbsolutePath() + "/ "
            + scratch.getAbsolutePath() + "/");
    super.setSubProcessStdIn(IOUtils.toInputStream(getInputDocument()));
    super.setSubProcessStdOut(bos);
    super.setSubProcessStdErr(bes);
    super.runSubprocess();

    String stderr = bes.toString();
    int newlines = stderr.split(System.getProperty("line.separator")).length;
    if (newlines > pipelineStep.getNumErrorLines()) {
        setFailed(true);/*from  w  w w  .  j a v a  2s.  com*/
    }
    // TODO instead of checking the number of newlines in stderr a much prettier solution would be to capture the exit code of
    // the run.sh script. The run.sh scripts do need to be altered so that this exit code reflects functioning or disfunctioning of a component.
    logger.error(stderr);
    bos.flush();
    setOutputDocument(bos.toString());
    bos.close();
    bes.close();
    return this;
}

From source file:org.apache.pdfbox.pdfwriter.COSWriter.java

private void doWriteSignature() throws IOException {
    if (signatureOffset == 0 || byteRangeOffset == 0) {
        return;//from  w  w w.jav  a  2s. co m
    }

    // calculate the ByteRange values
    long inLength = incrementalInput.available();
    long beforeLength = signatureOffset;
    long afterOffset = signatureOffset + signatureLength;
    long afterLength = getStandardOutput().getPos() - (inLength + signatureLength)
            - (signatureOffset - inLength);

    String byteRange = "0 " + beforeLength + " " + afterOffset + " " + afterLength + "]";
    if (byteRangeLength - byteRange.length() < 0) {
        throw new IOException("Can't write new ByteRange, not enough space");
    }

    // copy the new incremental data into a buffer (e.g. signature dict, trailer)
    ByteArrayOutputStream byteOut = (ByteArrayOutputStream) output;
    byteOut.flush();
    byte[] buffer = byteOut.toByteArray();

    // overwrite the ByteRange in the buffer
    byte[] byteRangeBytes = byteRange.getBytes(Charsets.ISO_8859_1);
    for (int i = 0; i < byteRangeLength; i++) {
        if (i >= byteRangeBytes.length) {
            buffer[(int) (byteRangeOffset + i - inLength)] = 0x20; // SPACE
        } else {
            buffer[(int) (byteRangeOffset + i - inLength)] = byteRangeBytes[i];
        }
    }

    // get the input PDF bytes
    byte[] inputBytes = IOUtils.toByteArray(incrementalInput);

    // get only the incremental bytes to be signed (includes /ByteRange but not /Contents)
    byte[] signBuffer = new byte[buffer.length - (int) signatureLength];
    int bufSignatureOffset = (int) (signatureOffset - inLength);
    System.arraycopy(buffer, 0, signBuffer, 0, bufSignatureOffset);
    System.arraycopy(buffer, bufSignatureOffset + (int) signatureLength, signBuffer, bufSignatureOffset,
            buffer.length - bufSignatureOffset - (int) signatureLength);

    SequenceInputStream signStream = new SequenceInputStream(new ByteArrayInputStream(inputBytes),
            new ByteArrayInputStream(signBuffer));

    // sign the bytes
    byte[] sign = signatureInterface.sign(signStream);
    String signature = new COSString(sign).toHexString();
    // substract 2 bytes because of the enclosing "<>"
    if (signature.length() > signatureLength - 2) {
        throw new IOException("Can't write signature, not enough space");
    }

    // overwrite the signature Contents in the buffer
    byte[] signatureBytes = signature.getBytes(Charsets.ISO_8859_1);
    System.arraycopy(signatureBytes, 0, buffer, bufSignatureOffset + 1, signatureBytes.length);

    // write the data to the incremental output stream
    incrementalOutput.write(inputBytes);
    incrementalOutput.write(buffer);
}

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

/**Writes a passed payload part to the passed message object. 
 *///from w  ww  . j  a  v a2 s  .c o  m
public void writePayloadsToMessage(Part payloadPart, AS2Message message, Properties header) throws Exception {
    List<Part> attachmentList = new ArrayList<Part>();
    AS2Info info = message.getAS2Info();
    if (!info.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
        if (payloadPart.isMimeType("multipart/*")) {
            //check if it is a CEM
            if (payloadPart.getContentType().toLowerCase().contains("application/ediint-cert-exchange+xml")) {
                messageInfo.setMessageType(AS2Message.MESSAGETYPE_CEM);
                if (this.logger != null) {
                    this.logger.log(Level.FINE, this.rb.getResourceString("found.cem",
                            new Object[] { messageInfo.getMessageId(), message }), info);
                }
            }
            ByteArrayOutputStream mem = new ByteArrayOutputStream();
            payloadPart.writeTo(mem);
            mem.flush();
            mem.close();
            MimeMultipart multipart = new MimeMultipart(
                    new ByteArrayDataSource(mem.toByteArray(), payloadPart.getContentType()));
            //add all attachments to the message
            for (int i = 0; i < multipart.getCount(); i++) {
                //its possible that one of the bodyparts is the signature (for compressed/signed messages), skip the signature
                if (!multipart.getBodyPart(i).getContentType().toLowerCase().contains("pkcs7-signature")) {
                    attachmentList.add(multipart.getBodyPart(i));
                }
            }
        } else {
            attachmentList.add(payloadPart);
        }
    } else {
        //its a MDN, write whole part
        attachmentList.add(payloadPart);
    }
    //write the parts
    for (Part attachmentPart : attachmentList) {
        ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
        InputStream payloadIn = attachmentPart.getInputStream();
        this.copyStreams(payloadIn, payloadOut);
        payloadOut.flush();
        payloadOut.close();
        byte[] data = payloadOut.toByteArray();
        AS2Payload as2Payload = new AS2Payload();
        as2Payload.setData(data);
        String[] contentIdHeader = attachmentPart.getHeader("content-id");
        if (contentIdHeader != null && contentIdHeader.length > 0) {
            as2Payload.setContentId(contentIdHeader[0]);
        }
        String[] contentTypeHeader = attachmentPart.getHeader("content-type");
        if (contentTypeHeader != null && contentTypeHeader.length > 0) {
            as2Payload.setContentType(contentTypeHeader[0]);
        }
        try {
            as2Payload.setOriginalFilename(payloadPart.getFileName());
        } catch (MessagingException e) {
            if (this.logger != null) {
                this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                        new Object[] { info.getMessageId(), e.getMessage(), }), info);
            }
        }
        if (as2Payload.getOriginalFilename() == null) {
            String filenameheader = header.getProperty("content-disposition");
            if (filenameheader != null) {
                //test part for convinience: extract file name
                MimeBodyPart filenamePart = new MimeBodyPart();
                filenamePart.setHeader("content-disposition", filenameheader);
                try {
                    as2Payload.setOriginalFilename(filenamePart.getFileName());
                } catch (MessagingException e) {
                    if (this.logger != null) {
                        this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                                new Object[] { info.getMessageId(), e.getMessage(), }), info);
                    }
                }
            }
        }
        message.addPayload(as2Payload);
    }
}

From source file:microsoft.exchange.webservices.data.core.request.ServiceRequestBase.java

/**
 * Processes the web exception./*from  ww  w . j  av  a  2s  . c  o  m*/
 *
 * @param webException the web exception
 * @param req          HTTP Request object used to send the http request
 * @throws Exception on error
 */
protected void processWebException(Exception webException, HttpWebRequest req) throws Exception {
    SoapFaultDetails soapFaultDetails;
    if (null != req) {
        this.getService().processHttpResponseHeaders(TraceFlags.EwsResponseHttpHeaders, req);
        if (500 == req.getResponseCode()) {
            if (this.service.isTraceEnabledFor(TraceFlags.EwsResponse)) {
                ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
                InputStream serviceResponseStream = ServiceRequestBase.getResponseErrorStream(req);
                while (true) {
                    int data = serviceResponseStream.read();
                    if (-1 == data) {
                        break;
                    } else {
                        memoryStream.write(data);
                    }
                }
                memoryStream.flush();
                serviceResponseStream.close();
                this.traceResponse(req, memoryStream);
                ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
                EwsServiceXmlReader reader = new EwsServiceXmlReader(memoryStreamIn, this.service);
                soapFaultDetails = this.readSoapFault(reader);
                memoryStream.close();
            } else {
                InputStream serviceResponseStream = ServiceRequestBase.getResponseStream(req);
                EwsServiceXmlReader reader = new EwsServiceXmlReader(serviceResponseStream, this.service);
                soapFaultDetails = this.readSoapFault(reader);
                serviceResponseStream.close();

            }

            if (soapFaultDetails != null) {
                switch (soapFaultDetails.getResponseCode()) {
                case ErrorInvalidServerVersion:
                    throw new ServiceVersionException("Exchange Server doesn't support the requested version.");

                case ErrorSchemaValidation:
                    // If we're talking to an E12 server
                    // (8.00.xxxx.xxx), a schema
                    // validation error is the same as
                    // a version mismatch error.
                    // (Which only will happen if we
                    // send a request that's not valid
                    // for E12).
                    if ((this.service.getServerInfo() != null)
                            && (this.service.getServerInfo().getMajorVersion() == 8)
                            && (this.service.getServerInfo().getMinorVersion() == 0)) {
                        throw new ServiceVersionException(
                                "Exchange Server doesn't support the requested version.");
                    }

                    break;

                case ErrorIncorrectSchemaVersion:
                    // This shouldn't happen. It
                    // indicates that a request wasn't
                    // valid for the version that was specified.
                    EwsUtilities.ewsAssert(false, "ServiceRequestBase.ProcessWebException",
                            "Exchange server supports " + "requested version "
                                    + "but request was invalid for that version");
                    break;

                default:
                    // Other error codes will
                    // be reported as remote error
                    break;
                }

                // General fall-through case:
                // throw a ServiceResponseException
                throw new ServiceResponseException(new ServiceResponse(soapFaultDetails));
            }
        } else {
            this.service.processHttpErrorResponse(req, webException);
        }
    }

}

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

/**Decrypts the data of a message with all given certificates etc
 * @param info MessageInfo, the encryption algorith will be stored in the encryption type of this info
 * @param rawMessageData encrypted data, will be decrypted
 * @param contentType contentType of the data
 * @param privateKey receivers private key
 * @param certificate receivers certificate
 *///from w  w  w  .  j a v  a  2  s  . c  om
public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver,
        X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeBodyPart encryptedBody = new MimeBodyPart();
    encryptedBody.setHeader("content-type", contentType);
    encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    RecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver);
    SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody);
    BCCryptoHelper helper = new BCCryptoHelper();
    String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID());
    if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_3DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_128);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_192);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_256);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN);
    } else {
        info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM);
    }
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    enveloped = null;
    encryptedBody = null;
    RecipientInformation recipient = recipients.get(recipientId);
    if (recipient == null) {
        //give some details about the required and used cert for the decryption
        Collection recipientList = recipients.getRecipients();
        Iterator iterator = recipientList.iterator();
        while (iterator.hasNext()) {
            RecipientInformation recipientInfo = (RecipientInformation) iterator.next();
            if (this.logger != null) {
                this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.inforequired",
                        new Object[] { info.getMessageId(), recipientInfo.getRID() }), info);
            }
        }
        if (this.logger != null) {
            this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.infoassigned",
                    new Object[] { info.getMessageId(), receiverCryptAlias, recipientId }), info);
        }
        throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR,
                "Error decrypting the message: Recipient certificate does not match.", message);
    }
    //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses
    //far more memory.
    InputStream contentStream = recipient
            .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC"))
            .getContentStream();
    //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream();
    //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk
    DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_",
            ".mem", null);
    this.copyStreams(contentStream, decryptedOutput);
    decryptedOutput.flush();
    decryptedOutput.close();
    contentStream.close();
    byte[] decryptedData = null;
    //size of the data was < than the threshold
    if (decryptedOutput.isInMemory()) {
        decryptedData = decryptedOutput.getData();
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        decryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = decryptedOutput.getFile().delete();
        decryptedData = memOut.toByteArray();
    }
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("decryption.done.alias",
                        new Object[] { info.getMessageId(), receiverCryptAlias,
                                this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }),
                info);
    }
    return (decryptedData);
}

From source file:org.kegbot.api.KegbotApiImpl.java

/** Builds a multi-part form body. */
private static RequestBody formBody(Map<String, String> params, Map<String, File> files)
        throws KegbotApiException {
    final String boundary = getBoundary();
    final byte[] boundaryBytes = boundary.getBytes();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    final byte[] outputBytes;
    try {/*  w  w  w. jav a 2s .  c o  m*/
        // Form data.
        for (final Map.Entry<String, String> param : params.entrySet()) {
            bos.write(HYPHENS);
            bos.write(boundaryBytes);
            bos.write(CRLF);
            bos.write(String.format("Content-Disposition: form-data; name=\"%s\"", param.getKey()).getBytes());
            bos.write(CRLF);
            bos.write(CRLF);
            bos.write(param.getValue().getBytes());
            bos.write(CRLF);
        }

        // Files
        for (final Map.Entry<String, File> entry : files.entrySet()) {
            final String entityName = entry.getKey();
            final File file = entry.getValue();

            bos.write(HYPHENS);
            bos.write(boundaryBytes);
            bos.write(CRLF);
            bos.write(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", entityName,
                    file.getName()).getBytes());
            bos.write(CRLF);
            bos.write(CRLF);

            final FileInputStream fis = new FileInputStream(file);
            try {
                ByteStreams.copy(fis, bos);
            } finally {
                fis.close();
            }
            bos.write(CRLF);
        }
        bos.write(HYPHENS);
        bos.write(boundaryBytes);
        bos.write(HYPHENS);
        bos.write(CRLF);

        bos.flush();
        outputBytes = bos.toByteArray();
    } catch (IOException e) {
        throw new KegbotApiException(e);
    }

    return RequestBody.create(MediaType.parse("multipart/form-data;boundary=" + boundary), outputBytes);
}