View Javadoc
1   package com.simpligility.maven.plugins.android;
2   
3   import com.google.common.base.Splitter;
4   import com.google.common.collect.Lists;
5   
6   import java.util.AbstractMap;
7   import java.util.Collections;
8   import java.util.HashMap;
9   import java.util.List;
10  import java.util.Map;
11  
12  /**
13   * <p>Parses a list of key/value pairs separated by a space in to a map.</p>
14   *
15   * <p>Example input:</p>
16   * <pre>
17   *     list[0] = "firstKey firstValue"
18   *     list[1] = "secondKey 'second value with space and single quote escape'
19   * </pre>
20   *
21   * <p>Example output:</p>
22   * <pre>
23   *     map["firstKey"] = "firstValue"
24   *     map["secondKey"] = "'second value with space and single quote escape'"
25   * </pre>
26   */
27  public class InstrumentationArgumentParser
28  {
29      private static final String SEPARATOR = " ";
30  
31      /**
32       * Parses the given {@code flatArgs} into a map of key/value pairs.
33       *
34       * @param flatArgs the flat representation of arguments, might be null
35       * @return a map representation of the given key/value pair list, might be empty
36       * @throws IllegalArgumentException when the given list contains unparseable entries
37       */
38      public static Map<String, String> parse( final List<String> flatArgs )
39      {
40          if ( flatArgs == null )
41          {
42              return Collections.EMPTY_MAP;
43          }
44  
45          final Map<String, String> mappedArgs = new HashMap<String, String>();
46  
47          for ( final String flatArg : flatArgs )
48          {
49              final AbstractMap.SimpleEntry<String, String> keyValuePair = parseKeyValuePair( flatArg );
50              mappedArgs.put( keyValuePair.getKey(), keyValuePair.getValue() );
51          }
52  
53          return mappedArgs;
54      }
55  
56      private static AbstractMap.SimpleEntry<String, String> parseKeyValuePair( final String arg )
57      {
58          final List<String> keyValueSplit = Lists.newArrayList( Splitter.on( SEPARATOR ).limit( 2 ).split( arg ) );
59  
60          if ( keyValueSplit.size() == 1 )
61          {
62              throw new IllegalArgumentException( "Could not separate \"" + arg + "\" by a whitespace into two parts" );
63          }
64  
65          return new AbstractMap.SimpleEntry<String, String>( keyValueSplit.get( 0 ), keyValueSplit.get( 1 ) );
66      }
67  }