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

com.github.dekobon.CloudApiUtils Maven / Gradle / Ivy

package com.github.dekobon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author Elijah Zupancic
 * @since 1.0.0
 */
public class CloudApiUtils {

    /**
     * Finds the first non-null value out of the passed values.
     * @param objects parameters to evaluate
     * @return first object that is not null otherwise null if all objects are null
     */
    @SuppressWarnings("unchecked")
    public static  T firstNonNull(final T... objects) {
        for (T o : objects) {
            if (o != null) {
                return o;
            }
        }

        return null;
    }

    /**
     * Converts an object's toString value to a String. If an empty string, the return null.
     *
     * @param value object to parse .toString() value from
     * @return null if toString() returns empty or if the passed in value is null, otherwise toString() value
     */
    public static String toStringEmptyToNull(final Object value) {
        if (value == null) {
            return null;
        }

        String stringValue = value.toString();

        if (stringValue.isEmpty()) {
            return null;
        }

        return stringValue;
    }

    /**
     * Parses an arbitrary object for an integer. If it can't be found, return null.
     *
     * @param value Object to parse for an integer
     * @return if parsing fails, return null
     */
    public static Integer parseIntegerOrNull(final Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Number) {
            return ((Number) value).intValue();
        }

        String string = toStringEmptyToNull(value);
        if (string == null) {
            return null;
        }

        Integer parsed;

        try {
            parsed = Integer.parseInt(string);
        } catch (Exception e) {
            Logger logger = LoggerFactory.getLogger(CloudApiUtils.class);
            String msg = "Error parsing value as integer. Value: %s";
            logger.warn(String.format(msg, value), e);
            parsed = null;
        }

        return parsed;
    }


    /**
     * Parses an arbitrary object for a boolean. If it can't be found, return null.
     *
     * @param value Object to parse for an boolean
     * @return if parsing fails, return null
     */
    public static Boolean parseBooleanOrNull(final Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof Boolean) {
            return (Boolean)value;
        }

        String string = toStringEmptyToNull(value);
        if (string == null) {
            return null;
        }

        Boolean parsed;

        try {
            parsed = Boolean.parseBoolean(string);
        } catch (Exception e) {
            Logger logger = LoggerFactory.getLogger(CloudApiUtils.class);
            String msg = "Error parsing value as boolean. Value: %s";
            logger.warn(String.format(msg, value), e);
            parsed = null;
        }

        return parsed;
    }

    /**
     * Naively converts a collection of objects to a single CSV string. Warning: this doesn't escape.
     * @param stringable collection of objects with implemented toString methods
     * @return CSV string or empty string
     */
    public static String csv(final Iterable stringable) {
        final StringBuilder builder = new StringBuilder();

        Iterator itr = stringable.iterator();

        for (Object o = itr.next(); itr.hasNext(); o = itr.next()) {
            if (o == null) {
                continue;
            }

            builder.append(o.toString());

            if (itr.hasNext()) {
                builder.append(",");
            }
        }

        return builder.toString();
    }

    /**
     * Naively converts a mapto a single CSV string. Warning: this doesn't escape.
     * @param map map with objects with implemented toString methods
     * @return CSV string or empty string
     */
    public static String csv(final Map map) {
        final StringBuilder builder = new StringBuilder();

        @SuppressWarnings("unchecked")
        final Set set = map.entrySet();
        final Iterator itr = set.iterator();

        for (Map.Entry entry = itr.next(); itr.hasNext(); entry = itr.next()) {
            if (entry == null) {
                continue;
            }

            builder.append(entry.getKey())
                   .append(": ")
                   .append(entry.getValue());

            if (itr.hasNext()) {
                builder.append(",");
            }
        }

        return builder.toString();
    }

    /**
     * Converts a naive CSV string to a collection.
     *
     * @param line CSV string
     * @return collection containing each value between each comma
     */
    public static Collection fromCsv(final String line) {
        Objects.requireNonNull(line, "Line must be present");

        final List list = new ArrayList<>();

        if (line.contains(",")) {
            String[] parts = csv2array(line);
            Collections.addAll(list, parts);
        } else {
            list.add(line);
        }

        return list;
    }

    public static String[] csv2array(final String line) {
        Objects.requireNonNull(line, "Line must be present");

        if (line.contains(",")) {
            return line.split(",\\s*");
        } else {
            return new String[] { line };
        }
    }

    /**
     * Serializes a specified value to a {@link String}.
     * @param value the value to be serialized
     * @return a serialized value as a {@link String}
     */
    public static String asString(final Object value) {
        if (value == null) {
            return null;
        } else if (value instanceof Iterable) {
            StringBuilder sb = new StringBuilder();

            Iterator itr = ((Iterable) value).iterator();
            while (itr.hasNext()) {
                Object next = itr.next();

                if (next != null) {
                    sb.append(next.toString());
                }

                if (itr.hasNext()) {
                    sb.append(",");
                }
            }

            return sb.toString();
        } else if (value.getClass().isArray()) {
            Object[] array = (Object[])value;

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < array.length; i++) {
                Object next = array[i];

                if (next != null) {
                    sb.append(next.toString());
                }

                if (i < array.length - 1) {
                    sb.append(", ");
                }
            }

            return sb.toString();
        }

        return value.toString();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy