List of usage examples for org.apache.commons.configuration SubnodeConfiguration configurationsAt
public List configurationsAt(String key)
From source file:com.seanmadden.fast.ldap.main.Main.java
/** * The Main Event.//from www .java 2 s. com * * @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(); } }
From source file:com.oltpbenchmark.multitenancy.MuTeBench.java
private static List<String> get_weights(String plugin, SubnodeConfiguration work) { List<String> weight_strings = new LinkedList<String>(); @SuppressWarnings("unchecked") List<SubnodeConfiguration> weights = work.configurationsAt("weights"); boolean weights_started = false; for (SubnodeConfiguration weight : weights) { // stop if second attributed node encountered if (weights_started && weight.getRootNode().getAttributeCount() > 0) { break; }/*from ww w . j av a2 s . co m*/ // start adding node values, if node with attribute equal to current // plugin encountered if (weight.getRootNode().getAttributeCount() > 0 && weight.getRootNode().getAttribute(0).getValue().equals(plugin)) { weights_started = true; } if (weights_started) { weight_strings.add(weight.getString("")); } } return weight_strings; }
From source file:com.oltpbenchmark.DBWorkload.java
private static List<String> get_weights(String plugin, SubnodeConfiguration work) { List<String> weight_strings = new LinkedList<String>(); @SuppressWarnings("unchecked") List<SubnodeConfiguration> weights = work.configurationsAt("weights"); boolean weights_started = false; for (SubnodeConfiguration weight : weights) { // stop if second attributed node encountered if (weights_started && weight.getRootNode().getAttributeCount() > 0) { break; }// ww w. j a va 2s .c o m //start adding node values, if node with attribute equal to current plugin encountered if (weight.getRootNode().getAttributeCount() > 0 && weight.getRootNode().getAttribute(0).getValue().equals(plugin)) { weights_started = true; } if (weights_started) { weight_strings.add(weight.getString("")); } } return weight_strings; }
From source file:fr.openfarm.jmx.utils.ProxyConfig.java
@Override public void afterPropertiesSet() throws Exception { log.info("set Up Proxy Configuration"); jmxAccess = new HashMap<String, JmxLoginPass>(); String fileName = System.getProperty("configFilePath"); if (System.getProperty("configFilePath") != null) { try {/*from w w w . jav a2s . co m*/ XMLConfiguration xmlConfiguration = new XMLConfiguration(fileName); SubnodeConfiguration accessList = xmlConfiguration.configurationAt("accessList"); List<HierarchicalConfiguration> loginPassConfs = accessList.configurationsAt("accessConf"); for (HierarchicalConfiguration loginPassConf : loginPassConfs) { JmxLoginPass jmxLoginPass = new JmxLoginPass(); jmxLoginPass.setLogin(loginPassConf.getString("login")); jmxLoginPass.setPassword(loginPassConf.getString("password")); jmxAccess.put(loginPassConf.getString("key"), jmxLoginPass); } } catch (Exception e) { log.error("Error while reading conf file : " + fileName, e); } } else { log.info("no configuration given to the jvm by param -DconfigFilePath"); } }
From source file:com.intuit.tank.proxy.config.CommonsProxyConfiguration.java
/** * @param string// w ww.j ava 2s .c o m * @return */ private Set<ConfigInclusionExclusionRule> parseInclusionExclusions(String key) { Set<ConfigInclusionExclusionRule> ret = new HashSet<ConfigInclusionExclusionRule>(); SubnodeConfiguration groupConfig = config.configurationAt(key); if (groupConfig != null) { @SuppressWarnings("unchecked") List<HierarchicalConfiguration> list = groupConfig.configurationsAt("rule"); for (HierarchicalConfiguration c : list) { ret.add(new ConfigInclusionExclusionRule(getTransactionPart(c), c.getString("@header", "all"), getMatchType(c), c.getString(""))); } } return ret; }
From source file:com.boozallen.cognition.ingest.storm.topology.ConfigurableIngestTopology.java
/** * Gets a topology builder and set of storm bolt configurations. Initializes the bolts and sets them with the * topology builder.//from w w w. j a v a2 s .c o m * * @param builder storm topology builder * @param boltsConf component configurations * @param spout type of storm component being added (spout/bolt) * @throws ConfigurationException */ void configureBolts(TopologyBuilder builder, SubnodeConfiguration boltsConf, String spout) throws ConfigurationException { String prevComponent = spout; // bolts subscribe to other bolts by number HashMap<Integer, String> boltNumberToId = new HashMap<>(); List<HierarchicalConfiguration> bolts = boltsConf.configurationsAt(BOLT); for (HierarchicalConfiguration bolt : bolts) { String boltType = bolt.getString(TYPE); Configuration boltConf = bolt.configurationAt(CONF); int boltNum = bolt.getInt(NUMBER_ATTRIBUTE); String boltId = String.format("%02d_%s", boltNum, boltType); boltNumberToId.put(boltNum, boltId); String subscribingToComponent = getSubscribingToComponent(prevComponent, boltNumberToId, boltConf); logger.info("{} subscribing to {}", boltId, subscribingToComponent); IComponent baseComponent = buildComponent(boltType, boltConf); StormParallelismConfig stormParallelismConfig = getStormParallelismConfig(boltConf); BoltDeclarer declarer = buildBoltDeclarer(builder, stormParallelismConfig, boltId, baseComponent); configureTickFrequency(boltConf, declarer); configureStreamGrouping(subscribingToComponent, boltConf, declarer); prevComponent = boltId; boltNum++; } }
From source file:edu.kit.dama.mdm.core.MetaDataManagement.java
/** * Load configuration from XML-File/*from ww w.jav a2 s . c o m*/ */ private void loadConfiguration() { String firstImplementation = null; String firstPersistenceUnit = null; HierarchicalConfiguration hc = null; List<String> persistenceUnits = null; URL configURL = null; try { configURL = DataManagerSettings.getConfigurationURL(); LOGGER.debug("Loading configuration from {}", configURL); hc = new HierarchicalConfiguration(new XMLConfiguration(configURL)); LOGGER.debug("Configuration successfully loaded"); } catch (ConfigurationException ex) { // error in configuration // reason see debug log message: LOGGER.error("Failed to load configuration.", ex); throw new RuntimeException(ex); } SubnodeConfiguration configurationAt = hc.configurationAt(CONFIG_ROOT); List fields = configurationAt.configurationsAt(CONFIG_PERSISTENCE_IMPL); LOGGER.debug("Found {} configured persistence implementations", fields.size()); persistenceUnitMap = new HashMap<>(); persistenceClassMap = new HashMap<>(); persistenceUnitDefaultMap = new HashMap<>(); String implementationName; IPersistenceFactory iPersistenceFactory = null; for (Iterator it = fields.iterator(); it.hasNext();) { HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next(); LOGGER.debug("Reading sub-configuration"); // First get all persistence units. persistenceUnits = new ArrayList<>(); try { List<HierarchicalConfiguration> persistenceUnitsList = sub .configurationsAt(CONFIG_PERSISTENCE_UNIT); if (persistenceUnitsList == null) { persistenceUnitsList = new LinkedList<>(); } LOGGER.debug("Configuration contains {} persistence units.", persistenceUnitsList.size()); firstPersistenceUnit = null; for (HierarchicalConfiguration item : persistenceUnitsList) { String value = item.getString("."); String defaultAttribute = item.getString("[@default]"); LOGGER.debug("PersistenceUnit found: " + value); LOGGER.debug("@default = {}", defaultAttribute); if (Boolean.parseBoolean(defaultAttribute)) { if (firstPersistenceUnit == null) { LOGGER.debug("{} is used as default persistence unit.", value); firstPersistenceUnit = value; } else { LOGGER.warn( "{} is an additional persistence unit defined as default. We'll ignore this.", value); } } LOGGER.debug("Adding persistence unit to list of units."); persistenceUnits.add(value); } } catch (Exception any) { LOGGER.error("Failed to read persistence units.", any); } LOGGER.debug("firstPersistenceUnit: " + firstPersistenceUnit); if ((persistenceUnits.size() > 0) && (firstPersistenceUnit == null)) { LOGGER.debug("No default persistence unit defined. Using first entry ({})", persistenceUnits.get(0)); firstPersistenceUnit = persistenceUnits.get(0); } LOGGER.debug("Getting implementation name."); implementationName = sub.getString(CONFIG_PERSISTENCE_NAME); LOGGER.debug("Implementation name '{}' found.", implementationName); if (firstImplementation == null) { LOGGER.debug("Using implementation '{}' as first implementation.", implementationName); firstImplementation = implementationName; } LOGGER.debug("Testing implementation '{}'", implementationName); if (sub.containsKey(CONFIG_DEFAULT_PERSISTENCE)) { LOGGER.debug("'{}' is configured as default implementation.", implementationName); if (defaultImplementation != null) { LOGGER.warn("{} is an additional implementation defined as default. We'll ignore this.", implementationName); } else { defaultImplementation = implementationName; } } Class<?> loadClass; boolean success = false; String persistenceClass = sub.getString(CONFIG_PERSISTENCE_CLASS); try { LOGGER.debug("Loading class '{}': ", persistenceClass); loadClass = getClass().getClassLoader().loadClass(persistenceClass); LOGGER.debug("Checking IPersistenceFactory.class.assignableFrom({})", persistenceClass); success = IPersistenceFactory.class.isAssignableFrom(loadClass); iPersistenceFactory = null; if (success) { LOGGER.debug("Creating instance of class {}", persistenceClass); iPersistenceFactory = (IPersistenceFactory) loadClass.newInstance(); LOGGER.debug("Persistence factory successfully instantiated."); } else { LOGGER.error("IPersistenceFactory seems not to be assignable from class {}", persistenceClass); } } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) { LOGGER.error("Failed to create instance of persistence implementation " + persistenceClass, ex); success = false; } if (success) { persistenceUnitMap.put(implementationName, persistenceUnits); persistenceClassMap.put(implementationName, iPersistenceFactory); persistenceUnitDefaultMap.put(implementationName, firstPersistenceUnit); } else { throw new edu.kit.dama.mdm.core.exception.ConfigurationException( "Failed to initialize persistence factory from URL '" + configURL + "'. See logfile for details."); } } if (defaultImplementation == null) { LOGGER.debug("Default implementation not set, yet. Using first one ({}) as default.", firstImplementation); defaultImplementation = firstImplementation; } }