com.formkiq.core.util.Strings.java Source code

Java tutorial

Introduction

Here is the source code for com.formkiq.core.util.Strings.java

Source

/*
 * Copyright (C) 2016 FormKiQ Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.formkiq.core.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.util.StringUtils;

/**
 * String helper utilities.
 *
 */
public final class Strings {

    /** UTF-8 String. */
    public static final String UTF8 = "UTF-8";

    /** UTF-8 Charset. */
    public static final Charset CHARSET_UTF8 = Charset.forName(UTF8);

    /** Default deliminator to use to encode strings. */
    public static final String DEFAULT_DELIM = ":";

    /** Regex to extract label / value. */
    private static final Pattern EXTRACT_LABEL_VALUE = Pattern.compile("^(.*)\\[(.*)\\]$");

    /** Start String of Base64 Image Header. */
    private static final String BASE64_IMAGE_HEADER = "data:";

    /**
     * String has at least 1 letter.
     * @param s {@link String}
     * @return boolean
     */
    public static boolean hasAtLeast1Letter(final String s) {
        return s.matches(".*[a-zA-Z]+.*");
    }

    /**
     * Converts Base64 String to byte[] image.
     * @param base64String {@link String}
     * @return {@link Pair}
     * @throws IOException IOException
     */
    public static Pair<byte[], String> base64StringToImg(final String base64String) throws IOException {

        int headerLen = BASE64_IMAGE_HEADER.length();

        if (base64String.startsWith(BASE64_IMAGE_HEADER) && base64String.length() > headerLen) {

            int semicolon = base64String.indexOf(";");
            int comma = base64String.indexOf(",", semicolon);

            String formatName = base64String.substring(headerLen, semicolon);
            int pos = formatName.lastIndexOf("/");
            if (pos != -1) {
                formatName = formatName.substring(pos + 1);
            }

            String base64Image = base64String.substring(comma + 1);

            BufferedImage img = ImageIO
                    .read(new ByteArrayInputStream(java.util.Base64.getDecoder().decode(base64Image)));

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(img, formatName, baos);
            byte[] bytes = baos.toByteArray();
            return Pair.of(bytes, formatName);
        }

        throw new IllegalArgumentException("Invalid Image base64 String");
    }

    /**
     * Convert Bytes to Img Src.
     * @param data byte[]
     * @param format {@link String}
     * @return {@link String}
     */
    public static String bytesToImg(final byte[] data, final String format) {
        return !ArrayUtils.isEmpty(data)
                ? "data:image/" + format + ";base64," + java.util.Base64.getEncoder().encodeToString(data)
                : "";
    }

    /**
     * Decodes string using deliminator and Base64.
     * @param base64 {@link String}
     * @return String[]
     */
    public static String decode(final String base64) {
        byte[] bytes = Base64.decodeBase64(base64);
        String s = new String(bytes, StandardCharsets.UTF_8);
        return s;
    }

    /**
     * Decodes string using deliminator and Base64.
     * @param base64 {@link String}
     * @param deliminator {@link String}
     * @return String[]
     */
    public static String[] decode(final String base64, final String deliminator) {
        return decode(base64).split(deliminator);
    }

    /**
     * Encodes string using Base64.
     * @param data byte[]
     * @return String[]
     */
    public static String encode(final byte[] data) {
        return Base64.encodeBase64String(data);
    }

    /**
     * Encodes two strings together using deliminator and Base64.
     * @param s0 {@link String}
     * @param s1 {@link String}
     * @param deliminator {@link String}
     * @return {@link String}
     */
    public static String encode(final String s0, final String s1, final String deliminator) {

        String encoded = s0 + deliminator + s1;

        byte[] bytes = Base64.encodeBase64(encoded.getBytes(StandardCharsets.UTF_8));
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * Compares values for match.
     *
     * @param s1 {@link String}
     * @param s2 {@link String}
     * @return boolean
     */
    public static boolean eq(final String s1, final String s2) {
        return extractLabelAndValue(s1).getRight().equals(extractLabelAndValue(s2).getRight());
    }

    /**
     * Compares values for match.
     *
     * @param list {@link Collection}
     * @param s2 {@link String}
     * @return boolean
     */
    public static boolean contains(final Collection<String> list, final String s2) {

        if (!org.apache.commons.collections.CollectionUtils.isEmpty(list)) {
            for (String s1 : list) {
                if (eq(s1, s2)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Extract Label / Value from String.
     * @param s {@link String}
     * @return {@link Pair}
     */
    public static Pair<String, String> extractLabelAndValue(final String s) {

        if (!StringUtils.isEmpty(s)) {

            Matcher m = EXTRACT_LABEL_VALUE.matcher(s);
            if (m.matches()) {
                return Pair.of(m.group(1), m.group(2));
            }

            return Pair.of(s, s);
        }

        return Pair.of("", "");
    }

    /**
     * Generate Token based off of Offset / Max Results.
     * @param offset int
     * @param maxResults int
     * @return {@link String}
     */
    public static String generateOffsetToken(final int offset, final int maxResults) {
        return encode("" + offset, "" + maxResults, DEFAULT_DELIM);
    }

    /**
     * Get encoded bytes.
     * @param s {@link String}
     * @return byte[]
     */
    public static byte[] getBytes(final String s) {
        return s.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * Get Max Results from Token.
     * @param token {@link String}
     * @param defaultMaxResults int
     * @return int
     */
    public static int getMaxResults(final String token, final int defaultMaxResults) {

        try {
            String s = decode(token, DEFAULT_DELIM)[1];
            return Integer.parseInt(s);
        } catch (NullPointerException | ArrayIndexOutOfBoundsException | NumberFormatException e) {
            return defaultMaxResults;
        }
    }

    /**
     * Get Offset from token.
     * @param token {@link String}
     * @return int
     */
    public static int getOffset(final String token) {
        try {
            String s = decode(token, DEFAULT_DELIM)[0];
            return Integer.parseInt(s);
        } catch (NullPointerException | ArrayIndexOutOfBoundsException | NumberFormatException e) {
            return 0;
        }
    }

    /**
     * Converts bytes to Base64 String.
     * @param data byte[]
     * @return {@link String}
     * @throws IOException IOException
     */
    public static String imageToBase64(final byte[] data) throws IOException {
        return new String(Base64.encodeBase64(data), StandardCharsets.UTF_8);
    }

    /**
     * Returns whether String is empty or equals 'null'.
     * @param s {@link String}
     * @return boolean
     */
    public static boolean isEmpty(final String s) {
        return StringUtils.isEmpty(s) || "null".equals(s);
    }

    /**
     * Does string start and end with '' or "".
     * @param s {@link String}
     * @return boolean
     */
    public static boolean isQuotedString(final String s) {
        return (s.startsWith("\"") && s.endsWith("\"") || (s.startsWith("'") && s.endsWith("'")));
    }

    /**
     * Whether string is a UUID.
     * @param key {@link String}
     * @return boolean
     */
    public static boolean isUUID(final String key) {

        try {
            UUID.fromString(key);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * Split string by new line.
     * @param s {@link String}
     * @return String[]
     */
    public static String[] splitByNewLine(final String s) {
        return StringUtils.hasText(s) ? s.split("\\r?\\n") : new String[] {};
    }

    /**
     * Strip Quotes from String.
     * @param string {@link String}
     * @return {@link String}
     */
    public static String stripQuotes(final String string) {

        if (isQuotedString(string)) {
            return string.substring(1, string.length() - 1);
        }

        return string;
    }

    /**
     * To String from byte[].
     * @param bytes byte[]
     * @return {@link String}
     */
    public static String toString(final byte[] bytes) {
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * private constructor.
     */
    private Strings() {
    }
}