2 * copyright(c) 2005 kuwata-lab all rights reserved.
7 import java.util.Collections;
9 import java.util.ArrayList;
11 import java.util.HashMap;
12 import java.util.IdentityHashMap;
13 import java.util.Iterator;
14 import java.util.regex.Pattern;
15 import java.util.regex.Matcher;
16 import java.util.Date;
17 import java.io.Reader;
18 import java.io.InputStreamReader;
19 import java.io.InputStream;
20 import java.io.FileInputStream;
21 import java.io.IOException;
24 private static final int VALUE_INTEGER = 1;
25 private static final int VALUE_DOUBLE = 2;
26 private static final int VALUE_STRING = 4;
27 private static final int VALUE_BOOLEAN = 8;
28 private static final int VALUE_DATE = 16;
29 private static final int VALUE_OBJECT = 32;
30 private static HashMap<String,Pattern> __patterns = new HashMap<>();
33 // You shouldn't instantiate this class
39 public static String inspect(Object obj) {
40 StringBuilder sb = new StringBuilder();
41 inspect(obj, sb, null);
45 private static void inspect(Object obj, StringBuilder sb, IdentityHashMap done) {
47 sb.append("nil"); // null?
48 } else if (obj instanceof String) {
49 inspect((String)obj, sb);
50 } else if (obj instanceof IdentityHashMap) {
52 done = new IdentityHashMap();
54 if (done.containsKey(obj)) {
57 done.put(obj, Boolean.TRUE);
58 inspect((Map)obj, sb, done);
60 } else if (obj instanceof List) {
62 done = new IdentityHashMap();
64 if (done.containsKey(obj)) {
67 done.put(obj, Boolean.TRUE);
68 inspect((List)obj, sb);
71 sb.append(obj.toString());
75 private static void inspect(Map map, StringBuilder sb, IdentityHashMap done) {
77 List list = new ArrayList(map.keySet());
78 Collections.sort(list);
80 for (Iterator it = list.iterator(); it.hasNext(); i++) {
81 Object key = it.next();
82 Object value = map.get(key);
86 inspect(key, sb, done);
88 inspect(value, sb, done);
93 private static void inspect(List list, StringBuilder sb) {
96 for (Iterator it = list.iterator(); it.hasNext(); i++) {
100 Object item = it.next();
101 inspect(item, sb, null);
106 private static void inspect(String str, StringBuilder sb) {
108 for (int i = 0; i < str.length(); i++) {
109 char ch = str.charAt(i);
132 * match pattern and return Mather object.
136 * String target = " name = foo\n mail = foo@mail.com\m";
137 * Matcher m = Util.matcher(target, "^\\s*(\\w+)\\s*=\\s*(.*)$");
139 * String key = m.group(1);
140 * String value = m.gropu(2);
144 public static Matcher matcher(String target, String regexp) {
145 Pattern pat = __patterns.get(regexp);
147 pat = Pattern.compile(regexp);
148 __patterns.put(regexp, pat);
150 return pat.matcher(target);
154 * return if pattern matched or not.
158 * String target = " name = foo\n";
159 * if (Util.matches(target, "^\\s*(\\w+)\\s*=\\s*(.*)$")) {
160 * System.out.println("matched.");
164 public static boolean matches(String target, String regexp) {
165 Matcher m = matcher(target, regexp);
170 public static boolean matches(String target, Pattern regexp) {
171 Matcher m = regexp.matcher(target);
176 * split string into list of line
178 public static List toListOfLines(String str) {
179 List<String> list = new ArrayList<>();
180 int len = str.length();
182 for (int i = 0; i < len; i++) {
183 char ch = str.charAt(i);
186 String line = str.substring(head, tail);
192 String line = str.substring(head, len);
199 * return true if 'instance' is an instance of 'klass'
201 public static boolean isInstanceOf(Object instance, Class klass) {
202 if (instance == null || klass == null) {
205 Class c = instance.getClass();
206 if (klass.isInterface()) {
208 Class[] interfaces = c.getInterfaces();
209 for (Class anInterface : interfaces) {
210 if (anInterface == klass) {
214 c = c.getSuperclass();
221 c = c.getSuperclass();
229 * read file content with default encoding of system
231 public static String readFile(String filename) throws IOException {
232 String charset = System.getProperty("file.encoding");
233 return readFile(filename, charset);
238 * read file content with specified encoding
240 private static String readFile(String filename, String encoding) throws IOException {
242 try (InputStream stream = new FileInputStream(filename)){
243 content = readInputStream(stream, encoding);
248 public static String readInputStream(InputStream stream) throws IOException {
249 String encoding = System.getProperty("file.encoding");
250 return readInputStream(stream, encoding);
253 private static String readInputStream(InputStream stream, String encoding) throws IOException {
255 try (Reader reader = new InputStreamReader(stream, encoding)){
256 StringBuilder sb = new StringBuilder();
258 while ((ch = reader.read()) >= 0) {
261 content = sb.toString();
266 public static String untabify(CharSequence str) {
268 StringBuilder sb = new StringBuilder();
269 int len = str.length();
271 for (int i = 0; i < len; i++) {
272 col = ++col % tabWidth;
273 char ch = str.charAt(i);
277 appendTabAsSpaces(tabWidth, sb, col);
288 return sb.toString();
291 private static void appendTabAsSpaces(int tabWidth, StringBuilder sb, int col) {
292 int n = tabWidth - col;
298 public static int compareValues(Object value1, Object value2) {
299 int vtype = (valueType(value1) << 8) | valueType(value2);
301 case (VALUE_INTEGER << 8) | VALUE_INTEGER :
302 return ((Integer)value1).compareTo((Integer)value2);
303 case (VALUE_DOUBLE << 8) | VALUE_DOUBLE :
304 return ((Double)value1).compareTo((Double)value2);
305 case (VALUE_STRING << 8) | VALUE_STRING :
306 return ((String)value1).compareTo((String)value2);
307 case (VALUE_BOOLEAN << 8) | VALUE_BOOLEAN :
308 boolean b1 = (Boolean) value1;
309 boolean b2 = (Boolean) value2;
310 int ret = b1 ? 1 : -1;
311 return (b1 == b2) ? 0 : ret;
312 case (VALUE_DATE << 8) | VALUE_DATE :
313 return ((Date)value1).compareTo((Date)value2);
314 case (VALUE_DOUBLE << 8) | VALUE_INTEGER :
315 case (VALUE_INTEGER << 8) | VALUE_DOUBLE :
316 double d1 = ((Number)value1).doubleValue();
317 double d2 = ((Number)value2).doubleValue();
318 return Double.compare(d1, d2);
320 throw new InvalidTypeException("cannot compare '" + value1.getClass().getName() + "' with '" + value2.getClass().getName());
324 private static int valueType(Object value) {
325 if (value instanceof Integer) {
326 return VALUE_INTEGER;
329 if (value instanceof Double) {
333 if (value instanceof String) {
337 if (value instanceof Boolean) {
338 return VALUE_BOOLEAN;
341 if (value instanceof Date) {
348 public static String repeatString(String str, int times) {
349 StringBuilder sb = new StringBuilder();
350 for (int i = 0; i < times; i++) {
353 return sb.toString();
357 * parse command-line options.
361 * public static void main(String[] arg) {
362 * String singles = "hv"; // options which takes no argument.
363 * String requireds = "fI"; // options which requires an argument.
364 * String optionals = "i"; // options which can take optional argument.
366 * Object[] ret = parseCommandOptions(args, singles, requireds, optionals);
367 * Map options = (Map)ret[0];
368 * Map properties = (Map)ret[1];
369 * String[] filenames = (String[])ret[2];
371 * } catch (CommandOptionException ex) {
372 * char option = ex.getOption();
373 * String error_symbol = ex.getErrorSymbol();
374 * Systen.err.println("*** error: " + ex.getMessage());
379 * @param args command-line strings
380 * @param singles options which takes no argument
381 * @param requireds options which requires an argument.
382 * @param optionals otpions which can take optional argument.
383 * @return array of options(Map), properties(Map), and filenames(String[])
385 public static Object[] parseCommandOptions(String[] args, String singles, String requireds, String optionals) throws CommandOptionException {
386 Map<String, Object> options = new HashMap<>();
387 Map<String, Object> properties = new HashMap<>();
391 for (i = 0; i < args.length; i++) {
392 if (args[i].length() == 0 || args[i].charAt(0) != '-') {
395 String opt = args[i];
396 int len = opt.length();
397 if (len == 1) { // option '-' means "don't parse arguments!"
402 if (opt.charAt(1) == '-') { // properties (--pname=pvalue)
405 int idx = opt.indexOf('=');
407 pname = opt.substring(2, idx);
408 pvalue = idx + 1 < opt.length() ? opt.substring(idx + 1) : "";
410 pname = opt.substring(2);
411 pvalue = Boolean.TRUE;
413 properties.put(pname, pvalue);
414 } else { // command-line options
415 for (int j = 1; j < len; j++) {
416 char ch = opt.charAt(j);
417 String chstr = Character.toString(ch);
418 if (singles != null && singles.indexOf(ch) >= 0) {
419 options.put(chstr, Boolean.TRUE);
420 } else if (requireds != null && requireds.indexOf(ch) >= 0) {
423 arg = opt.substring(j);
424 } else if (++i < args.length) {
427 throw new CommandOptionException("-" + ch + ": filename required.", ch, "command.option.noarg");
429 options.put(chstr, arg);
431 } else if (optionals != null && optionals.indexOf(ch) >= 0) {
434 arg = opt.substring(j);
438 options.put(chstr, arg);
441 throw new CommandOptionException("-" + ch + "invalid option.", ch, "command.option.invalid");
447 assert i <= args.length;
448 int n = args.length - i;
449 filenames = new String[n];
450 for (int j = 0; i < args.length; i++, j++) {
451 filenames[j] = args[i];
454 return new Object[] { options, properties, filenames };