All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.seeq.utilities.SeeqStrings Maven / Gradle / Ivy

The newest version!
package com.seeq.utilities;

import java.util.Locale;
import java.util.UUID;

import org.owasp.html.HtmlPolicyBuilder;
import org.owasp.html.PolicyFactory;

import lombok.experimental.UtilityClass;

@UtilityClass
public class SeeqStrings {
    public final String EMPTY_GUID = "00000000-0000-0000-0000-000000000000";
    private static final PolicyFactory DEFAULT_HTML_POLICY = new HtmlPolicyBuilder()
            .allowCommonInlineFormattingElements()
            .allowCommonBlockElements()
            .allowStandardUrlProtocols()
            .allowElements("a", "pre", "span", "i", "hr", "figure")
            .allowAttributes("class", "style").onElements("figure")
            .allowAttributes("class").onElements("hr")
            .allowAttributes("style", "id", "class")
            .onElements("span", "p", "div", "pre", "h1", "h2", "h3", "h4", "i")
            .allowAttributes("href", "target").onElements("a")
            .requireRelsOnLinks("nofollow", "noopener", "noreferrer")
            .allowElements("img")
            .allowAttributes("alt", "src", "id").onElements("img")
            .allowAttributes(SeeqNames.TopicDocumentAttributes.DataSeeqContent,
                    SeeqNames.TopicDocumentAttributes.DataSeeqContentPending,
                    "data-seeq-workbookid", "data-seeq-worksheetid", "data-seeq-workstepid",
                    "data-seeq-datevariableid", "data-seeq-size", "data-seeq-shape", "data-seeq-scale",
                    "data-seeq-customheight", "data-seeq-customwidth", "data-seeq-contentwidth",
                    "data-seeq-contentheight", "data-seeq-content-for", "data-seeq-autoupdate")
            .onElements("img")
            .allowAttributes("border", "height", "width", "style", "class", "no-margin", "width-percent",
                    SeeqNames.TopicDocumentAttributes.DataSeeqContentNoMargin,
                    SeeqNames.TopicDocumentAttributes.DataSeeqContentBorder,
                    SeeqNames.TopicDocumentAttributes.DataSeeqContentHeight,
                    SeeqNames.TopicDocumentAttributes.DataSeeqContentPercentWidth,
                    SeeqNames.TopicDocumentAttributes.DataSeeqContentWidth,
                    SeeqNames.TopicDocumentAttributes.DataSeeqRestrictContentHeight,
                    SeeqNames.TopicDocumentAttributes.DataSeeqContentPropertyOverrides)
            .onElements("img")
            .allowElements("table", "tr", "td", "th", "colgroup", "caption", "col", "thead", "tbody", "tfoot")
            .allowAttributes("summary").onElements("table")
            .allowAttributes("align", "valign", "style", "class").onElements("table", "tr", "td", "th", "colgroup",
                    "col", "thead", "tbody", "tfoot")
            .allowAttributes("rowspan", "colspan").onElements("td", "th")
            .allowAttributes("contenteditable").onElements("table")
            .allowElements("figure")
            .allowAttributes("class").onElements("figure")
            .allowAttributes(SeeqNames.TopicDocumentAttributes.DataSeeqDateRangeId,
                    SeeqNames.TopicDocumentAttributes.DataSeeqDateRangeFormat,
                    SeeqNames.TopicDocumentAttributes.DataSeeqDateRangeContent)
            .onElements("span")
            .allowAttributes(SeeqNames.TopicDocumentAttributes.DataSeeqAssetSelectionId,
                    SeeqNames.TopicDocumentAttributes.DataSeeqAssetSelectionDepthLevel)
            .onElements("span")
            .allowAttributes(SeeqNames.TopicDocumentAttributes.DataSeeqIframeContentUrl,
                    SeeqNames.TopicDocumentAttributes.DataSeeqIframeContentHeight,
                    SeeqNames.TopicDocumentAttributes.DataSeeqIframeContentWidth)
            // Allowed on divs to support original iframe wrapper (CRAB-38387)
            .onElements("span", "div")
            .toFactory();

    private static final PolicyFactory REMOVE_HTML_POLICY = new HtmlPolicyBuilder().toFactory();


    /**
     * A variant of Guava's Preconditions formatter that substitutes each {@code {}} in {@code template} with an
     * argument. Intended to match Slf4j's style. These are matched by position: the first {@code {}} gets {@code
     * args[0]}, etc. If there are more arguments than place holders, the unmatched arguments will be appended to the
     * end of the formatted message in square braces.
     *
     * @param template
     *         A string containing 0 or more {@code {}} place holders. null is treated as "null".
     * @param args
     *         The arguments to be substituted into the message template. Arguments are converted to strings using
     *         {@link String#valueOf(Object)}. Arguments can be null.
     */
    public String format(String template, Object... args) {
        template = String.valueOf(template); // null -> "null"

        args = args == null ? new Object[] { "(Object[])null" } : args;

        // Start substituting the arguments into the {} placeholders
        StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
        int templateStart = 0;
        int i = 0;
        while (i < args.length) {
            int placeholderStart = template.indexOf("{}", templateStart);
            if (placeholderStart == -1) {
                break;
            }
            builder.append(template, templateStart, placeholderStart);
            builder.append(args[i++]);
            templateStart = placeholderStart + 2;
        }
        builder.append(template, templateStart, template.length());

        // If we run out of placeholders, append the extra args in square braces
        if (i < args.length) {
            builder.append(" [");
            builder.append(args[i++]);
            while (i < args.length) {
                builder.append(", ");
                builder.append(args[i++]);
            }
            builder.append(']');
        }

        return builder.toString();
    }

    /**
     * Some interfaces, such as the BatchSignalDriver specify a String id, but internally many connectors use
     * {@link UUID} * ids to store the data. This method should be used to parse data ids into UUIDs as it will ensure
     * that if the * id is not a UUID it will be converted into one. See CRAB-8909.
     *
     * @param id
     *         A string ID to encode as a UUID using an MD5 hash.
     * @return The UUID encoding of the string id.
     */
    public static UUID parseUUID(String id) {
        try {
            return UUID.fromString(id);
        } catch (IllegalArgumentException e) {
            return UUID.nameUUIDFromBytes(id.getBytes());
        }
    }

    /**
     * Convert a GUID to its uppercase string representation
     *
     * @param guid
     *         The {@link UUID} to convert to a string representation
     * @return An uppercase string representation of the GUID
     */
    public static String getGuidString(UUID guid) {
        return guid.toString().toUpperCase(Locale.ROOT);
    }

    /**
     * Sanitizes the passed string using the OWASP Java HTML Sanitizer. This will filter out script blocks, make sure
     * only certain attributes are allowed, add rel attribute to links specifying the browser not to pass on any
     * information etc.
     *
     * @param html
     *         The string to sanitize
     * @return The sanitized string
     */
    public static String sanitizeHtml(String html) {
        // The sanitizer incorrectly transforms html5 empty elements to be self closing (e.g. )
        // and there is no way to configure it not to, so we undo it with a regex before returning the string.
        return DEFAULT_HTML_POLICY.sanitize(html).replaceAll("(<(?:img|br|hr).*?) />", "$1>");
    }

    /**
     * Removes HTML from the passed string using the OWASP Java HTML Sanitizer. This should only leave plaintext.
     *
     * @param html
     *         The string to de-html
     * @return The de-htmled string
     */
    public static String removeHtml(String html) {
        return REMOVE_HTML_POLICY.sanitize(html);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy