package il.net.inter.genadyb.phonebook; import java.util.StringTokenizer; /** * This class contains the implementations of the different * field retrieval methods. */ public class FieldRetrieval { /* * Constant that select the retrieval method. */ public static final int INDEX_OF = 1; public static final int TOKENIZER = 2; public static final int REGEX = 3; public static final int INTERN = 4; public static final int NEW_STRING = 5; /** * The field that controls which field retrieval method * will be used. */ private static int method = INDEX_OF; /** * Set the field retrieval method. */ public static void setMethod(int newMethod) { method = newMethod; } /** * Retrieve the i-th field from colon delimited string according * to the selected field retrieval {@link #method}. * * @param line A line from the database file * @param field Field number */ public static String getField(String line, int field) { switch (method) { case INDEX_OF: return getFieldIndexOf(line, field); case TOKENIZER: return getFieldTokenizer(line, field); case REGEX: return getFieldRegex(line, field); case INTERN: return getFieldIntern(line, field); case NEW_STRING: return getFieldNewString(line, field); default : throw new IllegalStateException("Unknown method"); } } private static String getFieldIndexOf(String line, int field) { int startIndex = 0; while (field-- != 0) { startIndex = line.indexOf(':', startIndex); if (startIndex == -1) { throw new IllegalArgumentException("String does not have enough fields"); } // skip over the ':' startIndex ++; } int endIndex = line.indexOf(':', startIndex); if (endIndex == -1) { // the last field return line.substring(startIndex); } else { return line.substring(startIndex, endIndex); } } private static String getFieldTokenizer(String line, int field) { StringTokenizer st = new StringTokenizer(line, ":"); while (field-- != 0) { st.nextToken(); } return st.nextToken(); } private static String getFieldRegex(String line, int field) { return line.split(":", field+2)[field]; } private static String getFieldNewString(String line, int field) { return new String(getFieldRegex(line, field)); } private static String getFieldIntern(String line, int field) { return getFieldRegex(line, field).intern(); } // ------------------------------------- // INTERNAL IMPLEMENTATION FOLLOWS. // ------------------------------------- /** * Return the i-th field from colon delimited string, * using the simplest regular expressions method. This method * is not controlled by the {@link #method} field. * It is an internal program implementation method and * has nothing to do with the described methods. */ static String getNormalField(String line, int field) { return getFieldRegex(line, field); } }