Example usage for org.apache.commons.codec.binary Base64 encodeBase64Chunked

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64Chunked

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 encodeBase64Chunked.

Prototype

public static byte[] encodeBase64Chunked(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks

Usage

From source file:mitm.common.properties.HierarchicalPropertiesUtils.java

/**
 * Sets the binary property named propertyName. The byte[] is base64 encoded.
 * @throws HierarchicalPropertiesException 
 *//*  w w w.j a v a 2  s . c  om*/
public static void setBinary(HierarchicalProperties properties, String propertyName, byte[] value,
        boolean encrypt) throws HierarchicalPropertiesException {
    String base64 = null;

    if (value != null) {
        base64 = MiscStringUtils.toAsciiString(Base64.encodeBase64Chunked(value));
    }

    properties.setProperty(propertyName, base64, encrypt);
}

From source file:mitm.application.djigzo.james.MailAttributesUtils.java

/**
 * Sets the binary attribute. The byte[] is base64 encoded.
 *//* w  ww .  j a v a  2s.c om*/
public static void setBinary(Mail mail, String attribute, byte[] value) {
    String base64 = MiscStringUtils.toAsciiString(Base64.encodeBase64Chunked(value));

    mail.setAttribute(attribute, base64);
}

From source file:mitm.common.tools.SMIME.java

private static MimeMessage loadp7m(String filename, boolean binary) throws Exception {
    File p7mFile = new File(filename);

    p7mFile = p7mFile.getAbsoluteFile();

    FileInputStream fis = new FileInputStream(p7mFile);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    OutputStreamWriter sw = new OutputStreamWriter(bos);

    sw.append("Content-Type: application/pkcs7-mime; name=\"smime.p7m\"\r\n");
    sw.append("Content-Transfer-Encoding: base64\r\n");
    sw.append("\r\n\r\n");

    byte[] content = IOUtils.toByteArray(fis);

    if (binary) {
        content = Base64.encodeBase64Chunked(content);
    }//from w w w .  ja  va  2 s. c  o m

    String base64Content = MiscStringUtils.toAsciiString(content);

    sw.append(base64Content);

    sw.flush();

    MimeMessage message = MailUtils.byteArrayToMessage(bos.toByteArray());

    return message;
}

From source file:com.mirth.connect.model.converters.DICOMSerializer.java

/**
 * Revoves pixel data from the specified DicomObject and returns a list of
 * Base64 encoded image data./*w  ww .j ava 2s .  c  o  m*/
 * 
 * @param dicomObject
 * @return
 */
private List<String> extractPixelDataFromDicomObject(DicomObject dicomObject) {
    List<String> images = new ArrayList<String>();
    // this removes the data from the DICOM object
    DicomElement dicomElement = dicomObject.remove(Tag.PixelData);

    if (dicomElement != null) {
        if (dicomElement.hasItems()) {
            for (int i = 0; i < dicomElement.countItems(); i++) {
                images.add(new String(Base64.encodeBase64Chunked(dicomElement.getFragment(i))));
            }
        } else {
            images.add(new String(Base64.encodeBase64Chunked(dicomElement.getBytes())));
        }
    }

    return images;
}

From source file:gov.nih.nci.cagrid.opensaml.SAMLObject.java

/**
 *  Returns a base64-encoded XML representation of the SAML object
 *
 * @return                          A byte array containing the encoded data
 * @exception  java.io.IOException  Raised if an I/O problem is detected
 * @exception  SAMLException Raised if the object is incompletely defined
 *//*from   w ww .  j a  va2s  .c  om*/
public byte[] toBase64() throws java.io.IOException, SAMLException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    toStream(out);
    return Base64.encodeBase64Chunked(out.toByteArray());
}

From source file:com.mirth.connect.connectors.file.FileMessageReceiver.java

public synchronized void processFile(FileInfo file) throws UMOException {

    boolean checkFileAge = fileConnector.isCheckFileAge();
    if (checkFileAge) {
        long fileAge = fileConnector.getFileAge();
        long lastMod = file.getLastModified();
        long now = System.currentTimeMillis();
        if ((now - lastMod) < fileAge)
            return;
    }/*from  w w  w .  j av a  2  s  . co  m*/

    String destinationDir = null;
    String destinationName = null;
    originalFilename = file.getName();
    UMOMessageAdapter adapter = connector.getMessageAdapter(file);
    adapter.setProperty(FileConnector.PROPERTY_ORIGINAL_FILENAME, originalFilename);

    if (moveDir != null) {
        destinationName = file.getName();

        VariableFilenameParser filenameParser = (VariableFilenameParser) fileConnector.getFilenameParser();
        filenameParser.setChannelId(fileConnector.getChannelId());

        if (moveToPattern != null) {
            destinationName = filenameParser.getFilename(adapter, moveToPattern);
        }

        destinationDir = filenameParser.getFilename(adapter, moveDir);
    }

    boolean resultOfFileMoveOperation = false;

    try {
        // Perform some quick checks to make sure file can be processed
        if (file.isDirectory()) {
            // ignore directories
        } else if (!(file.isReadable() && file.isFile())) {
            // it's either not readable, or something odd like a link */
            throw new MuleException(new Message(Messages.FILE_X_DOES_NOT_EXIST, file.getName()));
        } else {

            Exception fileProcessedException = null;

            try {

                // ast: use the user-selected encoding
                if (fileConnector.isProcessBatchFiles()) {
                    processBatch(file);
                } else {
                    String message = "";
                    if (fileConnector.isBinary()) {
                        message = new String(Base64.encodeBase64Chunked(getBytesFromFile(file)));
                    } else {
                        message = new String(getBytesFromFile(file), fileConnector.getCharsetEncoding());
                    }
                    adapter = connector.getMessageAdapter(message);
                    adapter.setProperty(FileConnector.PROPERTY_ORIGINAL_FILENAME, originalFilename);
                    UMOMessage umoMessage = routeMessage(new MuleMessage(adapter), endpoint.isSynchronous());
                    if (umoMessage != null) {
                        postProcessor.doPostProcess(umoMessage.getPayload());
                    }
                }
            } catch (RoutingException e) {
                logger.error("Unable to route." + ExceptionUtils.getStackTrace(e));

                // routingError is reset to false at the beginning of the
                // poll method
                routingError = true;

                if (errorDir != null) {
                    logger.error("Moving file to error directory: " + errorDir);

                    VariableFilenameParser filenameParser = (VariableFilenameParser) fileConnector
                            .getFilenameParser();
                    filenameParser.setChannelId(fileConnector.getChannelId());

                    destinationDir = filenameParser.getFilename(adapter, errorDir);
                    destinationName = file.getName();
                }
            } catch (Throwable t) {
                logger.error("Error reading file " + file.getAbsolutePath() + "\n" + t.getMessage());
                fileProcessedException = new MuleException(
                        new Message(Messages.FAILED_TO_READ_PAYLOAD, file.getName()));
            }

            // move the file if needed
            if (destinationDir != null) {
                deleteFile(destinationName, destinationDir, true);

                resultOfFileMoveOperation = renameFile(file.getName(), readDir, destinationName,
                        destinationDir);

                if (!resultOfFileMoveOperation) {
                    throw new MuleException(new Message("file", 4, pathname(file.getName(), readDir),
                            pathname(destinationName, destinationDir)));
                }
            } else if (fileConnector.isAutoDelete()) {
                // adapter.getPayloadAsBytes();

                resultOfFileMoveOperation = deleteFile(file.getName(), readDir, false);

                if (!resultOfFileMoveOperation) {
                    throw new MuleException(new Message("file", 3, pathname(file.getName(), readDir)));
                }
            }

            if (fileProcessedException != null) {
                throw fileProcessedException;
            }
        }
    } catch (Exception e) {
        alertController.sendAlerts(((FileConnector) connector).getChannelId(), Constants.ERROR_403, "", e);
        handleException(e);
    }
}

From source file:com.zimbra.cs.service.formatter.VCard.java

public static List<VCard> parseVCard(String vcard) throws ServiceException {
    List<VCard> cards = new ArrayList<VCard>();

    Map<String, String> fields = new HashMap<String, String>();
    ListMultimap<String, VCardParamsAndValue> xprops = ArrayListMultimap.create();
    List<Attachment> attachments = new ArrayList<Attachment>();

    VCardProperty vcprop = new VCardProperty();
    int depth = 0;
    int cardstart = 0;
    String uid = null;/*from   www  .ja  va2s  .  co  m*/
    StringBuilder line = new StringBuilder(256);
    for (int start, pos = 0, limit = vcard.length(); pos < limit;) {
        // unfold the next line in the vcard
        line.setLength(0);
        String name = null;
        String value;
        int linestart = pos;
        boolean folded = true;
        do {
            start = pos;
            while (pos < limit && vcard.charAt(pos) != '\r' && vcard.charAt(pos) != '\n') {
                pos++;
            }
            line.append(vcard.substring(start, pos));
            if (pos < limit) {
                if (pos < limit && vcard.charAt(pos) == '\r')
                    pos++;
                if (pos < limit && vcard.charAt(pos) == '\n')
                    pos++;
            }
            if (pos < limit && (vcard.charAt(pos) == ' ' || vcard.charAt(pos) == '\t')) {
                pos++;
            } else {
                name = vcprop.parse(line);
                if ((vcprop.getEncoding() != Encoding.Q)
                        || !((line.length() > 0) && ('=' == (line.charAt(line.length() - 1))))) {
                    folded = false;
                }
            }
        } while (folded);
        if (vcprop.isEmpty()) {
            continue;
        }

        if (Strings.isNullOrEmpty(name)) {
            throw ServiceException.PARSE_ERROR("missing property name in line " + shortFormForLogging(line),
                    null);
        } else if (name.equals("VERSION") || name.equals("REV") || name.equals("PRODID")) {
            continue;
        } else if ((name.startsWith("X-") && !name.startsWith("X-ZIMBRA-"))
                || (!PROPERTY_NAMES.contains(name) /* Assume iana-token */)) {
            VCardParamsAndValue ppav;
            if (Encoding.B.equals(vcprop.encoding)) {
                // Keep value encoded as don't trust binary data stored in metadata
                Set<String> params = vcprop.params;
                params.add("ENCODING=B");
                if ((vcprop.charset != null) && (!MimeConstants.P_CHARSET_UTF8.equals(vcprop.charset))) {
                    params.add(String.format("CHARSET=%s", vcprop.charset));
                }
                ppav = new VCardParamsAndValue(vcprop.value, vcprop.params);
            } else {
                ppav = new VCardParamsAndValue(vcfDecode(vcprop.getValue()), vcprop.params);
            }
            // handle multiple occurrences of xprops with the same key
            String group = vcprop.getGroup();
            String key = (group == null) ? name : group + "." + name;
            xprops.put(key, ppav);
        } else if (name.equals("BEGIN")) {
            if (++depth == 1) {
                // starting a top-level vCard; reset state
                fields = new HashMap<String, String>();
                xprops = ArrayListMultimap.create();
                attachments = new ArrayList<Attachment>();
                cardstart = linestart;
                uid = null;
            }
            continue;
        } else if (name.equals("END")) {
            if (depth > 0 && depth-- == 1) {
                if (!xprops.isEmpty()) {
                    fields.put(ContactConstants.A_vCardXProps, Contact.encodeUnknownVCardProps(xprops));
                }

                // finished a vCard; add to list if non-empty
                if (!fields.isEmpty()) {
                    Contact.normalizeFileAs(fields);
                    cards.add(new VCard(fields.get(ContactConstants.A_fullName),
                            vcard.substring(cardstart, pos), fields, attachments, uid));
                }
            }
            continue;
        } else if (depth <= 0) {
            continue;
        } else if (name.equals("AGENT")) {
            // catch AGENT on same line as BEGIN block when rest of AGENT is not on the same line
            if (vcprop.getValue().trim().toUpperCase().matches("BEGIN\\s*:\\s*VCARD"))
                depth++;
            continue;
        }

        if (vcprop.getEncoding() == Encoding.B && !vcprop.containsParam("VALUE=URI")) {
            if (name.equals("PHOTO")) {
                String suffix = vcprop.getParamValue("TYPE").toUpperCase();
                String ctype = null;
                if (!Strings.isNullOrEmpty(suffix)) {
                    ctype = "image/" + suffix.toLowerCase();
                    suffix = '.' + suffix;
                }
                attachments.add(new Attachment(vcprop.getDecoded(), ctype, "image", "image" + suffix));
                continue;
            }
            if (name.equals("KEY")) {
                String encoded = new String(Base64.encodeBase64Chunked(vcprop.getDecoded()));
                fields.put(ContactConstants.A_userCertificate, encoded);
                continue;
            }
        }

        value = vcprop.getValue();

        // decode the property's value and assign to the appropriate contact field(s)
        if (name.equals("FN"))
            addField(ContactConstants.A_fullName, vcfDecode(value), "altFullName", 2, fields);
        else if (name.equals("N"))
            decodeStructured(value, NAME_FIELDS, fields);
        else if (name.equals("NICKNAME")) // TODO: VCARD 4 NICKNAME is multi-valued (COMMA separated)
                                          //       It is treated as a single value here
            addField(ContactConstants.A_nickname, vcfDecode(value), "altNickName", 2, fields);
        else if (name.equals("PHOTO"))
            fields.put(ContactConstants.A_image, vcfDecode(value)); // Assumption: Do not want multiple photos.
        else if (name.equals("BDAY"))
            addField(ContactConstants.A_birthday, vcfDecode(value), null, 2, fields);
        else if (name.equals("ADR"))
            decodeAddress(value, vcprop, fields);
        else if (name.equals("TEL"))
            decodeTelephone(value, vcprop, fields);
        else if (name.equals("URL"))
            decodeURL(value, vcprop, fields);
        else if (name.equals("ORG"))
            decodeStructured(value, ORG_FIELDS, fields);
        else if (name.equals("TITLE"))
            addField(ContactConstants.A_jobTitle, vcfDecode(value), "altJobTitle", 2, fields);
        else if (name.equals("NOTE"))
            addField(ContactConstants.A_notes, vcfDecode(value), null, 2, fields);
        else if (name.equals("EMAIL"))
            addField(ContactConstants.A_email, vcfDecode(value), null, 2, fields);
        else if (name.equals("X-ZIMBRA-MAIDENNAME"))
            fields.put(ContactConstants.A_maidenName, vcfDecode(value));
        else if (name.startsWith("X-ZIMBRA-IMADDRESS"))
            addField("imAddress", true, vcfDecode(value), null, 1, fields);
        else if (name.equals("X-ZIMBRA-ANNIVERSARY"))
            addField(ContactConstants.A_anniversary, vcfDecode(value), null, 2, fields);
        else if (name.equals("UID"))
            uid = value;
    }

    return cards;
}

From source file:com.jbrisbin.riak.async.RiakAsyncClient.java

@SuppressWarnings({ "unchecked" })
@Override//from w  w  w. j a va 2  s. c o m
public Promise<byte[]> generateAndSetClientId() throws IOException {
    SecureRandom sr;
    try {
        sr = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    byte[] data = new byte[6];
    sr.nextBytes(data);
    String clientId = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1);
    RPB.RpbSetClientIdReq.Builder b = RPB.RpbSetClientIdReq.newBuilder().setClientId(copyFromUtf8(clientId));
    Promise<byte[]> promise = new Promise<byte[]>();
    try {
        getConnection().write(new RpbRequest(new RpbMessage(MSG_SetClientIdReq, b.build()), promise));
    } catch (Exception e) {
        errorHandler.handleError(e);
    }
    return promise;
}

From source file:com.mirth.connect.client.ui.EditMessageDialog.java

private void openBinaryFileButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_openBinaryFileButtonActionPerformed
{//GEN-HEADEREND:event_openBinaryFileButtonActionPerformed
    byte[] content = parent.browseForFileBytes(null);

    if (content != null) {
        messageContent.setText(new String(Base64.encodeBase64Chunked(content)));
    }/*  ww w .  j av a2s . c  o  m*/
}

From source file:com.vmware.aurora.vc.vcservice.VcService.java

/**
 * Returns a PEM representation of a certificate
 *
 * @param cert A non-null certificate/*from  w  w w .jav a  2  s  .com*/
 * @return The PEM representation
 * @throws CertificateEncodingException, if certificate is malformed
 */
private static String CertificateToPem(Certificate cert) throws CertificateEncodingException {
    byte[] base64 = Base64.encodeBase64Chunked(cert.getEncoded());
    StringBuffer sb = new StringBuffer();
    sb.append("-----BEGIN CERTIFICATE-----\n");
    sb.append(new String(base64));
    sb.append("-----END CERTIFICATE-----");
    return sb.toString();
}