1 2 24 25 26 27 28 29 package com.lutris.util; 30 import java.text.MessageFormat ; 31 import java.util.StringTokenizer ; 32 33 40 public class KeywordParser { 41 static private String separator = "."; 42 43 52 static private String parseComponent (StringTokenizer tokens, 53 int compIdx, 54 String keyword) 55 throws KeywordValueException { 56 String comp = tokens.nextToken (); 57 58 62 if (comp.equals (separator) && (compIdx == 0)) { 63 String pattern = "keyword should not start with a {0} separator: \"{1} \""; 64 Object [] args = new String [] {separator,keyword}; 65 String msg = MessageFormat.format(pattern, args); 66 67 throw new KeywordValueException (msg); 70 } 71 72 75 boolean isOk = (comp.length () > 0); 76 if (isOk) { 77 if (!Character.isJavaIdentifierStart (comp.charAt (0))) { 78 isOk = false; 79 } 80 for (int j = 1; j < comp.length (); j++) { 81 if (!Character.isJavaIdentifierPart (comp.charAt (j))) { 82 isOk = false; 83 break; 84 } 85 } 86 } 87 if (!isOk) { 88 String msg = "keyword component must be a legal Java identifier " + 89 "component \"" + comp + "\": \"" + keyword + "\""; 90 throw new KeywordValueException (msg); 91 } 92 93 96 if (tokens.hasMoreTokens ()) { 97 String sep = tokens.nextToken (); 98 if (!sep.equals (separator)) { 99 String msg = "keyword component separator must be a " + 100 "single '" + separator + "', got \"" + sep + "\": " + 101 keyword + "\""; 102 throw new KeywordValueException (msg); 103 } 104 } 105 return comp; 106 } 107 108 115 static public String [] parse (String keyword) 116 throws KeywordValueException { 117 118 StringTokenizer tokens = new StringTokenizer (keyword, 119 separator, 120 true); 121 126 int numTokens = tokens.countTokens (); 127 if ((numTokens % 2) != 1) { 128 String msg = "keyword component must be single word or words " + 129 "separated by '" + separator + "': \"" + keyword + "\""; 130 throw new KeywordValueException (msg); 131 } 132 int numComps = (numTokens / 2) + 1; 133 String [] keyParts = new String [numComps]; 134 135 for (int compIdx = 0; compIdx < numComps; compIdx++) { 136 keyParts [compIdx] = parseComponent (tokens, 137 compIdx, 138 keyword); 139 } 140 141 return keyParts; 142 } 143 144 150 static public String join (String [] keywordPath) { 151 StringBuffer keyword = new StringBuffer (); 152 153 for (int idx = 0; idx < keywordPath.length; idx++) { 154 if (idx > 0) { 155 keyword.append (separator); 156 } 157 keyword.append (keywordPath [idx]); 158 } 159 return keyword.toString (); 160 } 161 162 169 static public String concat (String keyword1, 170 String keyword2) { 171 return keyword1 + separator + keyword2; 172 } 173 } 174 | Popular Tags |