1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.cts.releaseparser; 18 19 import java.util.HashMap; 20 import java.util.Map; 21 import java.util.ArrayList; 22 import java.util.List; 23 24 public class ArgumentParser { 25 private HashMap<String, List<String>> mArgumentMap; 26 private String[] mArguments; 27 ArgumentParser(String args[])28 public ArgumentParser(String args[]) { 29 mArguments = args; 30 mArgumentMap = null; 31 } 32 getArgumentMap()33 public Map<String, List<String>> getArgumentMap() { 34 if (mArgumentMap == null) { 35 parse(); 36 } 37 return mArgumentMap; 38 } 39 40 /** 41 * Gets parameter list of an option 42 * 43 * @return List<String> of parameters or null if no such option 44 */ getParameterList(String option)45 public List<String> getParameterList(String option) { 46 return getArgumentMap().get(option); 47 } 48 49 /** 50 * Gets parameter element by index of an option 51 * 52 * @return String of the parameter or null 53 */ getParameterElement(String option, int index)54 public String getParameterElement(String option, int index) { 55 String ele = null; 56 try { 57 ele = getArgumentMap().get(option).get(index); 58 } catch (Exception ex) { 59 } 60 return ele; 61 } 62 63 /** 64 * Checks if arguments contin an option 65 * 66 * @return true or false 67 */ containsOption(String option)68 public boolean containsOption(String option) { 69 return getArgumentMap().containsKey(option); 70 } 71 72 /** 73 * Parses arguments for a map of <options, parameterList> format: -[option1] <parameter1.1> 74 * <parameter1.2>... 75 */ parse()76 private void parse() { 77 mArgumentMap = new HashMap<String, List<String>>(); 78 79 for (int i = 0; i < mArguments.length; i++) { 80 // an option starts with "-" 81 if (mArguments[i].startsWith("-")) { 82 String option = mArguments[i].substring(1); 83 84 // gets parameters till the next option, starts with - 85 ArrayList parameterList = new ArrayList<String>(); 86 while ((i + 1 < mArguments.length) && (!mArguments[i + 1].startsWith("-"))) { 87 ++i; 88 parameterList.add(mArguments[i]); 89 } 90 mArgumentMap.put(option, parameterList); 91 } 92 } 93 } 94 } 95