001package com.thetransactioncompany.cors;
002
003
004import java.util.Iterator;
005import java.util.Set;
006
007
008/**
009 * Header utilities.
010 *
011 * @author Vladimir Dzhuvinov
012 */
013public class HeaderUtils {
014
015
016        /**
017         * Serialises the items of a set into a string. Each item must have a
018         * meaningful {@code toString()} method.
019         *
020         * @param set The set to serialise. Must not be {@code null}.
021         * @param sep The string separator to apply. Should not be
022         *            {@code null}.
023         *
024         * @return The serialised set as string.
025         */
026        public static String serialize(final Set<String> set, final String sep) {
027
028                StringBuilder sb = new StringBuilder();
029
030                Iterator<String> it = set.iterator();
031
032                while (it.hasNext()) {
033
034                        sb.append(it.next());
035
036                        if (it.hasNext())
037                                sb.append(sep);
038                }
039
040                return sb.toString();
041        }
042
043
044        /**
045         * Parses a header value consisting of zero or more space / comma /
046         * space + comma separated strings. The input string is trimmed before
047         * splitting.
048         *
049         * @param headerValue The header value, may be {@code null}.
050         *
051         * @return A string array of the parsed string items, empty if none
052         *         were found or the input was {@code null}.
053         */
054        public static String[] parseMultipleHeaderValues(final String headerValue) {
055
056                if (headerValue == null)
057                        return new String[0]; // empty array
058
059                String trimmedHeaderValue = headerValue.trim();
060
061                if (trimmedHeaderValue.isEmpty())
062                        return new String[0];
063
064                return trimmedHeaderValue.split("\\s*,\\s*|\\s+");
065        }
066}