Example usage for org.apache.commons.lang3 StringUtils toEncodedString

List of usage examples for org.apache.commons.lang3 StringUtils toEncodedString

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils toEncodedString.

Prototype

public static String toEncodedString(final byte[] bytes, final Charset charset) 

Source Link

Document

Converts a byte[] to a String using the specified character encoding.

Usage

From source file:dumpsection.util.Util.java

public static String[] stringArrayCharSetDefaultToDesired(String[] src, Charset charset)
        throws UnsupportedEncodingException {
    Charset cs = Charset.defaultCharset();
    List<String> strs = Arrays.asList(src);
    List<String> strd = new ArrayList<>();
    for (String str : strs) {
        strd.add(StringUtils.toEncodedString(str.getBytes(cs), Charset.forName("UTF-8")));
    }//w  ww. j  a  v  a  2  s  .co  m
    return strd.toArray(src);
}

From source file:io.stallion.testing.MockOutputStream.java

public String toString() {
    return StringUtils.toEncodedString(writer.toByteArray(), Charset.forName("UTF-8"));
}

From source file:com.comcast.viper.flume2storm.event.F2SEvent.java

/**
 * @see java.lang.Object#toString()/*from  w  w  w.j a va 2s .  c o m*/
 */
@Override
public String toString() {
    ToStringBuilder toStringBuilder = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
            .append("headers", headers);
    String bodyStr = StringUtils.toEncodedString(body, F2SEventFactory.DEFAULT_CHARACTER_SET);
    if (StringUtils.isAsciiPrintable(bodyStr)) {
        toStringBuilder.append("body", bodyStr);
    } else {
        toStringBuilder.append(Hex.encodeHexString(body));
    }
    return toStringBuilder.toString();
}

From source file:com.uber.stream.kafka.chaperone.collector.KafkaIngesterConsumer.java

private void processAuditMsg(final MessageAndMetadata mm) throws Exception {
    JSONObject record = JSON//w  ww .j  a  v  a  2s.  com
            .parseObject(StringUtils.toEncodedString((byte[]) mm.message(), Charset.forName("UTF-8")));

    String topicName = record.getString(AuditMsgField.TOPICNAME.getName());
    if (blacklistedTopics.contains(topicName)) {
        logger.debug("Topic={} is blacklisted", topicName);
        return;
    }

    if (deduplicator != null) {
        String uuid = record.getString(AuditMsgField.UUID.getName());
        String host = record.getString(AuditMsgField.HOSTNAME.getName());
        if (deduplicator.isDuplicated(topicName, mm.partition(), mm.offset(), host, uuid)) {
            return;
        }
    }

    if (enablePersistentStore) {
        auditReporter.submit(mm.topic(), mm.partition(), mm.offset(), record);
    }
}

From source file:com.feilong.core.lang.StringUtil.java

/**
 * Constructs a new <code>String</code> by decoding the specified array of bytes using the given charset.
 *
 * @param bytes/* w ww.  j  a v  a2  s  .co  m*/
 *            The bytes to be decoded into characters, may be <code>null</code>
 * @param charsetType
 *            {@link CharsetType}
 * @return A new <code>String</code> decoded from the specified array of bytes using the given charset,
 *         or <code>null</code> if the input byte array was <code>null</code>.
 * @see String#String(byte[], String)
 * @see "org.apache.commons.lang3.StringUtils#toString(byte[], String)"
 * @see org.apache.commons.lang3.StringUtils#toEncodedString(byte[], Charset)
 * @see "org.apache.commons.codec.binary.StringUtils#newString(byte[], String)"
 * @since 1.3.0
 */
public static String newString(byte[] bytes, String charsetType) {
    return StringUtils.toEncodedString(bytes, Charset.forName(charsetType));
}

From source file:org.finra.herd.core.HerdStringUtils.java

/**
 * Decodes and return the base64 encoded string.
 *
 * @param base64EncodedText the base64 encoded string
 *
 * @return the decoded string/*from  w  w w  .ja v  a 2s .c  o m*/
 */
public static String decodeBase64(String base64EncodedText) {
    return StringUtils.toEncodedString(
            Base64.getDecoder().decode(base64EncodedText.getBytes(StandardCharsets.UTF_8)),
            StandardCharsets.UTF_8);
}

From source file:org.finra.herd.core.HerdStringUtilsTest.java

@Test
public void testDecodeBase64() {
    // Test decode using hard coded values.
    assertEquals("UT_SomeText", HerdStringUtils.decodeBase64("VVRfU29tZVRleHQ="));

    // Test decode using random string and encoder.
    String encodedText = StringUtils.toEncodedString(
            Base64.getEncoder().encode(STRING_VALUE.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
    assertEquals(STRING_VALUE, HerdStringUtils.decodeBase64(encodedText));
}

From source file:org.structr.function.IncludeFunction.java

@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
        throws FrameworkException {

    if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) {

        final SecurityContext securityContext = entity != null ? entity.getSecurityContext()
                : ctx.getSecurityContext();
        final App app = StructrApp.getInstance(securityContext);
        final RenderContext innerCtx = new RenderContext((RenderContext) ctx);
        final List<DOMNode> nodeList = app.nodeQuery(DOMNode.class).andName((String) sources[0]).getAsList();

        DOMNode node = null;//from  w w w. j  a v a2 s .c  o  m

        /**
         * Nodes can be included via their name property These nodes MUST: 1. be unique in name 2. NOT be in the trash => have an ownerDocument AND a parent (public
         * users are not allowed to see the __ShadowDocument__ ==> this check must either be made in a superuser-context OR the __ShadowDocument could be made public?)
         *
         * These nodes can be: 1. somewhere in the pages tree 2. in the shared components 3. both ==> causes a problem because we now have multiple nodes with the same
         * name (one shared component and multiple linking instances of that component)
         *
         * INFOS:
         *
         * - If a DOMNode has "syncedNodes" it MUST BE a shared component - If a DOMNodes "sharedComponent" is set it MUST BE AN INSTANCE of a shared component => Can
         * we safely ignore these? I THINK SO!
         */
        for (final DOMNode n : nodeList) {

            // Ignore nodes in trash
            if (n.getProperty(DOMNode.parent) == null && n.getOwnerDocumentAsSuperUser() == null) {
                continue;
            }

            // IGNORE everything that REFERENCES a shared component!
            if (n.getProperty(DOMNode.sharedComponent) == null) {

                // the DOMNode is either a shared component OR a named node in the pages tree
                if (node == null) {

                    node = n;

                } else {

                    // ERROR: we have found multiple DOMNodes with the same name
                    // TODO: Do we need to remove the nodes from the nodeList which can be ignored? (references to a shared component)
                    return "Ambiguous node name \"" + ((String) sources[0]) + "\" (nodes found: "
                            + StringUtils.join(nodeList, ", ") + ")";

                }

            }

        }

        if (node != null) {

            node.render(innerCtx, 0);

        } else {

            final FileBase file = app.nodeQuery(FileBase.class).andName((String) sources[0]).getFirst();

            if (file != null) {

                final String name = file.getProperty(NodeInterface.name);
                final String contentType = file.getProperty(FileBase.contentType);
                final String charset = StringUtils.substringAfterLast(contentType, "charset=");
                final String extension = StringUtils.substringAfterLast(name, ".");

                if (contentType == null || StringUtils.isBlank(extension)) {

                    return "No valid file type detected. Please make sure " + name
                            + " has a valid content type set or file extension.";

                }

                if (contentType.startsWith("text/css")) {

                    return "<link href=\"" + file.getPath() + "\" rel=\"stylesheet\">";

                } else if (contentType.contains("/javascript")) {

                    return "<script src=\"" + file.getPath() + "\"></script>";

                } else if (contentType.startsWith("image/svg")) {

                    try {
                        final byte[] buffer = new byte[file.getSize().intValue()];
                        IOUtils.read(file.getInputStream(), buffer);
                        return StringUtils.toEncodedString(buffer, Charset.forName(charset));
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }

                    return "<img alt=\"" + name + "\" src=\"" + file.getPath() + "\">";

                } else if (contentType.startsWith("image/")) {

                    return "<img alt=\"" + name + "\" src=\"" + file.getPath() + "\">";

                } else {

                    return "Don't know how to render content type or extension of  " + name + ".";

                }

            }

        }

        return StringUtils.join(innerCtx.getBuffer().getQueue(), "");
    }

    return usage(ctx.isJavaScriptContext());
}

From source file:org.structr.web.function.IncludeFunction.java

@Override
public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources)
        throws FrameworkException {

    try {//from  w w  w .j av a 2s. c o  m

        if (!(arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String)) {

            return null;
        }

        final SecurityContext securityContext = entity != null ? entity.getSecurityContext()
                : ctx.getSecurityContext();
        final App app = StructrApp.getInstance(securityContext);
        final RenderContext innerCtx = new RenderContext((RenderContext) ctx);
        final List<DOMNode> nodeList = app.nodeQuery(DOMNode.class).andName((String) sources[0]).getAsList();

        DOMNode node = null;

        /**
         * Nodes can be included via their name property These nodes MUST: 1. be unique in name 2. NOT be in the trash => have an ownerDocument AND a parent (public
         * users are not allowed to see the __ShadowDocument__ ==> this check must either be made in a superuser-context OR the __ShadowDocument could be made public?)
         *
         * These nodes can be: 1. somewhere in the pages tree 2. in the shared components 3. both ==> causes a problem because we now have multiple nodes with the same
         * name (one shared component and multiple linking instances of that component)
         *
         * INFOS:
         *
         * - If a DOMNode has "syncedNodes" it MUST BE a shared component - If a DOMNodes "sharedComponent" is set it MUST BE AN INSTANCE of a shared component => Can
         * we safely ignore these? I THINK SO!
         */
        for (final DOMNode n : nodeList) {

            // Ignore nodes in trash
            if (n.getProperty(DOMNode.parent) == null && n.getOwnerDocumentAsSuperUser() == null) {
                continue;
            }

            // IGNORE everything that REFERENCES a shared component!
            if (n.getProperty(DOMNode.sharedComponent) == null) {

                // the DOMNode is either a shared component OR a named node in the pages tree
                if (node == null) {

                    node = n;

                } else {

                    // ERROR: we have found multiple DOMNodes with the same name
                    // TODO: Do we need to remove the nodes from the nodeList which can be ignored? (references to a shared component)
                    return "Ambiguous node name \"" + ((String) sources[0]) + "\" (nodes found: "
                            + StringUtils.join(nodeList, ", ") + ")";

                }

            }

        }

        if (node != null) {

            node.render(innerCtx, 0);

        } else {

            final FileBase file = app.nodeQuery(FileBase.class).andName((String) sources[0]).getFirst();

            if (file != null) {

                final String name = file.getProperty(NodeInterface.name);
                final String contentType = file.getProperty(FileBase.contentType);
                final String charset = StringUtils.substringAfterLast(contentType, "charset=");
                final String extension = StringUtils.substringAfterLast(name, ".");

                if (contentType == null || StringUtils.isBlank(extension)) {

                    logger.log(Level.WARNING,
                            "No valid file type detected. Please make sure {0} has a valid content type set or file extension. Parameters: {1}",
                            new Object[] { name, getParametersAsString(sources) });
                    return "No valid file type detected. Please make sure " + name
                            + " has a valid content type set or file extension.";

                }

                if (contentType.startsWith("text/css")) {

                    return "<link href=\"" + file.getPath() + "\" rel=\"stylesheet\">";

                } else if (contentType.contains("/javascript")) {

                    return "<script src=\"" + file.getPath() + "\"></script>";

                } else if (contentType.startsWith("image/svg")) {

                    try {

                        final byte[] buffer = new byte[file.getSize().intValue()];
                        IOUtils.read(file.getInputStream(), buffer);
                        return StringUtils.toEncodedString(buffer, Charset.forName(charset));

                    } catch (IOException ex) {

                        logger.log(Level.WARNING, "Exception for parameters: {0}",
                                getParametersAsString(sources));
                        logger.log(Level.SEVERE, "", ex);

                    }

                    return "<img alt=\"" + name + "\" src=\"" + file.getPath() + "\">";

                } else if (contentType.startsWith("image/")) {

                    return "<img alt=\"" + name + "\" src=\"" + file.getPath() + "\">";

                } else {

                    logger.log(Level.WARNING,
                            "Don't know how to render content type or extension of {0}. Parameters: {1}",
                            new Object[] { name, getParametersAsString(sources) });
                    return "Don't know how to render content type or extension of  " + name + ".";

                }

            }

        }

        return StringUtils.join(innerCtx.getBuffer().getQueue(), "");

    } catch (final IllegalArgumentException e) {

        logParameterError(entity, sources, ctx.isJavaScriptContext());

        return usage(ctx.isJavaScriptContext());

    }
}