List of usage examples for org.apache.commons.configuration PropertiesConfiguration PropertiesConfiguration
public PropertiesConfiguration(URL url) throws ConfigurationException
From source file:edu.berkeley.sparrow.daemon.SparrowDaemon.java
public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser(); parser.accepts("c", "configuration file (required)").withRequiredArg().ofType(String.class); parser.accepts("help", "print help statement"); OptionSet options = parser.parse(args); if (options.has("help") || !options.has("c")) { parser.printHelpOn(System.out); System.exit(-1);//from www. j a va 2s .c o m } // Set up a simple configuration that logs on the console. BasicConfigurator.configure(); Logging.configureAuditLogging(); String configFile = (String) options.valueOf("c"); Configuration conf = new PropertiesConfiguration(configFile); SparrowDaemon sparrowDaemon = new SparrowDaemon(); sparrowDaemon.initialize(conf); }
From source file:joshelser.as2015.query.Query.java
public static void main(String[] args) throws Exception { JCommander commander = new JCommander(); final Opts options = new Opts(); commander.addObject(options);/*w w w. j ava 2 s . c om*/ commander.setProgramName("Query"); try { commander.parse(args); } catch (ParameterException ex) { commander.usage(); System.err.println(ex.getMessage()); System.exit(1); } ClientConfiguration conf = ClientConfiguration.loadDefault(); if (null != options.clientConfFile) { conf = new ClientConfiguration(new PropertiesConfiguration(options.clientConfFile)); } conf.withInstance(options.instanceName).withZkHosts(options.zookeepers); ZooKeeperInstance inst = new ZooKeeperInstance(conf); Connector conn = inst.getConnector(options.user, new PasswordToken(options.password)); BatchScanner bs = conn.createBatchScanner(options.table, Authorizations.EMPTY, 16); try { bs.setRanges(Collections.singleton(new Range())); final Text categoryText = new Text("category"); bs.fetchColumn(categoryText, new Text("name")); bs.fetchColumn(new Text("review"), new Text("score")); bs.fetchColumn(new Text("review"), new Text("userId")); bs.addScanIterator(new IteratorSetting(50, "wri", WholeRowIterator.class)); final Text colf = new Text(); Map<String, List<Integer>> scoresByUser = new HashMap<>(); for (Entry<Key, Value> entry : bs) { SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue()); Iterator<Entry<Key, Value>> iter = row.entrySet().iterator(); if (!iter.hasNext()) { // row was empty continue; } Entry<Key, Value> categoryEntry = iter.next(); categoryEntry.getKey().getColumnFamily(colf); if (!colf.equals(categoryText)) { throw new IllegalArgumentException("Unknown!"); } if (!categoryEntry.getValue().toString().equals("books")) { // not a book review continue; } if (!iter.hasNext()) { continue; } Entry<Key, Value> reviewScore = iter.next(); if (!iter.hasNext()) { continue; } Entry<Key, Value> reviewUserId = iter.next(); String userId = reviewUserId.getValue().toString(); if (userId.equals("unknown")) { // filter unknow user id continue; } List<Integer> scores = scoresByUser.get(userId); if (null == scores) { scores = new ArrayList<>(); scoresByUser.put(userId, scores); } scores.add(Float.valueOf(reviewScore.getValue().toString()).intValue()); } for (Entry<String, List<Integer>> entry : scoresByUser.entrySet()) { int sum = 0; for (Integer val : entry.getValue()) { sum += val; } System.out.println(entry.getKey() + " => " + new Float(sum) / entry.getValue().size()); } } finally { bs.close(); } }
From source file:ch.epfl.eagle.daemon.EagleDaemon.java
public static void main(String[] args) throws Exception { OptionParser parser = new OptionParser(); parser.accepts("c", "configuration file (required)").withRequiredArg().ofType(String.class); parser.accepts("help", "print help statement"); OptionSet options = parser.parse(args); if (options.has("help") || !options.has("c")) { parser.printHelpOn(System.out); System.exit(-1);//from ww w. j av a 2s .co m } // Set up a simple configuration that logs on the console. BasicConfigurator.configure(); Logging.configureAuditLogging(); String configFile = (String) options.valueOf("c"); Configuration conf = new PropertiesConfiguration(configFile); EagleDaemon eagleDaemon = new EagleDaemon(); eagleDaemon.initialize(conf); }
From source file:gobblin.compaction.hive.CompactionRunner.java
public static void main(String[] args) throws IOException, ConfigurationException { properties = CliOptions.parseArgs(MRCompactionRunner.class, args); File compactionConfigDir = new File(properties.getProperty(COMPACTION_CONFIG_DIR)); File[] listOfFiles = compactionConfigDir.listFiles(); if (listOfFiles == null || listOfFiles.length == 0) { System.err.println("No compaction configuration files found under " + compactionConfigDir); System.exit(1);//from w w w . j a v a 2 s. c o m } int numOfJobs = 0; for (File file : listOfFiles) { if (file.isFile() && !file.getName().startsWith(".")) { numOfJobs++; } } LOG.info("Found " + numOfJobs + " compaction tasks."); try (PrintWriter pw = new PrintWriter(new OutputStreamWriter( new FileOutputStream(properties.getProperty(TIMING_FILE, TIMING_FILE_DEFAULT)), Charset.forName("UTF-8")))) { for (File file : listOfFiles) { if (file.isFile() && !file.getName().startsWith(".")) { Configuration jobConfig = new PropertiesConfiguration(file.getAbsolutePath()); jobProperties = ConfigurationConverter.getProperties(jobConfig); long startTime = System.nanoTime(); compact(); long endTime = System.nanoTime(); long elapsedTime = endTime - startTime; double seconds = TimeUnit.NANOSECONDS.toSeconds(elapsedTime); pw.printf("%s: %f%n", file.getAbsolutePath(), seconds); } } } }
From source file:com.dattack.dbcopy.cli.DbCopyCli.java
/** * The <code>main</code> method. * * @param args/* w w w.j av a2 s. c om*/ * the program arguments */ public static void main(final String[] args) { final Options options = createOptions(); try { final CommandLineParser parser = new DefaultParser(); final CommandLine cmd = parser.parse(options, args); final String[] filenames = cmd.getOptionValues(FILE_OPTION); final String[] jobNames = cmd.getOptionValues(JOB_NAME_OPTION); final String[] propertiesFiles = cmd.getOptionValues(PROPERTIES_OPTION); HashSet<String> jobNameSet = null; if (jobNames != null) { jobNameSet = new HashSet<>(Arrays.asList(jobNames)); } CompositeConfiguration configuration = new CompositeConfiguration(); if (propertiesFiles != null) { for (final String fileName : propertiesFiles) { configuration.addConfiguration(new PropertiesConfiguration(fileName)); } } final DbCopyEngine ping = new DbCopyEngine(); ping.execute(filenames, jobNameSet, configuration); } catch (@SuppressWarnings("unused") final ParseException e) { showUsage(options); } catch (final ConfigurationException | DattackParserException e) { System.err.println(e.getMessage()); } }
From source file:de.berber.kindle.annotator.Main.java
/** * Main function of PDFAnnotator. For command line parameters see the {@see * Options} class./*from w w w .j av a2s . co m*/ * * @param args * List of command line parameters. */ public static void main(String[] args) { final CompositeConfiguration cc = new CompositeConfiguration(); try { // configure logging final PatternLayout layout = new PatternLayout("%d{ISO8601} %-5p [%t] %c: %m%n"); final ConsoleAppender consoleAppender = new ConsoleAppender(layout); Logger.getRootLogger().addAppender(consoleAppender); Logger.getRootLogger().setLevel(Level.WARN); // read commandline final Options options = new Options(); final CmdLineParser parser = new CmdLineParser(options); parser.setUsageWidth(80); try { // parse the arguments. parser.parseArgument(args); if (options.help) { parser.printUsage(System.err); return; } } catch (CmdLineException e) { // if there's a problem in the command line, // you'll get this exception. this will report // an error message. System.err.println(e.getMessage()); System.err.println("Usage:"); // print the list of available options parser.printUsage(System.err); System.err.println(); // print option sample. This is useful some time System.err.println(" Example: java -jar <jar> " + parser.printExample(ExampleMode.ALL)); return; } // read default configuration file final URL defaultURL = PDFAnnotator.class.getClassLoader() .getResource("de/berber/kindle/annotator/PDFAnnotator.default"); // read config file specified at the command line if (options.config != null) { final File configFile = new File(options.config); if (!configFile.exists() || !configFile.canRead()) { LOG.error("Specified configuration file does not exist."); } else { cc.addConfiguration(new PropertiesConfiguration(configFile)); } } cc.addConfiguration(new PropertiesConfiguration(defaultURL)); final WorkingList model = new WorkingList(); final WorkQueue queue = new WorkQueue(cc, model); AbstractMain view = null; if (options.noGUI) { view = new BatchMain(options, model); } else { view = new MainWindow(options, model); } view.run(); if (options.noGUI) { queue.stop(); } } catch (Exception ex) { LOG.error("Error while executing Kindle Annotator. Please report a bug."); ex.printStackTrace(); } }
From source file:fr.dudie.acrachilisync.tools.MigrateDescriptions.java
public static void main(final String[] args) throws AuthenticationException, ConfigurationException, SynchronizationException { final MigrateDescriptions updater = new MigrateDescriptions( new PropertiesConfiguration("acrachilisync.properties")); updater.upgrade(1, 2);/* w w w .j a v a 2 s . co m*/ }
From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java
/** * Main entry point for the Apiman Gateway micro service. * @param args the arguments/*from ww w . j av a 2 s . c om*/ * @throws Exception when any unhandled exception occurs */ public static final void main(String[] args) throws Exception { String isTestModeString = Systems.getEnvVarOrSystemProperty(APIMAN_GATEWAY_TESTMODE, "false"); boolean isTestMode = "true".equalsIgnoreCase(isTestModeString); if (isTestMode) log.info("Apiman Gateway Running in TestMode"); String isSslString = Systems.getEnvVarOrSystemProperty(APIMAN_GATEWAY_SSL, "false"); isSsl = "true".equalsIgnoreCase(isSslString); log.info("Apiman Gateway running in SSL: " + isSsl); String protocol = "http"; if (isSsl) protocol = "https"; URL elasticEndpoint = null; File gatewayConfigFile = new File(APIMAN_GATEWAY_PROPERTIES); String esUsername = null; String esPassword = null; if (gatewayConfigFile.exists()) { PropertiesConfiguration config = new PropertiesConfiguration(gatewayConfigFile); esUsername = config.getString("es.username"); esPassword = config.getString("es.password"); if (Utils.isNotNullOrEmpty(esPassword)) esPassword = new String(Base64.getDecoder().decode(esPassword), StandardCharsets.UTF_8).trim(); setConfigProp(APIMAN_GATEWAY_ES_USERNAME, esUsername); setConfigProp(APIMAN_GATEWAY_ES_PASSWORD, esPassword); } log.info(esUsername + esPassword); // Require ElasticSearch and the Gateway Services to to be up before proceeding if (isTestMode) { URL url = new URL(protocol + "://localhost:9200"); elasticEndpoint = waitForDependency(url, "elasticsearch-v1", "status", "200", esUsername, esPassword); } else { String defaultEsUrl = protocol + "://elasticsearch-v1:9200"; String esURL = Systems.getEnvVarOrSystemProperty(APIMAN_GATEWAY_ELASTICSEARCH_URL, defaultEsUrl); URL url = new URL(esURL); elasticEndpoint = waitForDependency(url, "elasticsearch-v1", "status", "200", esUsername, esPassword); log.info("Found " + elasticEndpoint); } File usersFile = new File(APIMAN_GATEWAY_USER_PATH); if (usersFile.exists()) { setConfigProp(Users.USERS_FILE_PROP, APIMAN_GATEWAY_USER_PATH); } log.info("** ******************************************** **"); Fabric8GatewayMicroService microService = new Fabric8GatewayMicroService(elasticEndpoint); if (isSsl) { microService.startSsl(); microService.joinSsl(); } else { microService.start(); microService.join(); } }
From source file:au.edu.flinders.ehl.filmweekly.FwImporter.java
/** * Main method for the class//from w w w. java 2 s .com * * @param args array of command line arguments */ public static void main(String[] args) { // before we do anything, output some useful information for (int i = 0; i < APP_HEADER.length; i++) { System.out.println(APP_HEADER[i]); } // parse the command line options CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(createOptions(), args); } catch (org.apache.commons.cli.ParseException e) { // something bad happened so output help message printCliHelp("Error in parsing options:\n" + e.getMessage()); } // get and check on the log4j properties path option if required if (cmd.hasOption("log4j") == true) { String log4jPath = cmd.getOptionValue("log4j"); if (FileUtils.isAccessible(log4jPath) == false) { printCliHelp("Unable to access the specified log4j properties file\n " + log4jPath); } // configure the log4j framework PropertyConfigurator.configure(log4jPath); } // get and check on the properties path option String propertiesPath = cmd.getOptionValue("properties"); if (FileUtils.isAccessible(propertiesPath) == false) { printCliHelp("Unable to access the specified properties file\n " + propertiesPath); } // get and check on the input file path option String inputPath = cmd.getOptionValue("input"); if (FileUtils.isAccessible(inputPath) == false) { printCliHelp("Unable to access the specified input file"); } // open the properties file Configuration config = null; try { config = new PropertiesConfiguration(propertiesPath); } catch (ConfigurationException e) { printCliHelp("Unable to read the properties file file: \n" + e.getMessage()); } // check to make sure all of the required configuration properties are present for (int i = 0; i < REQD_PROPERTIES.length; i++) { if (config.containsKey(REQD_PROPERTIES[i]) == false) { printCliHelp("Unable to find the required property: " + REQD_PROPERTIES[i]); } } if (cmd.hasOption("debug_coord_list") == true) { // output debug info logger.debug("undertaking the debug-coord-list task"); // undertake the debug coordinate list task if (FileUtils.doesFileExist(cmd.getOptionValue("debug_coord_list")) == true) { printCliHelp("the debug_coord_list file already exists"); } else { CoordList list = new CoordList(inputPath, cmd.getOptionValue("debug_coord_list")); try { list.openFiles(); list.doTask(); } catch (IOException e) { logger.error("unable to undertake the debug-coord-list task", e); errorExit(); } System.out.println("Task completed"); System.exit(0); } } if (cmd.hasOption("debug_json_list") == true) { // output debug info logger.debug("undertaking the debug-json-list task"); // undertake the debug coordinate list task if (FileUtils.doesFileExist(cmd.getOptionValue("debug_json_list")) == true) { printCliHelp("the debug_json_list file already exists"); } else { JsonList list = new JsonList(inputPath, cmd.getOptionValue("debug_json_list")); try { list.openFiles(); list.doTask(); } catch (IOException e) { logger.error("unable to undertake the debug_json_list task", e); errorExit(); } System.out.println("Task completed"); System.exit(0); } } // if no debug options present assume import System.out.println("Importing data into the database."); System.out.println( "*Note* if this input file has been processed before duplicate records *will* be created."); // get a connection to the database try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception e) { logger.error("unable to load the MySQL database classes", e); errorExit(); } Connection database = null; //private static final String[] REQD_PROPERTIES = {"db-host", "db-user", "db-password", "db-name"}; String connectionString = "jdbc:mysql://" + config.getString(REQD_PROPERTIES[0]) + "/" + config.getString(REQD_PROPERTIES[1]) + "?user=" + config.getString(REQD_PROPERTIES[2]) + "&password=" + config.getString(REQD_PROPERTIES[3]); try { database = DriverManager.getConnection(connectionString); } catch (SQLException e) { logger.error("unable to connect to the MySQL database", e); errorExit(); } // do the import DataImporter importer = new DataImporter(database, inputPath); try { importer.openFiles(); importer.doTask(); System.out.println("Task completed"); System.exit(0); } catch (IOException e) { logger.error("unable to complete the import"); errorExit(); } catch (ImportException e) { logger.error("unable to complete the import"); errorExit(); } finally { // play nice and tidy up try { database.close(); } catch (SQLException e) { logger.error("Unable to close the database connection: ", e); } } }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java
public static void main(String[] args) { List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); String oldMSKey = null;/*w w w . j a v a 2 s . c o m*/ String oldDBKey = null; String newMSKey = null; String newDBKey = null; //Parse command-line args while (iter.hasNext()) { String arg = iter.next(); // Old MS Key if (arg.equals("-m")) { oldMSKey = iter.next(); } // Old DB Key if (arg.equals("-d")) { oldDBKey = iter.next(); } // New MS Key if (arg.equals("-n")) { newMSKey = iter.next(); } // New DB Key if (arg.equals("-e")) { newDBKey = iter.next(); } } if (oldMSKey == null || oldDBKey == null) { System.out.println("Existing MS secret key or DB secret key is not provided"); usage(); return; } if (newMSKey == null && newDBKey == null) { System.out.println("New MS secret key and DB secret are both not provided"); usage(); return; } final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); final Properties dbProps; EncryptionSecretKeyChanger keyChanger = new EncryptionSecretKeyChanger(); StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); keyChanger.initEncryptor(encryptor, oldMSKey); dbProps = new EncryptableProperties(encryptor); PropertiesConfiguration backupDBProps = null; System.out.println("Parsing db.properties file"); try { dbProps.load(new FileInputStream(dbPropsFile)); backupDBProps = new PropertiesConfiguration(dbPropsFile); } catch (FileNotFoundException e) { System.out.println("db.properties file not found while reading DB secret key" + e.getMessage()); } catch (IOException e) { System.out.println("Error while reading DB secret key from db.properties" + e.getMessage()); } catch (ConfigurationException e) { e.printStackTrace(); } String dbSecretKey = null; try { dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret"); } catch (EncryptionOperationNotPossibleException e) { System.out.println("Failed to decrypt existing DB secret key from db.properties. " + e.getMessage()); return; } if (!oldDBKey.equals(dbSecretKey)) { System.out.println("Incorrect MS Secret Key or DB Secret Key"); return; } System.out.println("Secret key provided matched the key in db.properties"); final String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); if (newMSKey == null) { System.out.println("No change in MS Key. Skipping migrating db.properties"); } else { if (!keyChanger.migrateProperties(dbPropsFile, dbProps, newMSKey, newDBKey)) { System.out.println("Failed to update db.properties"); return; } else { //db.properties updated successfully if (encryptionType.equals("file")) { //update key file with new MS key try { FileWriter fwriter = new FileWriter(keyFile); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(newMSKey); bwriter.close(); } catch (IOException e) { System.out.println("Failed to write new secret to file. Please update the file manually"); } } } } boolean success = false; if (newDBKey == null || newDBKey.equals(oldDBKey)) { System.out.println("No change in DB Secret Key. Skipping Data Migration"); } else { EncryptionSecretKeyChecker.initEncryptorForMigration(oldMSKey); try { success = keyChanger.migrateData(oldDBKey, newDBKey); } catch (Exception e) { System.out.println("Error during data migration"); e.printStackTrace(); success = false; } } if (success) { System.out.println("Successfully updated secret key(s)"); } else { System.out.println("Data Migration failed. Reverting db.properties"); //revert db.properties try { backupDBProps.save(); } catch (ConfigurationException e) { e.printStackTrace(); } if (encryptionType.equals("file")) { //revert secret key in file try { FileWriter fwriter = new FileWriter(keyFile); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(oldMSKey); bwriter.close(); } catch (IOException e) { System.out.println("Failed to revert to old secret to file. Please update the file manually"); } } } }