List of usage examples for java.util Hashtable Hashtable
public Hashtable()
From source file:Main.java
public static void main(String[] args) { JTextArea area = new JTextArea(6, 32); Keymap parent = area.getKeymap(); Keymap newmap = JTextComponent.addKeymap("KeymapExampleMap", parent); KeyStroke u = KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK); Action actionU = new UppercaseAction(); newmap.addActionForKeyStroke(u, actionU); Action actionList[] = area.getActions(); Hashtable lookup = new Hashtable(); for (int j = 0; j < actionList.length; j += 1) lookup.put(actionList[j].getValue(Action.NAME), actionList[j]); KeyStroke L = KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK); Action actionL = (Action) lookup.get(DefaultEditorKit.selectLineAction); newmap.addActionForKeyStroke(L, actionL); area.setKeymap(newmap);//from w ww. jav a 2 s . c om JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new JScrollPane(area), BorderLayout.CENTER); area.setText("this is a test"); f.setSize(300, 300); f.setVisible(true); }
From source file:KeymapExample.java
public static void main(String[] args) { JTextArea area = new JTextArea(6, 32); Keymap parent = area.getKeymap(); Keymap newmap = JTextComponent.addKeymap("KeymapExampleMap", parent); KeyStroke u = KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK); Action actionU = new UpWord(); newmap.addActionForKeyStroke(u, actionU); Action actionList[] = area.getActions(); Hashtable lookup = new Hashtable(); for (int j = 0; j < actionList.length; j += 1) lookup.put(actionList[j].getValue(Action.NAME), actionList[j]); KeyStroke L = KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK); Action actionL = (Action) lookup.get(DefaultEditorKit.selectLineAction); newmap.addActionForKeyStroke(L, actionL); KeyStroke W = KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK); Action actionW = (Action) lookup.get(DefaultEditorKit.selectWordAction); newmap.addActionForKeyStroke(W, actionW); area.setKeymap(newmap);//w w w. ja v a 2 s .c o m JFrame f = new JFrame("KeymapExample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER); area.setText("This is a test."); f.pack(); f.setVisible(true); }
From source file:SampleSliders.java
public static void main(String args[]) { String title = (args.length == 0 ? "Sample Slider" : args[0]); JFrame f = new JFrame(title); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JSlider js1 = new JSlider(); js1.putClientProperty("JSlider.isFilled", Boolean.TRUE); JSlider js2 = new JSlider(); js2.setMajorTickSpacing(25);/*from w w w.j a v a 2 s . c o m*/ js2.setPaintTicks(true); js2.setSnapToTicks(true); JSlider js3 = new JSlider(JSlider.VERTICAL); js3.setPaintTrack(false); js3.setMinorTickSpacing(5); js3.setMajorTickSpacing(10); js3.setPaintTicks(true); js3.setPaintLabels(true); js3.setSnapToTicks(true); JSlider js4 = new JSlider(JSlider.VERTICAL); Hashtable table = new Hashtable(); table.put(new Integer(0), new JLabel(new DiamondIcon(Color.red))); table.put(new Integer(10), new JLabel("Ten")); table.put(new Integer(25), new JLabel("Twenty-Five")); table.put(new Integer(34), new JLabel("Thirty-Four")); table.put(new Integer(52), new JLabel("Fifty-Two")); table.put(new Integer(70), new JLabel("Seventy")); table.put(new Integer(82), new JLabel("Eighty-Two")); table.put(new Integer(100), new JLabel(new DiamondIcon(Color.black))); js4.setLabelTable(table); js4.setPaintLabels(true); js4.setSnapToTicks(true); Container c = f.getContentPane(); c.add(js1, BorderLayout.NORTH); c.add(js2, BorderLayout.SOUTH); c.add(js3, BorderLayout.WEST); c.add(js4, BorderLayout.EAST); f.setSize(300, 200); f.setVisible(true); }
From source file:org.ala.hbase.AdfInfoSourceUrlUpdater.java
/** * Usage: outputFileName [option: cassandraAddress cassandraPort] * /* w w w . ja v a2 s . c o m*/ * @param args */ public static void main(String[] args) throws Exception { Map<String, String> hashtable = new Hashtable<String, String>(); for (int i = 0; i < args.length; i++) { String infoId = args[i].substring(0, args[i].indexOf(':')); String url = args[i].substring(args[i].indexOf(':') + 1); hashtable.put(infoId, url); } ApplicationContext context = SpringUtils.getContext(); AdfInfoSourceUrlUpdater loader = context.getBean(AdfInfoSourceUrlUpdater.class); try { loader.doFullScan(hashtable); } catch (Exception e) { System.out.println("***** Fatal Error !!!.... shutdown cassandra connection."); e.printStackTrace(); logger.error(e); System.exit(0); } System.exit(0); }
From source file:com.talkdesk.geo.PhoneNumberGeoMap.java
/** * @param args//from w w w.j a v a2 s. c o m * @throws IOException * @throws SQLException * @throws ClassNotFoundException * @throws GeoResolverException */ public static void main(String[] args) throws GeoResolverException { // create Options object DBConnector connector = new DBConnector(); GeoCodeResolver resolver = new GeoCodeResolver(connector.getDefaultDBconnection()); ArrayList list = new ArrayList(Arrays.asList(args)); Hashtable<String, Double> infoTable = new Hashtable<String, Double>(); if (list.contains("--populate-data")) { GeoCodeRepositoryBuilder repositoryBuilder = new GeoCodeRepositoryBuilder(); if (list.contains("--country")) repositoryBuilder.populateCountryData(); else if (list.contains("--geo")) repositoryBuilder.populateGeoData(); else { repositoryBuilder.populateCountryData(); repositoryBuilder.populateGeoData(); } } else if (list.contains("--same-country-only")) { list.remove("--same-country-only"); infoTable = resolver.buildInfoTable(list, true); } else { infoTable = resolver.buildInfoTable(list, false); } String phoneNumber = resolver.getClosestNumber(infoTable); if (phoneNumber != null) { System.out.println("-----------------------"); System.out.println(phoneNumber); Locale locale = new Locale("en", phoneNumber.split(":")[0]); System.out.println(locale.getDisplayCountry()); } else { System.out.println("-----------------------"); System.out.println("No Result ..!!!"); } }
From source file:HashtableDemo.java
public static void main(String[] argv) { // Construct and load the hash. This simulates loading a // database or reading from a file, or wherever the data is. Hashtable h = new Hashtable(); // The hash maps from company name to address. // In real life this might map to an Address object... h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Learning Tree", "Los Angeles, CA"); h.put("Microsoft", "Redmond, WA"); h.put("Netscape", "Mountain View, CA"); h.put("O'Reilly", "Sebastopol, CA"); h.put("Sun", "Mountain View, CA"); // Two versions of the "retrieval" phase. // Version 1: get one pair's value given its key // (presumably the key would really come from user input): String queryString = "O'Reilly"; System.out.println("You asked about " + queryString + "."); String resultString = (String) h.get(queryString); System.out.println("They are located in: " + resultString); System.out.println();/*from w w w. ja va2 s . c o m*/ // Version 2: get ALL the keys and pairs // (maybe to print a report, or to save to disk) Enumeration k = h.keys(); while (k.hasMoreElements()) { String key = (String) k.nextElement(); System.out.println("Key " + key + "; Value " + (String) h.get(key)); } }
From source file:ReflectClass.java
public static void main(String args[]) { Constructor cn[];/*from w w w . j ava 2 s. co m*/ Class cc[]; Method mm[]; Field ff[]; Class c = null; Class supClass; String x, y, s1, s2, s3; Hashtable classRef = new Hashtable(); if (args.length == 0) { System.out.println("Please specify a class name on the command line."); System.exit(1); } try { c = Class.forName(args[0]); } catch (ClassNotFoundException ee) { System.out.println("Couldn't find class '" + args[0] + "'"); System.exit(1); } /* * Step 0: If our name contains dots we're in a package so put * that out first. */ x = c.getName(); if (x.lastIndexOf(".") != -1) { y = x.substring(0, x.lastIndexOf(".")); System.out.println("package " + y + ";\n\r"); } /* * Let's use the Reflection API to sift through what is * inside this class. * * Step 1: Collect referenced classes * This step is used so that I can regenerate the import statements. * It isn't strictly required of course, Java works just fine with * fully qualified object class names, but it looks better when you * use 'String' rather than 'java.lang.String' as the return type. */ ff = c.getDeclaredFields(); for (int i = 0; i < ff.length; i++) { x = tName(ff[i].getType().getName(), classRef); } cn = c.getDeclaredConstructors(); for (int i = 0; i < cn.length; i++) { Class cx[] = cn[i].getParameterTypes(); if (cx.length > 0) { for (int j = 0; j < cx.length; j++) { x = tName(cx[j].getName(), classRef); } } } mm = c.getDeclaredMethods(); for (int i = 0; i < mm.length; i++) { x = tName(mm[i].getReturnType().getName(), classRef); Class cx[] = mm[i].getParameterTypes(); if (cx.length > 0) { for (int j = 0; j < cx.length; j++) { x = tName(cx[j].getName(), classRef); } } } // Don't import ourselves ... classRef.remove(c.getName()); /* * Step 2: Start class description generation, start by printing * out the import statements. * * This is the line that goes 'public SomeClass extends Foo {' */ for (Enumeration e = classRef.keys(); e.hasMoreElements();) { System.out.println("import " + e.nextElement() + ";"); } System.out.println(); /* * Step 3: Print the class or interface introducer. We use * a convienience method in Modifer to print the whole string. */ int mod = c.getModifiers(); System.out.print(Modifier.toString(mod)); if (Modifier.isInterface(mod)) { System.out.print(" interface "); } else { System.out.print(" class "); } System.out.print(tName(c.getName(), null)); supClass = c.getSuperclass(); if (supClass != null) { System.out.print(" extends " + tName(supClass.getName(), classRef)); } System.out.println(" {"); /* * Step 4: Print out the fields (internal class members) that are declared * by this class. * * Fields are of the form [Modifiers] [Type] [Name] ; */ System.out.println("\n\r/*\n\r * Field Definitions.\r\n */"); for (int i = 0; i < ff.length; i++) { Class ctmp = ff[i].getType(); int md = ff[i].getModifiers(); System.out.println(" " + Modifier.toString(md) + " " + tName(ff[i].getType().getName(), null) + " " + ff[i].getName() + ";"); } /* * Step 5: Print out the constructor declarations. * * We note the name of the class which is the 'name' for all * constructors. Also there is no type, so the definition is * simplye [Modifiers] ClassName ( [ Parameters ] ) { } * */ System.out.println("\n\r/*\n\r * Declared Constructors. \n\r */"); x = tName(c.getName(), null); for (int i = 0; i < cn.length; i++) { int md = cn[i].getModifiers(); System.out.print(" " + Modifier.toString(md) + " " + x); Class cx[] = cn[i].getParameterTypes(); System.out.print("( "); if (cx.length > 0) { for (int j = 0; j < cx.length; j++) { System.out.print(tName(cx[j].getName(), null)); if (j < (cx.length - 1)) System.out.print(", "); } } System.out.print(") "); System.out.println("{ ... }"); } /* * Step 6: Print out the method declarations. * * Now methods have a name, a return type, and an optional * set of parameters so they are : * [modifiers] [type] [name] ( [optional parameters] ) { } */ System.out.println("\n\r/*\n\r * Declared Methods.\n\r */"); for (int i = 0; i < mm.length; i++) { int md = mm[i].getModifiers(); System.out.print(" " + Modifier.toString(md) + " " + tName(mm[i].getReturnType().getName(), null) + " " + mm[i].getName()); Class cx[] = mm[i].getParameterTypes(); System.out.print("( "); if (cx.length > 0) { for (int j = 0; j < cx.length; j++) { System.out.print(tName(cx[j].getName(), classRef)); if (j < (cx.length - 1)) System.out.print(", "); } } System.out.print(") "); System.out.println("{ ... }"); } /* * Step 7: Print out the closing brace and we're done! */ System.out.println("}"); }
From source file:asl.seedscan.SeedScan.java
public static void main(String args[]) { // Default locations of config and schema files File configFile = new File("config.xml"); File schemaFile = new File("schemas/SeedScanConfig.xsd"); boolean parseConfig = true; ArrayList<File> schemaFiles = new ArrayList<File>(); schemaFiles.add(schemaFile);//from ww w .j a v a2 s . c o m // ==== Command Line Parsing ==== Options options = new Options(); Option opConfigFile = new Option("c", "config-file", true, "The config file to use for seedscan. XML format according to SeedScanConfig.xsd."); Option opSchemaFile = new Option("s", "schema-file", true, "The xsd schema file which should be used to verify the config file format. "); OptionGroup ogConfig = new OptionGroup(); ogConfig.addOption(opConfigFile); OptionGroup ogSchema = new OptionGroup(); ogConfig.addOption(opSchemaFile); options.addOptionGroup(ogConfig); options.addOptionGroup(ogSchema); PosixParser optParser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = optParser.parse(options, args, true); } catch (org.apache.commons.cli.ParseException e) { logger.error("Error while parsing command-line arguments."); System.exit(1); } Option opt; Iterator<?> iter = cmdLine.iterator(); while (iter.hasNext()) { opt = (Option) iter.next(); if (opt.getOpt().equals("c")) { configFile = new File(opt.getValue()); } else if (opt.getOpt().equals("s")) { schemaFile = new File(opt.getValue()); } } // ==== Configuration Read and Parse Actions ==== ConfigParser parser = new ConfigParser(schemaFiles); ConfigT config = parser.parseConfig(configFile); // Print out configuration file contents Formatter formatter = new Formatter(new StringBuilder(), Locale.US); // ===== CONFIG: LOCK FILE ===== File lockFile = new File(config.getLockfile()); logger.info("SeedScan lock file is '" + lockFile + "'"); LockFile lock = new LockFile(lockFile); if (!lock.acquire()) { logger.error("Could not acquire lock."); System.exit(1); } // ===== CONFIG: LOGGING ===== // MTH: This is now done in log4j.properties file // ===== CONFIG: DATABASE ===== MetricDatabase readDB = new MetricDatabase(config.getDatabase()); MetricDatabase writeDB = new MetricDatabase(config.getDatabase()); MetricReader reader = new MetricReader(readDB); MetricInjector injector = new MetricInjector(writeDB); // ===== CONFIG: SCANS ===== Hashtable<String, Scan> scans = new Hashtable<String, Scan>(); if (config.getScans().getScan() == null) { logger.error("No scans in configuration."); System.exit(1); } else { for (ScanT scanCfg : config.getScans().getScan()) { String name = scanCfg.getName(); if (scans.containsKey(name)) { logger.error("Duplicate scan name '" + name + "' encountered."); System.exit(1); } // This should really be handled by jaxb by setting it up in schemas/SeedScanConfig.xsd if (scanCfg.getStartDay() == null && scanCfg.getStartDate() == null) { logger.error( "== SeedScan Error: Must set EITHER cfg:start_day -OR- cfg:start_date in config.xml to start Scan!"); System.exit(1); } // Configure this Scan Scan scan = new Scan(scanCfg.getName()); scan.setPathPattern(scanCfg.getPath()); scan.setDatalessDir(scanCfg.getDatalessDir()); scan.setEventsDir(scanCfg.getEventsDir()); scan.setPlotsDir(scanCfg.getPlotsDir()); scan.setDaysToScan(scanCfg.getDaysToScan().intValue()); if (scanCfg.getStartDay() != null) { scan.setStartDay(scanCfg.getStartDay().intValue()); } if (scanCfg.getStartDate() != null) { scan.setStartDate(scanCfg.getStartDate().intValue()); } if (scanCfg.getNetworkSubset() != null) { logger.debug("Filter on Network Subset=[{}]", scanCfg.getNetworkSubset()); Filter filter = new Filter(false); for (String network : scanCfg.getNetworkSubset().split(",")) { logger.debug("Network =[{}]", network); filter.addFilter(network); } scan.setNetworks(filter); } if (scanCfg.getStationSubset() != null) { logger.debug("Filter on Station Subset=[{}]", scanCfg.getStationSubset()); Filter filter = new Filter(false); for (String station : scanCfg.getStationSubset().split(",")) { logger.debug("Station =[{}]", station); filter.addFilter(station); } scan.setStations(filter); } if (scanCfg.getLocationSubset() != null) { logger.debug("Filter on Location Subset=[{}]", scanCfg.getLocationSubset()); Filter filter = new Filter(false); for (String location : scanCfg.getLocationSubset().split(",")) { logger.debug("Location =[{}]", location); filter.addFilter(location); } scan.setLocations(filter); } if (scanCfg.getChannelSubset() != null) { logger.debug("Filter on Channel Subset=[{}]", scanCfg.getChannelSubset()); Filter filter = new Filter(false); for (String channel : scanCfg.getChannelSubset().split(",")) { logger.debug("Channel =[{}]", channel); filter.addFilter(channel); } scan.setChannels(filter); } for (MetricT met : scanCfg.getMetrics().getMetric()) { try { Class<?> metricClass = Class.forName(met.getClassName()); MetricWrapper wrapper = new MetricWrapper(metricClass); for (ArgumentT arg : met.getArgument()) { wrapper.add(arg.getName(), arg.getValue()); } scan.addMetric(wrapper); } catch (ClassNotFoundException ex) { logger.error("No such metric class '" + met.getClassName() + "'"); System.exit(1); } catch (InstantiationException ex) { logger.error("Could not dynamically instantiate class '" + met.getClassName() + "'"); System.exit(1); } catch (IllegalAccessException ex) { logger.error("Illegal access while loading class '" + met.getClassName() + "'"); System.exit(1); } catch (NoSuchFieldException ex) { logger.error("Invalid dynamic argument to Metric subclass '" + met.getClassName() + "'"); System.exit(1); } } scans.put(name, scan); } } // ==== Establish Database Connection ==== // TODO: State Tracking in the Database // - Record scan started in database. // - Track our progress as we go so a new process can pick up where // we left off if our process dies. // - Mark when each date-station-channel-operation is complete //LogDatabaseHandler logDB = new LogDatabaseHandler(configuration.get // For each day ((yesterday - scanDepth) to yesterday) // scan for these channel files, only process them if // they have not yet been scanned, or if changes have // occurred to the file since its last scan. Do this for // each scan type. Do not re-scan data for each type, // launch processes for each scan and use the same data set // for each. If we can pipe the data as it is read, do so. // If we need to push all of it at once, do these in sequence // in order to preserve overall system memory resources. Scan scan = null; // ==== Perform Scans ==== scan = scans.get("daily"); //MTH: This part could/should be moved up higher except that we need to know datalessDir, which, // at this point, is configured on a per scan basis ... so we need to know what scan we're doing MetaServer metaServer = null; if (config.getMetaserver() != null) { if (config.getMetaserver().getUseRemote().equals("yes") || config.getMetaserver().getUseRemote().equals("true")) { String remoteServer = config.getMetaserver().getRemoteUri(); try { metaServer = new MetaServer(new URI(remoteServer)); } catch (Exception e) { logger.error("caught URI exception:" + e.getMessage()); } } else { metaServer = new MetaServer(scan.getDatalessDir()); } } else { // Use local MetaServer metaServer = new MetaServer(scan.getDatalessDir()); } List<Station> stations = null; if (config.getStationList() == null) { // get StationList from MetaServer logger.info("Get StationList from MetaServer"); stations = metaServer.getStationList(); } else { // read StationList from config.xml logger.info("Read StationList from config.xml"); List<String> stationList = config.getStationList().getStation(); if (stationList.size() > 0) { stations = new ArrayList<Station>(); for (String station : stationList) { String[] words = station.split("_"); if (words.length != 2) { logger.warn(String.format("stationList: station=[%s] is NOT a valid station --> Skip", station)); } else { stations.add(new Station(words[0], words[1])); logger.info("config.xml: Read station:" + station); } } } else { logger.error("Error: No valid stations read from config.xml"); } } if (stations == null) { logger.error("Found NO stations to scan --> EXITTING SeedScan"); System.exit(1); } Thread readerThread = new Thread(reader); readerThread.start(); logger.info("Reader thread started."); Thread injectorThread = new Thread(injector); injectorThread.start(); logger.info("Injector thread started."); // Loop over scans and hand each one to a ScanManager logger.info("Hand scan to ScanManager"); for (String key : scans.keySet()) { scan = scans.get(key); logger.info(String.format("Scan=[%s] startDay=%d startDate=%d daysToScan=%d\n", key, scan.getStartDay(), scan.getStartDate(), scan.getDaysToScan())); ScanManager scanManager = new ScanManager(reader, injector, stations, scan, metaServer); } logger.info("ScanManager is [ FINISHED ] --> stop the injector and reader threads"); try { injector.halt(); logger.info("All stations processed. Waiting for injector thread to finish..."); synchronized (injectorThread) { //injectorThread.wait(); injectorThread.interrupt(); } logger.info("Injector thread halted."); } catch (InterruptedException ex) { logger.warn("The injector thread was interrupted while attempting to complete requests."); } try { reader.halt(); logger.info("All stations processed. Waiting for reader thread to finish..."); synchronized (readerThread) { //readerThread.wait(); readerThread.interrupt(); } logger.info("Reader thread halted."); } catch (InterruptedException ex) { logger.warn("The reader thread was interrupted while attempting to complete requests."); } try { lock.release(); } catch (IOException e) { ; } finally { logger.info("Release seedscan lock and quit metaServer"); lock = null; metaServer.quit(); } }
From source file:org.ala.hbase.RepoDataLoader.java
/** * This takes a list of infosource ids... * <p/>/* w w w . j a va 2s . c o m*/ * Usage: -stats or -reindex or -gList and list of infosourceId * * @param args */ public static void main(String[] args) throws Exception { //RepoDataLoader loader = new RepoDataLoader(); ApplicationContext context = SpringUtils.getContext(); RepoDataLoader loader = (RepoDataLoader) context.getBean(RepoDataLoader.class); long start = System.currentTimeMillis(); loader.loadInfoSources(); String filePath = repositoryDir; if (args.length > 0) { if (args[0].equalsIgnoreCase("-stats")) { loader.statsOnly = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); } if (args[0].equalsIgnoreCase("-reindex")) { loader.reindex = true; loader.indexer = context.getBean(PartialIndex.class); args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -reindex: " + loader.reindex); logger.debug("reindex url: " + loader.reindexUrl); } if (args[0].equalsIgnoreCase("-gList")) { loader.gList = true; args = (String[]) ArrayUtils.subarray(args, 1, args.length); logger.info("**** -gList: " + loader.gList); } if (args[0].equalsIgnoreCase("-biocache")) { Hashtable<String, String> hashTable = new Hashtable<String, String>(); hashTable.put("accept", "application/json"); ObjectMapper mapper = new ObjectMapper(); mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); RestfulClient restfulClient = new RestfulClient(0); String fq = "&fq="; if (args.length > 1) { java.util.Date date = new java.util.Date(); if (args[1].equals("-lastWeek")) { date = DateUtils.addWeeks(date, -1); } else if (args[1].equals("-lastMonth")) { date = DateUtils.addMonths(date, -1); } else if (args[1].equals("-lastYear")) { date = DateUtils.addYears(date, -1); } else date = null; if (date != null) { SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); fq += "last_load_date:%5B" + sfd.format(date) + "%20TO%20*%5D"; } } Object[] resp = restfulClient .restGet("http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0", hashTable); logger.info("The URL: " + "http://biocache.ala.org.au/ws/occurrences/search?q=multimedia:Image" + fq + "&facets=data_resource_uid&pageSize=0"); if ((Integer) resp[0] == HttpStatus.SC_OK) { String content = resp[1].toString(); logger.debug(resp[1]); if (content != null && content.length() > "[]".length()) { Map map = mapper.readValue(content, Map.class); try { List<java.util.LinkedHashMap<String, String>> list = ((List<java.util.LinkedHashMap<String, String>>) ((java.util.LinkedHashMap) ((java.util.ArrayList) map .get("facetResults")).get(0)).get("fieldResult")); Set<String> arg = new LinkedHashSet<String>(); for (int i = 0; i < list.size(); i++) { java.util.LinkedHashMap<String, String> value = list.get(i); String dataResource = getDataResource(value.get("fq")); Object provider = (loader.getUidInfoSourceMap().get(dataResource)); if (provider != null) { arg.add(provider.toString()); } } logger.info("Set of biocache infosource ids to load: " + arg); args = new String[] {}; args = arg.toArray(args); //handle the situation where biocache-service reports no data resources if (args.length < 1) { logger.error("No biocache data resources found. Unable to load."); System.exit(0); } } catch (Exception e) { logger.error("ERROR: exit process....." + e); e.printStackTrace(); System.exit(0); } } } else { logger.warn("Unable to process url: "); } } } int filesRead = loader.load(filePath, args); //FIX ME - move to config long finish = System.currentTimeMillis(); logger.info(filesRead + " files scanned/loaded in: " + ((finish - start) / 60000) + " minutes " + ((finish - start) / 1000) + " seconds."); System.exit(1); }
From source file:com.seanmadden.fast.ldap.main.Main.java
/** * The Main Event./*from w w w. j a va2 s. co m*/ * * @param args */ @SuppressWarnings("static-access") public static void main(String[] args) { BasicConfigurator.configure(); log.debug("System initializing"); try { Logger.getRootLogger().addAppender( new FileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), "log.log")); } catch (IOException e1) { log.error("Unable to open the log file..?"); } /* * Initialize the configuration engine. */ XMLConfiguration config = new XMLConfiguration(); config.setListDelimiter('|'); /* * Initialize the Command-Line parsing engine. */ CommandLineParser parser = new PosixParser(); Options opts = new Options(); opts.addOption(OptionBuilder.withLongOpt("config-file").hasArg() .withDescription("The configuration file to load").withArgName("config.xml").create("c")); opts.addOption(OptionBuilder.withLongOpt("profile").hasArg().withDescription("The profile to use") .withArgName("Default").create("p")); opts.addOption(OptionBuilder.withLongOpt("password").hasArg().withDescription("Password to connect with") .withArgName("password").create("P")); opts.addOption(OptionBuilder.withLongOpt("debug").hasArg(false).create('d')); opts.addOption(OptionBuilder.withLongOpt("verbose").hasArg(false).create('v')); File configurationFile = new File("config.xml"); try { // Parse the command-line options CommandLine cmds = parser.parse(opts, args); if (!cmds.hasOption('p')) { Logger.getRootLogger().addAppender(new GuiErrorAlerter(Level.ERROR)); } Logger.getRootLogger().setLevel(Level.ERROR); if (cmds.hasOption('v')) { Logger.getRootLogger().setLevel(Level.INFO); } if (cmds.hasOption('d')) { Logger.getRootLogger().setLevel(Level.DEBUG); } log.debug("Enabling configuration file parsing"); // The user has given us a file to parse. if (cmds.hasOption("c")) { configurationFile = new File(cmds.getOptionValue("c")); } log.debug("Config file: " + configurationFile); // Load the configuration file if (configurationFile.exists()) { config.load(configurationFile); } else { log.error("Cannot find config file"); } /* * Convert the profiles into memory */ Vector<ConnectionProfile> profs = new Vector<ConnectionProfile>(); List<?> profList = config.configurationAt("Profiles").configurationsAt("Profile"); for (Object p : profList) { SubnodeConfiguration profile = (SubnodeConfiguration) p; String name = profile.getString("[@name]"); String auth = profile.getString("LdapAuthString"); String server = profile.getString("LdapServerString"); String group = profile.getString("LdapGroupsLocation"); ConnectionProfile prof = new ConnectionProfile(name, server, auth, group); profs.add(prof); } ConnectionProfile prof = null; if (!cmds.hasOption('p')) { /* * Deploy the profile selector, to select a profile */ ProfileSelector profSel = new ProfileSelector(profs); prof = profSel.getSelection(); if (prof == null) { return; } /* * Empty the profiles and load a clean copy - then save it back * to the file */ config.clearTree("Profiles"); for (ConnectionProfile p : profSel.getProfiles()) { config.addProperty("Profiles.Profile(-1)[@name]", p.getName()); config.addProperty("Profiles.Profile.LdapAuthString", p.getLdapAuthString()); config.addProperty("Profiles.Profile.LdapServerString", p.getLdapServerString()); config.addProperty("Profiles.Profile.LdapGroupsLocation", p.getLdapGroupsString()); } config.save(configurationFile); } else { for (ConnectionProfile p : profs) { if (p.getName().equals(cmds.getOptionValue('p'))) { prof = p; break; } } } log.info("User selected " + prof); String password = ""; if (cmds.hasOption('P')) { password = cmds.getOptionValue('P'); } else { password = PasswordPrompter.promptForPassword("Password?"); } if (password.equals("")) { return; } LdapInterface ldap = new LdapInterface(prof.getLdapServerString(), prof.getLdapAuthString(), prof.getLdapGroupsString(), password); /* * Gather options information from the configuration engine for the * specified report. */ Hashtable<String, Hashtable<String, ReportOption>> reportDataStructure = new Hashtable<String, Hashtable<String, ReportOption>>(); List<?> repConfig = config.configurationAt("Reports").configurationsAt("Report"); for (Object p : repConfig) { SubnodeConfiguration repNode = (SubnodeConfiguration) p; // TODO Do something with the report profile. // Allowing the user to deploy "profiles" is a nice feature // String profile = repNode.getString("[@profile]"); String reportName = repNode.getString("[@report]"); Hashtable<String, ReportOption> reportOptions = new Hashtable<String, ReportOption>(); reportDataStructure.put(reportName, reportOptions); // Loop through the options and add each to the table. for (Object o : repNode.configurationsAt("option")) { SubnodeConfiguration option = (SubnodeConfiguration) o; String name = option.getString("[@name]"); String type = option.getString("[@type]"); String value = option.getString("[@value]"); ReportOption ro = new ReportOption(); ro.setName(name); if (type.toLowerCase().equals("boolean")) { ro.setBoolValue(Boolean.parseBoolean(value)); } else if (type.toLowerCase().equals("integer")) { ro.setIntValue(Integer.valueOf(value)); } else { // Assume a string type here then. ro.setStrValue(value); } reportOptions.put(name, ro); log.debug(ro); } } System.out.println(reportDataStructure); /* * At this point, we now need to deploy the reports window to have * the user pick a report and select some happy options to allow * that report to work. Let's go. */ /* * Deploy the Reports selector, to select a report */ Reports.getInstance().setLdapConnection(ldap); ReportsWindow reports = new ReportsWindow(Reports.getInstance().getAllReports(), reportDataStructure); Report report = reports.getSelection(); if (report == null) { return; } /* * Empty the profiles and load a clean copy - then save it back to * the file */ config.clearTree("Reports"); for (Report r : Reports.getInstance().getAllReports()) { config.addProperty("Reports.Report(-1)[@report]", r.getClass().getCanonicalName()); config.addProperty("Reports.Report[@name]", "Standard"); for (ReportOption ro : r.getOptions().values()) { config.addProperty("Reports.Report.option(-1)[@name]", ro.getName()); config.addProperty("Reports.Report.option[@type]", ro.getType()); config.addProperty("Reports.Report.option[@value]", ro.getStrValue()); } } config.save(configurationFile); ProgressBar bar = new ProgressBar(); bar.start(); report.execute(); ASCIIFormatter format = new ASCIIFormatter(); ReportResult res = report.getResult(); format.format(res, new File(res.getForName() + "_" + res.getReportName() + ".txt")); bar.stop(); JOptionPane.showMessageDialog(null, "The report is at " + res.getForName() + "_" + res.getReportName() + ".txt", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("FAST Ldap Searcher", opts); } catch (ConfigurationException e) { e.printStackTrace(); log.fatal("OH EM GEES! Configuration errors."); } catch (Exception e) { e.printStackTrace(); } }