List of usage examples for org.apache.commons.configuration XMLConfiguration load
private void load(InputSource source) throws ConfigurationException
From source file:com.vaushell.superpipes.App.java
/** * Main method./* www .j a v a2s .com*/ * * @param args Command line arguments * @throws Exception */ public static void main(final String... args) throws Exception { // My config final XMLConfiguration config = new XMLConfiguration(); config.setDelimiterParsingDisabled(true); final long delay; final Path datas; switch (args.length) { case 1: { config.load(args[0]); datas = Paths.get("datas"); delay = 10000L; break; } case 2: { config.load(args[0]); datas = Paths.get(args[1]); delay = 10000L; break; } case 3: { config.load(args[0]); datas = Paths.get(args[1]); delay = Long.parseLong(args[2]); break; } default: { config.load("conf/configuration.xml"); datas = Paths.get("datas"); delay = 10000L; break; } } final Dispatcher dispatcher = new Dispatcher(); dispatcher.init(config, datas, new VC_SystemInputFactory()); // Run dispatcher.start(); // Wait try { Thread.sleep(delay); } catch (final InterruptedException ex) { // Ignore } // Stop dispatcher.stopAndWait(); }
From source file:com.seanmadden.fast.ldap.main.Main.java
/** * The Main Event.//from w ww. j a v a2s . c o 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(); } }
From source file:com.bytelightning.opensource.pokerface.HelloWorldScriptTest.java
@BeforeClass public static void setUpBeforeClass() throws Exception { PrevSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); PrevHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); proxy = new PokerFace(); XMLConfiguration conf = new XMLConfiguration(); conf.load(ProxySpecificTest.class.getResource("/HelloWorldTestConfig.xml")); proxy.config(conf);/*from ww w . j a va 2 s . co m*/ boolean started = proxy.start(); Assert.assertTrue("Successful proxy start", started); SSLContext sc = SSLContext.getInstance("TLS"); TrustManager[] trustAllCertificates = { new X509TrustAllManager() }; sc.init(null, trustAllCertificates, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; // Just allow them all. } }); }
From source file:com.bytelightning.opensource.pokerface.ProxySpecificTest.java
/** * Configure both servers/* ww w . j a v a 2s . c om*/ */ @BeforeClass public static void setUpBeforeClass() throws Exception { RemoteTarget = new SunHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 8088), null); RemoteTarget.start(new HttpHandler() { @Override public void handle(HttpExchange exchange) throws IOException { OnRemoteTargetRequest(exchange); } }); proxy = new PokerFace(); XMLConfiguration conf = new XMLConfiguration(); conf.load(ProxySpecificTest.class.getResource("/ProxySpecificTestConfig.xml")); proxy.config(conf); boolean started = proxy.start(); Assert.assertTrue("Successful proxy start", started); }
From source file:edu.hawaii.soest.pacioos.text.TextSourceFactory.java
/** * Configure and return a simple text-based source driver instance using the given XML-based * configuration file./* w w w . j a v a2 s.c o m*/ * * @param configLocation the path to the file on disk or in a jar * @return a new instance of a subclassed SimpleTextSource * @throws ConfigurationException */ public static SimpleTextSource getSimpleTextSource(String configLocation) throws ConfigurationException { // Get the per-driver configuration XMLConfiguration xmlConfig = new XMLConfiguration(); xmlConfig.setListDelimiter(new String("|").charAt(0)); xmlConfig.load(configLocation); String connectionType = xmlConfig.getString("connectionType"); if (log.isDebugEnabled()) { Iterator i = xmlConfig.getKeys(); while (i.hasNext()) { String key = (String) i.next(); String value = xmlConfig.getString(key); log.debug(key + ":\t\t" + value); } } // return the correct configuration type if (connectionType.equals("file")) { FileTextSource fileTextSource = getFileTextSource(xmlConfig); String filePath = xmlConfig.getString("connectionParams.filePath"); fileTextSource.setDataFilePath(filePath); simpleTextSource = (SimpleTextSource) fileTextSource; } else if (connectionType.equals("socket")) { SocketTextSource socketTextSource = getSocketTextSource(xmlConfig); String hostName = xmlConfig.getString("connectionParams.hostName"); socketTextSource.setHostName(hostName); int hostPort = xmlConfig.getInt("connectionParams.hostPort"); socketTextSource.setHostPort(hostPort); simpleTextSource = (SimpleTextSource) socketTextSource; } else if (connectionType.equals("serial")) { SerialTextSource serialTextSource = getSerialTextSource(xmlConfig); String serialPort = xmlConfig.getString("connectionParams.serialPort"); serialTextSource.setSerialPort(serialPort); int baudRate = xmlConfig.getInt("connectionParams.serialPortParams.baudRate"); serialTextSource.setBaudRate(baudRate); int dataBits = xmlConfig.getInt("connectionParams.serialPortParams.dataBits"); serialTextSource.setDataBits(dataBits); int stopBits = xmlConfig.getInt("connectionParams.serialPortParams.stopBits"); serialTextSource.setStopBits(stopBits); String parity = xmlConfig.getString("connectionParams.serialPortParams.parity"); serialTextSource.setParity(parity); simpleTextSource = (SimpleTextSource) serialTextSource; } else { throw new ConfigurationException("There was an issue parsing the configuration." + " The connection type of " + connectionType + " wasn't recognized."); } return simpleTextSource; }
From source file:lh.api.showcase.server.config.ConfigurationUtils.java
public static synchronized XMLConfiguration getConfig() { XMLConfiguration config = null; InputStream in = Thread.currentThread().getContextClassLoader() .getResourceAsStream("lh/api/showcase/Showcase-settings.xml"); if (in != null) { logger.info("Load configuration"); config = new XMLConfiguration(); try {// w ww.j a v a 2 s . c om config.load(in); } catch (ConfigurationException e) { logger.severe("Error occurred while opeing config file"); } catch (Exception e) { logger.severe("Error occurred while opeing config file: " + e.getMessage()); throw e; } finally { try { in.close(); } catch (IOException e) { } } } else { logger.info("NO configuration file found"); } return config; }
From source file:com.norconex.jef4.status.JobSuiteStatusSnapshot.java
public static JobSuiteStatusSnapshot newSnapshot(File suiteIndex) throws IOException { //--- Ensure file looks good --- if (suiteIndex == null) { throw new IllegalArgumentException("Suite index file cannot be null."); }/*from w ww. j a v a 2 s . c o m*/ if (!suiteIndex.exists()) { return null; } if (!suiteIndex.isFile()) { throw new IllegalArgumentException("Suite index is not a file: " + suiteIndex.getAbsolutePath()); } //--- Load XML file --- String suiteName = FileUtil.fromSafeFileName(FilenameUtils.getBaseName(suiteIndex.getPath())); XMLConfiguration xml = new XMLConfiguration(); ConfigurationUtil.disableDelimiterParsing(xml); try { xml.load(suiteIndex); } catch (ConfigurationException e) { throw new IOException("Could not load suite index: " + suiteIndex, e); } //--- LogManager --- ILogManager logManager = ConfigurationUtil.newInstance(xml, "logManager"); //--- Load status tree --- IJobStatusStore serial = ConfigurationUtil.newInstance(xml, "statusStore"); return new JobSuiteStatusSnapshot(loadTreeNode(null, xml.configurationAt("job"), suiteName, serial), logManager); }
From source file:edu.cornell.med.icb.R.RUtils.java
/** * Make an an XMLConfiguration fo RConnectionPool. * @param hostname the hostname to connect to * @param port the port on localhost to connect to * @param username the username to use for the connection * @param password the password to use for the connection * @return the XMLConfiguration/* w w w . ja va2 s . c o m*/ * @throws ConfigurationException problem configuring with specified parameters */ public static XMLConfiguration makeConfiguration(final String hostname, final int port, final String username, final String password) throws ConfigurationException { final StringBuilder xml = new StringBuilder(); xml.append("<?xml version='1.0' encoding='UTF-8'?>"); xml.append("<RConnectionPool xsi:noNamespaceSchemaLocation='RConnectionPool.xsd'"); xml.append(" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"); xml.append("<RConfiguration publish='false'>"); xml.append("<RServer "); xml.append("host='").append(hostname).append("' "); xml.append("port='").append(port).append("' "); if (username != null) { xml.append("username='").append(username).append("' "); } if (password != null) { xml.append("password='").append(password).append("' "); } xml.append("/>"); xml.append("</RConfiguration>"); xml.append("</RConnectionPool>"); final XMLConfiguration configuration = new XMLConfiguration(); configuration.load(new StringReader(xml.toString())); return configuration; }
From source file:cn.quickj.Setting.java
private static void loadApplicationConfig() { XMLConfiguration config; try {// w w w . j ava 2s. c om config = new XMLConfiguration(); // ?????? config.setDelimiterParsingDisabled(true); String appconfigPath = webRoot + "WEB-INF/appconfig.xml"; config.load(appconfigPath); } catch (Exception e) { config = null; } String className = null; if (config != null) className = config.getString("class", null); if (className != null) { try { Class<?> clazz = Class.forName(className); appconfig = (ApplicationConfig) clazz.newInstance(); appconfig.init(config); } catch (Exception e) { e.printStackTrace(); log.error("?appconfig.xml?!" + e.getCause()); appconfig = null; } } }
From source file:com.bibisco.test.AllTests.java
private static XMLConfiguration getXMLConfiguration() throws ConfigurationException { XMLConfiguration lXMLConfiguration = null; lXMLConfiguration = new XMLConfiguration(); lXMLConfiguration.setEncoding(ENCODING); lXMLConfiguration.setBasePath(CONFIG_DIR); lXMLConfiguration.load(CONFIG_FILENAME); lXMLConfiguration.setExpressionEngine(new XPathExpressionEngine()); return lXMLConfiguration; }