List of usage examples for java.util Properties load
public synchronized void load(InputStream inStream) throws IOException
From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFMapQuerySpecificInvisibleMethodDeclarations.java
public static void main(String[] args) { Options options = new Options(); Option inputOpt = OptionBuilder.create(IN); inputOpt.setArgName("INPUT"); inputOpt.setDescription("Input Kyanos resource directory"); inputOpt.setArgs(1);/* w w w . ja va 2 s. co m*/ inputOpt.setRequired(true); Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS); inClassOpt.setArgName("CLASS"); inClassOpt.setDescription("FQN of EPackage implementation class"); inClassOpt.setArgs(1); inClassOpt.setRequired(true); Option optFileOpt = OptionBuilder.create(OPTIONS_FILE); optFileOpt.setArgName("FILE"); optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource"); optFileOpt.setArgs(1); options.addOption(inputOpt); options.addOption(inClassOpt); options.addOption(optFileOpt); CommandLineParser parser = new PosixParser(); try { PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME, new MapPersistenceBackendFactory()); CommandLine commandLine = parser.parse(options, args); URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN))); Class<?> inClazz = NeoEMFMapQuerySpecificInvisibleMethodDeclarations.class.getClassLoader() .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS)); inClazz.getMethod("init").invoke(null); ResourceSet resourceSet = new ResourceSetImpl(); resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME, PersistentResourceFactory.eINSTANCE); Resource resource = resourceSet.createResource(uri); Map<String, Object> loadOpts = new HashMap<String, Object>(); if (commandLine.hasOption(OPTIONS_FILE)) { Properties properties = new Properties(); properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE)))); for (final Entry<Object, Object> entry : properties.entrySet()) { loadOpts.put((String) entry.getKey(), (String) entry.getValue()); } } // Add the LoadedObjectCounter store List<StoreOption> storeOptions = new ArrayList<StoreOption>(); // storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING); storeOptions.add(MapResourceOptions.EStoreMapOption.AUTOCOMMIT); storeOptions.add(PersistentResourceOptions.EStoreOption.ESTRUCUTRALFEATURE_CACHING); storeOptions.add(PersistentResourceOptions.EStoreOption.IS_SET_CACHING); storeOptions.add(PersistentResourceOptions.EStoreOption.SIZE_CACHING); loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions); resource.load(loadOpts); { Runtime.getRuntime().gc(); long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}", MessageUtil.byteCountToDisplaySize(initialUsedMemory))); LOG.log(Level.INFO, "Start query"); long begin = System.currentTimeMillis(); EList<MethodDeclaration> list = ASE2015JavaQueries.getSpecificInvisibleMethodDeclarations(resource); long end = System.currentTimeMillis(); LOG.log(Level.INFO, "End query"); LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size())); LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin))); Runtime.getRuntime().gc(); long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory))); LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}", MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory))); } if (resource instanceof PersistentResourceImpl) { PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource); } else { resource.unload(); } } catch (ParseException e) { MessageUtil.showError(e.toString()); MessageUtil.showError("Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { MessageUtil.showError(e.toString()); } }
From source file:gobblin.test.TestWorker.java
@SuppressWarnings("all") public static void main(String[] args) throws Exception { // Build command-line options Option configOption = OptionBuilder.withArgName("framework config file") .withDescription("Configuration properties file for the framework").hasArgs().withLongOpt("config") .create('c'); Option jobConfigsOption = OptionBuilder.withArgName("job config files") .withDescription("Comma-separated list of job configuration files").hasArgs() .withLongOpt("jobconfigs").create('j'); Option modeOption = OptionBuilder.withArgName("run mode") .withDescription("Test mode (schedule|run); 'schedule' means scheduling the jobs, " + "whereas 'run' means running the jobs immediately") .hasArg().withLongOpt("mode").create('m'); Option helpOption = OptionBuilder.withArgName("help").withDescription("Display usage information") .withLongOpt("help").create('h'); Options options = new Options(); options.addOption(configOption);/*from w w w . ja v a2s.co m*/ options.addOption(jobConfigsOption); options.addOption(modeOption); options.addOption(helpOption); // Parse command-line options CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { printUsage(options); System.exit(0); } // Start the test worker with the given configuration properties Configuration config = new PropertiesConfiguration(cmd.getOptionValue('c')); Properties properties = ConfigurationConverter.getProperties(config); TestWorker testWorker = new TestWorker(properties); testWorker.start(); // Job running mode Mode mode = Mode.valueOf(cmd.getOptionValue('m').toUpperCase()); // Get the list of job configuration files List<String> jobConfigFiles = Lists .newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(cmd.getOptionValue('j'))); CountDownLatch latch = new CountDownLatch(jobConfigFiles.size()); for (String jobConfigFile : jobConfigFiles) { // For each job, load the job configuration, then run or schedule the job. Properties jobProps = new Properties(); jobProps.load(new FileReader(jobConfigFile)); jobProps.putAll(properties); testWorker.runJob(jobProps, mode, new TestJobListener(latch)); } // Wait for all jobs to finish latch.await(); testWorker.stop(); }
From source file:eu.databata.engine.util.PropagatorRecreateDatabaseTool.java
public static void main(String[] args) { ClassLoader classLoader = PropagatorRecreateDatabaseTool.class.getClassLoader(); InputStream resourceAsStream = classLoader.getResourceAsStream("databata.properties"); Properties propagatorProperties = new Properties(); try {/* w ww. j a v a 2 s . c o m*/ propagatorProperties.load(resourceAsStream); } catch (FileNotFoundException e) { LOG.error("Sepecified file 'databata.properties' not found"); } catch (IOException e) { LOG.error("Sepecified file 'databata.properties' cannot be loaded"); } SingleConnectionDataSource dataSource = new SingleConnectionDataSource(); dataSource.setDriverClassName(propagatorProperties.getProperty("db.propagation.driver")); dataSource.setUrl(propagatorProperties.getProperty("db.propagation.dba.connection-url")); dataSource.setUsername(propagatorProperties.getProperty("db.propagation.dba.user")); dataSource.setPassword(propagatorProperties.getProperty("db.propagation.dba.password")); dataSource.setSuppressClose(true); String databaseName = "undefined"; try { databaseName = dataSource.getConnection().getMetaData().getDatabaseProductName(); } catch (SQLException e) { LOG.error("Cannot get connection by specified url", e); } String databaseCode = PropagationUtils.getDatabaseCode(databaseName); LOG.info("Database with code '" + databaseCode + "' is identified."); String submitFileName = "META-INF/databata/" + databaseCode + "_recreate_database.sql"; String fileContent = ""; try { fileContent = getFileContent(classLoader, submitFileName); } catch (IOException e) { LOG.info("File with name '" + submitFileName + "' cannot be read from classpath. Trying to load default submit file."); } if (fileContent == null || "".equals(fileContent)) { String defaultSubmitFileName = "META-INF/databata/" + databaseCode + "_recreate_database.default.sql"; try { fileContent = getFileContent(classLoader, defaultSubmitFileName); } catch (IOException e) { LOG.info("File with name '" + defaultSubmitFileName + "' cannot be read from classpath. Trying to load default submit file."); } } if (fileContent == null) { LOG.info("File content is empty. Stopping process."); return; } fileContent = replacePlaceholders(fileContent, propagatorProperties); SqlFile sqlFile = null; try { sqlFile = new SqlFile(fileContent, null, submitFileName, new SqlExecutionCallback() { @Override public void handleExecuteSuccess(String sql, int arg1, double arg2) { LOG.info("Sql is sucessfully executed \n ======== \n" + sql + "\n ======== \n"); } @Override public void handleException(SQLException arg0, String sql) throws SQLException { LOG.info("Sql returned error \n ======== \n" + sql + "\n ======== \n"); } }, null); } catch (IOException e) { LOG.error("Error when initializing SqlTool", e); } try { sqlFile.setConnection(dataSource.getConnection()); } catch (SQLException e) { LOG.error("Error is occured when setting connection", e); } try { sqlFile.execute(); } catch (SqlToolError e) { LOG.error("Error when creating user", e); } catch (SQLException e) { LOG.error("Error when creating user", e); } }
From source file:org.ensembl.gti.seqstore.server.MetaDataServer.java
public static void main(String[] args) throws Exception { final Logger log = LoggerFactory.getLogger(MetaDataServer.class); Properties properties = new Properties(); properties.load(new ClassPathResource("metadata_server.properties").getInputStream()); MetaDataServerOptions opts = new MetaDataServerOptions(properties); new JCommander(opts, args); log.info("Starting ENA submission handler"); EnaCramSubmissionHandler enaHandler = new EnaCramSubmissionHandler(opts.getFtpUri(), opts.getSubmitUri(), opts.getCentre(), opts.getSubmitUser(), opts.getSubmitPass()); log.info("Starting server on " + opts.getPort()); new MetaDataServer(opts.getPort(), buildDataSource(opts.getDbUri(), opts.getDbUser(), opts.getDbPass()), enaHandler).run();//from w w w . ja v a 2 s . c o m }
From source file:net.roboconf.iaas.openstack.IaasOpenstack.java
public static void main(String args[]) throws Exception { Map<String, String> conf = new HashMap<String, String>(); java.util.Properties p = new java.util.Properties(); p.load(new java.io.FileReader(args[0])); for (Object name : p.keySet()) { conf.put(name.toString(), p.get(name).toString()); }//from ww w . j av a 2s. c o m // conf.put("openstack.computeUrl", "http://localhost:8888/v2"); IaasOpenstack iaas = new IaasOpenstack(); iaas.setIaasProperties(conf); String machineImageId = conf.get("openstack.image"); String channelName = "test"; String applicationName = "roboconf"; String ipMessagingServer = "localhost"; String serverId = iaas.createVM(machineImageId, ipMessagingServer, channelName, applicationName); /*Thread.sleep(25000); iaas.terminateVM(serverId);*/ }
From source file:com.bt.aloha.batchtest.WeekendBatchTest.java
public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("batchTestApplicationContext.xml"); BatchTest batchTest = (BatchTest) ctx.getBean("batchTestBean"); batchTest.setApplicationContext(ctx); batchTest.init();/* w w w .j av a 2 s .co m*/ batchTest.assignNewCollectionsToBeans(); while (true) { configure(batchTest); if (stop) break; batchTest.run(); logStatistics(log, batchTest); batchTest.reset(); if (sleepTime > 0) { log.info(String.format("sleeping for %d minutes", sleepTime / 60 / 1000)); Thread.sleep(sleepTime); } } // wait until all things in collection should be ready for housekeeping Properties batchProps = new Properties(); InputStream is = batchTest.getClass().getResourceAsStream("/batchrun.sip.properties"); batchProps.load(is); is.close(); Thread.sleep(Long.parseLong(batchProps.getProperty("dialog.max.time.to.live", "900000")) + Long.parseLong(batchProps.getProperty("housekeeping.interval", "300000"))); // housekeeping should have happend // log out all things still left logCollections(batchTest); batchTest.destroy(); }
From source file:edu.indiana.d2i.sloan.internal.StopVMSimulator.java
public static void main(String[] args) { StopVMSimulator simulator = new StopVMSimulator(); CommandLineParser parser = new PosixParser(); try {/*from w ww .ja v a2 s . c o m*/ CommandLine line = simulator.parseCommandLine(parser, args); String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR)); if (!HypervisorCmdSimulator.resourceExist(wdir)) { logger.error(String.format("Cannot find VM working dir: %s", wdir)); System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST)); } Properties prop = new Properties(); String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME; prop.load(new FileInputStream(new File(filename))); // cannot stop VM when it is not running VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE))); if (!currentState.equals(VMState.RUNNING)) { logger.error("Cannot perform stop when VM is not running"); System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING)); } // stop VM try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error(e.getMessage()); } // update VM status file, i.e. set state to shutdown prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString()); // save VM state file back prop.store(new FileOutputStream(new File(filename)), ""); // success System.exit(0); } catch (ParseException e) { logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s", StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, ""))); System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS)); } catch (IOException e) { logger.error(e.getMessage(), e); System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR)); } }
From source file:com.netflix.suro.SuroServer.java
public static void main(String[] args) throws IOException { final AtomicReference<Injector> injector = new AtomicReference<Injector>(); try {/* www .j a v a 2s. c o m*/ // Parse the command line Options options = createOptions(); final CommandLine line = new BasicParser().parse(options, args); // Load the properties file final Properties properties = new Properties(); if (line.hasOption('p')) { properties.load(new FileInputStream(line.getOptionValue('p'))); } // Bind all command line options to the properties with prefix "SuroServer." for (Option opt : line.getOptions()) { String name = opt.getOpt(); String value = line.getOptionValue(name); String propName = PROP_PREFIX + opt.getArgName(); if (propName.equals(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY)) { properties.setProperty(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY, FileUtils.readFileToString(new File(value))); } else if (propName.equals(DynamicPropertySinkConfigurator.SINK_PROPERTY)) { properties.setProperty(DynamicPropertySinkConfigurator.SINK_PROPERTY, FileUtils.readFileToString(new File(value))); } else if (propName.equals(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY)) { properties.setProperty(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY, FileUtils.readFileToString(new File(value))); } else { properties.setProperty(propName, value); } } create(injector, properties); injector.get().getInstance(LifecycleManager.class).start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { Closeables.close(injector.get().getInstance(LifecycleManager.class), true); } catch (IOException e) { // do nothing because Closeables.close will swallow IOException } } }); waitForShutdown(getControlPort(properties)); } catch (Throwable e) { System.err.println("SuroServer startup failed: " + e.getMessage()); System.exit(-1); } finally { Closeables.close(injector.get().getInstance(LifecycleManager.class), true); } }
From source file:edu.usc.goffish.gopher.impl.Main.java
public static void main(String[] args) { Properties properties = new Properties(); try {// w w w .j a va 2s .c o m properties.load(new FileInputStream(CONFIG_FILE)); } catch (IOException e) { String message = "Error while loading Container Configuration from " + CONFIG_FILE + " Cause -" + e.getCause(); log.warning(message); } if (args.length == 4) { PropertiesConfiguration propertiesConfiguration; String url = null; URI uri = URI.create(args[3]); String dataDir = uri.getPath(); String currentHost = uri.getHost(); try { propertiesConfiguration = new PropertiesConfiguration(dataDir + "/gofs.config"); propertiesConfiguration.load(); url = (String) propertiesConfiguration.getString(DataNode.DATANODE_NAMENODE_LOCATION_KEY); } catch (ConfigurationException e) { String message = " Error while reading gofs-config cause -" + e.getCause(); handleException(message); } URI nameNodeUri = URI.create(url); INameNode nameNode = new RemoteNameNode(nameNodeUri); int partition = -1; try { for (URI u : nameNode.getDataNodes()) { if (URIHelper.isLocalURI(u)) { IDataNode dataNode = DataNode.create(u); IntCollection partitions = dataNode.getLocalPartitions(args[2]); partition = partitions.iterator().nextInt(); break; } } if (partition == -1) { String message = "Partition not loaded from uri : " + nameNodeUri; handleException(message); } properties.setProperty(GopherInfraHandler.PARTITION, String.valueOf(partition)); } catch (Exception e) { String message = "Error while loading Partitions from " + nameNodeUri + " Cause -" + e.getMessage(); e.printStackTrace(); handleException(message); } properties.setProperty(Constants.STATIC_PELLET_COUNT, String.valueOf(1)); FloeRuntimeEnvironment environment = FloeRuntimeEnvironment.getEnvironment(); environment.setSystemConfig(properties); properties.setProperty(Constants.CURRET_HOST, currentHost); String managerHost = args[0]; int managerPort = Integer.parseInt(args[1]); Container container = environment.getContainer(); container.setManager(managerHost, managerPort); DefaultClientConfig config = new DefaultClientConfig(); config.getProperties().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true); config.getFeatures().put(ClientConfig.FEATURE_DISABLE_XML_SECURITY, true); Client c = Client.create(config); if (managerHost == null || managerPort == 0) { handleException("Manager Host / Port have to be configured in " + args[0]); } WebResource r = c.resource("http://" + managerHost + ":" + managerPort + "/Manager/addContainerInfo/Container=" + container.getContainerInfo().getContainerId() + "/Host=" + container.getContainerInfo().getContainerHost()); c.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true); r.post(); log.log(Level.INFO, "Container started "); } else { String message = "Invalid arguments , arg[0]=Manager host, " + "arg[1] = mamanger port,arg[2]=graph id,arg[3]=partition uri"; message += "\n Current Arguments...." + args.length + "\n"; for (int i = 0; i < args.length; i++) { message += "arg " + i + " : " + args[i] + "\n"; } handleException(message); } }
From source file:de.zazaz.iot.bosch.indego.util.IndegoMqttAdapter.java
public static void main(String[] args) { System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-normal.xml"); Options options = new Options(); StringBuilder commandList = new StringBuilder(); for (DeviceCommand cmd : DeviceCommand.values()) { if (commandList.length() > 0) { commandList.append(", "); }/*www . j av a 2 s . c o m*/ commandList.append(cmd.toString()); } options.addOption(Option // .builder("c") // .longOpt("config") // .desc("The configuration file to use") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("d") // .longOpt("debug") // .desc("Logs more details") // .build()); options.addOption(Option // .builder("?") // .longOpt("help") // .desc("Prints this help") // .build()); CommandLineParser parser = new DefaultParser(); CommandLine cmds = null; try { cmds = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); System.err.println(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(IndegoMqttAdapter.class.getName(), options); System.exit(1); return; } if (cmds.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); return; } if (cmds.hasOption("d")) { System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-debug.xml"); } String configFileName = cmds.getOptionValue('c'); File configFile = new File(configFileName); if (!configFile.exists()) { System.err.println(String.format("The specified config file (%s) does not exist", configFileName)); System.err.println(); System.exit(2); return; } Properties properties = new Properties(); try (InputStream in = new FileInputStream(configFile)) { properties.load(in); } catch (IOException ex) { System.err.println(ex.getMessage()); System.err.println(String.format("Was not able to load the properties file (%s)", configFileName)); System.err.println(); } MqttIndegoAdapterConfiguration config = new MqttIndegoAdapterConfiguration(); config.setIndegoBaseUrl(properties.getProperty("indego.mqtt.device.base-url")); config.setIndegoUsername(properties.getProperty("indego.mqtt.device.username")); config.setIndegoPassword(properties.getProperty("indego.mqtt.device.password")); config.setMqttBroker(properties.getProperty("indego.mqtt.broker.connection")); config.setMqttClientId(properties.getProperty("indego.mqtt.broker.client-id")); config.setMqttUsername(properties.getProperty("indego.mqtt.broker.username")); config.setMqttPassword(properties.getProperty("indego.mqtt.broker.password")); config.setMqttTopicRoot(properties.getProperty("indego.mqtt.broker.topic-root")); config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.mqtt.polling-interval-ms"))); MqttIndegoAdapter adapter = new MqttIndegoAdapter(config); adapter.startup(); }