Example usage for org.apache.commons.codec.binary StringUtils newString

List of usage examples for org.apache.commons.codec.binary StringUtils newString

Introduction

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

Prototype

public static String newString(final byte[] bytes, final String charsetName) 

Source Link

Document

Constructs a new String by decoding the specified array of bytes using the given charset.

Usage

From source file:com.mirth.connect.server.attachments.MirthAttachmentHandler.java

public String reAttachMessage(ImmutableConnectorMessage message) {
    String messageData = null;//from  ww  w .j  a va2s  .  c  om
    if (message.getEncoded() != null && message.getEncoded().getContent() != null) {
        messageData = message.getEncoded().getContent();
    } else if (message.getRaw() != null) {
        messageData = message.getRaw().getContent();
    }

    return StringUtils.newString(reAttachMessage(messageData, message, Constants.ATTACHMENT_CHARSET, false),
            Constants.ATTACHMENT_CHARSET);
}

From source file:com.mirth.connect.server.attachments.MirthAttachmentHandler.java

public String reAttachMessage(String raw, ImmutableConnectorMessage message) {
    return StringUtils.newString(reAttachMessage(raw, message, Constants.ATTACHMENT_CHARSET, false),
            Constants.ATTACHMENT_CHARSET);
}

From source file:com.mirth.connect.connectors.jdbc.JdbcUtils.java

/**
 * Get an array of parameter values using a TemplateValueReplacer based on the given list of
 * parameter keys, using a ConnectorMessage and/or Map<String, Object> to look up the
 * values.//from   w  ww. j a  v a2s  .  c  o  m
 * 
 * @param paramNames
 *            A list of the parameter names to look up
 * @param channelId
 *            A channel id to use for the default context in the TemplateValueReplacer
 * @param connectorMessage
 *            A connector message to reference when looking up values
 * @param map
 *            A String/Object map to reference when looking up values
 * @param attachmentHandler
 *            An attachment handler to use for re-attaching attachment data in the parameter
 *            values
 * @return
 */
public static Object[] getParameters(List<String> paramNames, String channelId, String channelName,
        ConnectorMessage connectorMessage, Map<String, Object> map,
        AttachmentHandlerProvider attachmentHandlerProvider) {
    Object[] params = new Object[paramNames.size()];
    TemplateValueReplacer replacer = new TemplateValueReplacer();
    int i = 0;

    for (String paramName : paramNames) {
        String key = paramName.substring(2, paramName.length() - 1);
        Object value;

        if (map != null && map.containsKey(key)) {
            value = map.get(key);
        } else if (connectorMessage != null) {
            value = replacer.replaceValues(paramName, connectorMessage);
        } else {
            value = replacer.replaceValues(paramName, channelId, channelName);
        }

        if (attachmentHandlerProvider != null
                && MirthAttachmentHandlerProvider.hasAttachmentKeys(value.toString())) {
            value = StringUtils.newString(attachmentHandlerProvider.reAttachMessage(value.toString(),
                    connectorMessage, Constants.ATTACHMENT_CHARSET, false), Constants.ATTACHMENT_CHARSET);
        }

        params[i++] = value;
    }

    return params;
}

From source file:com.mirth.connect.util.MessageEncryptionUtil.java

public static void decryptAttachment(Attachment attachment, Encryptor encryptor) {
    if (attachment != null && attachment.getContent() != null && attachment.isEncrypted()) {
        String decryptedByteString = encryptor
                .decrypt(StringUtils.newString(attachment.getContent(), Constants.ATTACHMENT_CHARSET));

        attachment.setContent(com.mirth.connect.donkey.util.StringUtil
                .getBytesUncheckedChunked(decryptedByteString, Constants.ATTACHMENT_CHARSET));
        attachment.setEncrypted(false);/*  ww  w  . j  a  va  2s  .  c  o m*/
    }
}

From source file:com.mirth.connect.connectors.vm.VmDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage message) {
    VmDispatcherProperties vmDispatcherProperties = (VmDispatcherProperties) connectorProperties;

    String targetChannelId = vmDispatcherProperties.getChannelId();
    String currentChannelId = getChannelId();

    eventController.dispatchEvent(new ConnectionStatusEvent(currentChannelId, getMetaDataId(),
            getDestinationName(), ConnectionStatusEventType.SENDING, "Target Channel: " + targetChannelId));

    String responseData = null;//w  w  w. jav a  2s .c o m
    String responseError = null;
    String responseStatusMessage = null;
    Status responseStatus = Status.QUEUED; // Always set the status to QUEUED
    boolean validateResponse = false;

    try {
        if (!targetChannelId.equals("none")) {
            boolean isBinary = ExtensionController.getInstance().getDataTypePlugins()
                    .get(this.getOutboundDataType().getType()).isBinary();
            byte[] data = getAttachmentHandlerProvider().reAttachMessage(
                    vmDispatcherProperties.getChannelTemplate(), message, Constants.ATTACHMENT_CHARSET,
                    isBinary);

            RawMessage rawMessage;

            if (isBinary) {
                rawMessage = new RawMessage(data);
            } else {
                rawMessage = new RawMessage(StringUtils.newString(data, Constants.ATTACHMENT_CHARSET));
            }

            Map<String, Object> rawSourceMap = rawMessage.getSourceMap();
            Map<String, Object> sourceMap = message.getSourceMap();

            /*
             * Build the lists of source channel and message Ids if this channel is not the
             * start of the chain.
             */
            List<String> sourceChannelIds = getSourceChannelIds(sourceMap);
            List<Long> sourceMessageIds = getSourceMessageIds(sourceMap);

            // Add the current channelId to the chain if it is built
            if (sourceChannelIds != null) {
                sourceChannelIds.add(currentChannelId);
                rawSourceMap.put(SOURCE_CHANNEL_IDS, sourceChannelIds);
            }

            // Add the current messageId to the chain if it is built
            if (sourceMessageIds != null) {
                sourceMessageIds.add(message.getMessageId());
                rawSourceMap.put(SOURCE_MESSAGE_IDS, sourceMessageIds);
            }

            // Always store the originating channelId and messageId
            rawSourceMap.put(SOURCE_CHANNEL_ID, currentChannelId);
            rawSourceMap.put(SOURCE_MESSAGE_ID, message.getMessageId());

            List<String> keys = vmDispatcherProperties.getMapVariables();
            if (CollectionUtils.isNotEmpty(keys)) {
                for (String key : keys) {
                    Object value = getMapValue(message, key);
                    if (value != null) {
                        rawSourceMap.put(key, value);
                    }
                }
            }

            // Remove the reference to the raw message so its doesn't hold the entire message in memory.
            data = null;

            DispatchResult dispatchResult = ControllerFactory.getFactory().createEngineController()
                    .dispatchRawMessage(targetChannelId, rawMessage, false, true);

            if (dispatchResult != null && dispatchResult.getSelectedResponse() != null) {
                // If a response was returned from the channel then use that message
                responseData = dispatchResult.getSelectedResponse().getMessage();
            }

            validateResponse = vmDispatcherProperties.getDestinationConnectorProperties().isValidateResponse();
        }

        responseStatus = Status.SENT;
        responseStatusMessage = "Message routed successfully to channel id: " + targetChannelId;
    } catch (Throwable e) {
        eventController.dispatchEvent(new ErrorEvent(currentChannelId, getMetaDataId(), message.getMessageId(),
                ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(),
                "Error routing message to channel id: " + targetChannelId, e));
        responseStatusMessage = ErrorMessageBuilder
                .buildErrorResponse("Error routing message to channel id: " + targetChannelId, e);
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                "Error routing message to channel id: " + targetChannelId, e);
    } finally {
        eventController.dispatchEvent(new ConnectionStatusEvent(currentChannelId, getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:com.mirth.connect.util.MessageEncryptionUtil.java

public static void encryptAttachment(Attachment attachment, Encryptor encryptor) {
    if (attachment != null && attachment.getContent() != null && !attachment.isEncrypted()) {
        String encryptedContents = encryptor
                .encrypt(StringUtils.newString(attachment.getContent(), Constants.ATTACHMENT_CHARSET));

        attachment.setContent(com.mirth.connect.donkey.util.StringUtil
                .getBytesUncheckedChunked(encryptedContents, Constants.ATTACHMENT_CHARSET));
        attachment.setEncrypted(true);//from  w  w  w  . j  a v  a 2  s  .  c om
    }
}

From source file:com.mirth.connect.server.util.AttachmentUtil.java

public static byte[] reAttachMessage(String raw, ImmutableConnectorMessage connectorMessage,
        String charsetEncoding, boolean binary) {
    try {//  w  w w.  j a  v a 2 s.co  m
        Map<Integer, Map<Integer, Object>> replacementObjects = new TreeMap<Integer, Map<Integer, Object>>();
        // Determine the buffersize during the first pass for better memory performance
        int bufferSize = raw.length();
        int index = 0;
        int endIndex;
        // Initialize the objects here so only one retrieval of the attachment content is ever needed.
        byte[] dicomObject = null;
        Map<String, Attachment> attachmentMap = null;

        // Handle the special case if only a dicom message is requested. 
        // In this case we can skip any byte appending and thus do not need to base64 encode the dicom object
        // if the type is binary.
        if (raw.trim().equals(PREFIX + DICOM_KEY + SUFFIX)) {
            dicomObject = DICOMUtil.getDICOMRawBytes(connectorMessage);

            if (!binary) {
                dicomObject = Base64Util.encodeBase64(dicomObject);
            }

            return dicomObject;
        }

        // Check the raw string in one pass for any attachments.
        // Stores the start and end indices to replace, along with the attachment content.
        while ((index = raw.indexOf(PREFIX, index)) != -1) {
            if (raw.startsWith(DICOM_KEY + SUFFIX, index + PREFIX.length())) {
                if (dicomObject == null) {
                    // Unfortunately, if the dicom data needs to appended to other base64 data, it must be done so in base64.
                    dicomObject = Base64Util.encodeBase64(DICOMUtil.getDICOMRawBytes(connectorMessage));
                }

                endIndex = index + PREFIX.length() + DICOM_KEY.length() + SUFFIX.length();

                Map<Integer, Object> replacementMap = new HashMap<Integer, Object>();
                replacementMap.put(KEY_END_INDEX, endIndex);
                replacementMap.put(KEY_DATA, dicomObject);
                replacementObjects.put(index, replacementMap);

                bufferSize += dicomObject.length;
                index += endIndex - index;
            } else if (raw.startsWith(ATTACHMENT_KEY, index + PREFIX.length())) {
                if (attachmentMap == null) {
                    List<Attachment> list = getMessageAttachments(connectorMessage);

                    // Store the attachments in a map with the attachment's Id as the key
                    attachmentMap = new HashMap<String, Attachment>();
                    for (Attachment attachment : list) {
                        attachmentMap.put(attachment.getId(), attachment);
                    }
                }

                int attachmentIdStartIndex = index + PREFIX.length() + ATTACHMENT_KEY.length();
                int attachmentIdEndIndex = attachmentIdStartIndex + ATTACHMENT_ID_LENGTH;
                endIndex = attachmentIdEndIndex + SUFFIX.length();
                String attachmentId = raw.substring(attachmentIdStartIndex,
                        attachmentIdStartIndex + ATTACHMENT_ID_LENGTH);

                if (raw.substring(attachmentIdEndIndex, endIndex).equals(SUFFIX)) {
                    Map<Integer, Object> replacementMap = new HashMap<Integer, Object>();
                    replacementMap.put(KEY_END_INDEX, endIndex);

                    if (attachmentMap.containsKey(attachmentId)) {
                        Attachment attachment = attachmentMap.get(attachmentId);
                        replacementMap.put(KEY_DATA, attachment.getContent());

                        bufferSize += attachment.getContent().length;
                    } else {
                        replacementMap.put(KEY_DATA, new byte[0]);
                    }

                    replacementObjects.put(index, replacementMap);
                }
            } else {
                endIndex = index + PREFIX.length();
            }

            index += endIndex - index;
        }
        // Release the object pointers of the attachment content so they aren't held in memory for the entire method
        dicomObject = null;
        attachmentMap = null;

        // Initialize the stream's buffer size. The buffer size will always be slightly large than needed,
        // because the template keys are never removed from the buffer size.
        // It is not worth doing any extra calculations for the amount of memory saved. 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize);

        int segmentStartIndex = 0;
        for (Map.Entry<Integer, Map<Integer, Object>> entry : replacementObjects.entrySet()) {
            int startReplacementIndex = entry.getKey();
            int endReplacementIndex = (Integer) entry.getValue().get(KEY_END_INDEX);
            byte[] data = (byte[]) entry.getValue().get(KEY_DATA);

            // Allows the memory used by the attachments to be released at the end of the loop
            entry.getValue().clear();

            byte[] templateSegment;
            // If the data is binary, the content should be in base64, so using US-ASCII as the charset encoding should be sufficient.
            if (binary) {
                templateSegment = StringUtils
                        .getBytesUsAscii(raw.substring(segmentStartIndex, startReplacementIndex));
            } else {
                templateSegment = StringUtil.getBytesUncheckedChunked(
                        raw.substring(segmentStartIndex, startReplacementIndex), Constants.ATTACHMENT_CHARSET);
            }

            baos.write(templateSegment);
            baos.write(data);

            segmentStartIndex = endReplacementIndex;
        }

        byte[] templateSegment;
        if (binary) {
            templateSegment = StringUtils.getBytesUsAscii(raw.substring(segmentStartIndex));
        } else {
            templateSegment = StringUtil.getBytesUncheckedChunked(raw.substring(segmentStartIndex),
                    Constants.ATTACHMENT_CHARSET);
        }

        byte[] combined;
        // If there are no attachments, don't bother writing to the output stream.
        if (segmentStartIndex == 0) {
            combined = templateSegment;
        } else {
            // Write the segment after the last replacement.
            baos.write(templateSegment);

            combined = baos.toByteArray();
            // Release the memory used by the byte array stream. ByteArrayOutputStreams do not need to be closed. 
            baos = null;
        }

        templateSegment = null;

        // If binary, the content should be in base64 so it is necessary to decode the data.
        if (binary) {
            combined = Base64Util.decodeBase64(combined);
        } else if (charsetEncoding != null
                && !charsetEncoding.toUpperCase().equals(Constants.ATTACHMENT_CHARSET.toUpperCase())) {
            // Convert the byte array to a string using the internal encoding.
            String combinedString = StringUtils.newString(combined, Constants.ATTACHMENT_CHARSET);
            // First release the reference to the old byte data so it can be reallocated if necessary.
            combined = null;
            // Convert the string to a byte array using the requested encoding
            combined = StringUtil.getBytesUncheckedChunked(combinedString, charsetEncoding);
        }

        return combined;
    } catch (Exception e) {
        logger.error("Error reattaching attachments", e);
        return null;
    }
}

From source file:com.mirth.connect.server.util.MessageAttachmentUtil.java

public static byte[] reAttachMessage(String raw, ImmutableConnectorMessage connectorMessage,
        String charsetEncoding, boolean binary) {
    try {/*from ww  w. j  ava2 s  .c  o m*/
        Map<Integer, Map<Integer, Object>> replacementObjects = new TreeMap<Integer, Map<Integer, Object>>();
        // Determine the buffersize during the first pass for better memory performance
        int bufferSize = raw.length();
        int index = 0;
        int endIndex;
        // Initialize the objects here so only one retrieval of the attachment content is ever needed.
        byte[] dicomObject = null;
        Map<String, Attachment> attachmentMap = null;

        // Handle the special case if only a dicom message is requested. 
        // In this case we can skip any byte appending and thus do not need to base64 encode the dicom object
        // if the type is binary.
        if (raw.trim().equals(PREFIX + DICOM_KEY + SUFFIX)) {
            dicomObject = DICOMMessageUtil.getDICOMRawBytes(connectorMessage);

            if (!binary) {
                dicomObject = Base64Util.encodeBase64(dicomObject);
            }

            return dicomObject;
        }

        // Check the raw string in one pass for any attachments.
        // Stores the start and end indices to replace, along with the attachment content.
        while ((index = raw.indexOf(PREFIX, index)) != -1) {
            if (raw.startsWith(DICOM_KEY + SUFFIX, index + PREFIX.length())) {
                if (dicomObject == null) {
                    // Unfortunately, if the dicom data needs to appended to other base64 data, it must be done so in base64.
                    dicomObject = Base64Util.encodeBase64(DICOMMessageUtil.getDICOMRawBytes(connectorMessage));
                }

                endIndex = index + PREFIX.length() + DICOM_KEY.length() + SUFFIX.length();

                Map<Integer, Object> replacementMap = new HashMap<Integer, Object>();
                replacementMap.put(KEY_END_INDEX, endIndex);
                replacementMap.put(KEY_DATA, dicomObject);
                replacementObjects.put(index, replacementMap);

                bufferSize += dicomObject.length;
                index += endIndex - index;
            } else if (raw.startsWith(ATTACHMENT_KEY, index + PREFIX.length())) {
                if (attachmentMap == null) {
                    List<Attachment> list = getMessageAttachments(connectorMessage);

                    // Store the attachments in a map with the attachment's Id as the key
                    attachmentMap = new HashMap<String, Attachment>();
                    for (Attachment attachment : list) {
                        attachmentMap.put(attachment.getId(), attachment);
                    }
                }

                int attachmentIdStartIndex = index + PREFIX.length() + ATTACHMENT_KEY.length();
                int attachmentIdEndIndex = attachmentIdStartIndex + ATTACHMENT_ID_LENGTH;
                endIndex = attachmentIdEndIndex + SUFFIX.length();
                String attachmentId = raw.substring(attachmentIdStartIndex,
                        attachmentIdStartIndex + ATTACHMENT_ID_LENGTH);

                if (raw.substring(attachmentIdEndIndex, endIndex).equals(SUFFIX)) {
                    Map<Integer, Object> replacementMap = new HashMap<Integer, Object>();
                    replacementMap.put(KEY_END_INDEX, endIndex);

                    if (attachmentMap.containsKey(attachmentId)) {
                        Attachment attachment = attachmentMap.get(attachmentId);
                        replacementMap.put(KEY_DATA, attachment.getContent());

                        bufferSize += attachment.getContent().length;
                    } else {
                        replacementMap.put(KEY_DATA, new byte[0]);
                    }

                    replacementObjects.put(index, replacementMap);
                }
            } else {
                endIndex = index + PREFIX.length();
            }

            index += endIndex - index;
        }
        // Release the object pointers of the attachment content so they aren't held in memory for the entire method
        dicomObject = null;
        attachmentMap = null;

        // Initialize the stream's buffer size. The buffer size will always be slightly large than needed,
        // because the template keys are never removed from the buffer size.
        // It is not worth doing any extra calculations for the amount of memory saved. 
        ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize);

        int segmentStartIndex = 0;
        for (Map.Entry<Integer, Map<Integer, Object>> entry : replacementObjects.entrySet()) {
            int startReplacementIndex = entry.getKey();
            int endReplacementIndex = (Integer) entry.getValue().get(KEY_END_INDEX);
            byte[] data = (byte[]) entry.getValue().get(KEY_DATA);

            // Allows the memory used by the attachments to be released at the end of the loop
            entry.getValue().clear();

            byte[] templateSegment;
            // If the data is binary, the content should be in base64, so using US-ASCII as the charset encoding should be sufficient.
            if (binary) {
                templateSegment = StringUtils
                        .getBytesUsAscii(raw.substring(segmentStartIndex, startReplacementIndex));
            } else {
                templateSegment = StringUtil.getBytesUncheckedChunked(
                        raw.substring(segmentStartIndex, startReplacementIndex), Constants.ATTACHMENT_CHARSET);
            }

            baos.write(templateSegment);
            baos.write(data);

            segmentStartIndex = endReplacementIndex;
        }

        byte[] templateSegment;
        if (binary) {
            templateSegment = StringUtils.getBytesUsAscii(raw.substring(segmentStartIndex));
        } else {
            templateSegment = StringUtil.getBytesUncheckedChunked(raw.substring(segmentStartIndex),
                    Constants.ATTACHMENT_CHARSET);
        }

        byte[] combined;
        // If there are no attachments, don't bother writing to the output stream.
        if (segmentStartIndex == 0) {
            combined = templateSegment;
        } else {
            // Write the segment after the last replacement.
            baos.write(templateSegment);

            combined = baos.toByteArray();
            // Release the memory used by the byte array stream. ByteArrayOutputStreams do not need to be closed. 
            baos = null;
        }

        templateSegment = null;

        // If binary, the content should be in base64 so it is necessary to decode the data.
        if (binary) {
            combined = Base64Util.decodeBase64(combined);
        } else if (charsetEncoding != null
                && !charsetEncoding.toUpperCase().equals(Constants.ATTACHMENT_CHARSET.toUpperCase())) {
            // Convert the byte array to a string using the internal encoding.
            String combinedString = StringUtils.newString(combined, Constants.ATTACHMENT_CHARSET);
            // First release the reference to the old byte data so it can be reallocated if necessary.
            combined = null;
            // Convert the string to a byte array using the requested encoding
            combined = StringUtil.getBytesUncheckedChunked(combinedString, charsetEncoding);
        }

        return combined;
    } catch (Exception e) {
        logger.error("Error reattaching attachments", e);
        return null;
    }
}

From source file:com.mirth.connect.server.util.AttachmentUtil.java

public static String reAttachMessage(ImmutableConnectorMessage message) {
    String messageData = null;//w  w w  .j  av  a  2  s . co m
    if (message.getEncoded() != null && message.getEncoded().getContent() != null) {
        messageData = message.getEncoded().getContent();
    } else if (message.getRaw() != null) {
        messageData = message.getRaw().getContent();
    }

    return StringUtils.newString(reAttachMessage(messageData, message, Constants.ATTACHMENT_CHARSET, false),
            Constants.ATTACHMENT_CHARSET);
}

From source file:com.mirth.connect.server.util.AttachmentUtil.java

public static String reAttachMessage(String raw, ImmutableConnectorMessage message) {
    return StringUtils.newString(reAttachMessage(raw, message, Constants.ATTACHMENT_CHARSET, false),
            Constants.ATTACHMENT_CHARSET);
}