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

by.stub.utils.CollectionUtils Maven / Gradle / Ivy

package by.stub.utils;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Alexander Zagniotov
 * @since 11/6/12, 6:33 PM
 */
public final class CollectionUtils {

   private CollectionUtils() {

   }

   public static Map constructParamMap(final String queryString) {

      if (!StringUtils.isSet(queryString)) {
         return new LinkedHashMap();
      }

      final Map paramMap = new LinkedHashMap();
      final String[] pairs = queryString.split("&");
      for (final String pair : pairs) {
         final String[] splittedPair = pair.split("=");

         final String splittedPairKey = splittedPair[0];
         String splittedPairValue = splittedPair.length > 1 ? splittedPair[1] : "";

         if (StringUtils.isWithinSquareBrackets(splittedPairValue)) {

            final String cleansedValue = StringUtils.decodeUrlEncodedQuotes(StringUtils.removeSquareBrackets(splittedPairValue));
            final String bracketedQueryValueAsCSV = Arrays.asList(cleansedValue.split(",")).toString();
            splittedPairValue = StringUtils.trimSpacesBetweenCSVElements(bracketedQueryValueAsCSV);
         }

         paramMap.put(splittedPairKey, splittedPairValue);
      }

      return paramMap;
   }

   public static String constructQueryString(final Map query) {

      final Set> mapEntries = query.entrySet();
      final Iterator> iterator = mapEntries.iterator();
      final StringBuilder queryStringBuilder = new StringBuilder();

      while (iterator.hasNext()) {
         final Map.Entry entry = iterator.next();
         final String pair = String.format("%s=%s", entry.getKey(), entry.getValue());

         queryStringBuilder.append(pair);
         if (iterator.hasNext()) {
            queryStringBuilder.append('&');
         }

      }

      return queryStringBuilder.toString();
   }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy