List of usage examples for java.util Properties Properties
public Properties()
From source file:org.apache.s4.MainApp.java
public static void main(String args[]) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c")); options.addOption(/* www . jav a2 s. c om*/ OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a")); options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d")); options.addOption(OptionBuilder.withArgName("seedtime").hasArg() .withDescription("event clock initialization time").create("s")); options.addOption( OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e")); options.addOption( OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i")); options.addOption( OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t")); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; String clockType = "wall"; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.err.println(pe.getLocalizedMessage()); System.exit(1); } int instanceId = -1; if (commandLine.hasOption("i")) { String instanceIdStr = commandLine.getOptionValue("i"); try { instanceId = Integer.parseInt(instanceIdStr); } catch (NumberFormatException nfe) { System.err.println("Bad instance id: %s" + instanceIdStr); System.exit(1); } } if (commandLine.hasOption("c")) { coreHome = commandLine.getOptionValue("c"); } if (commandLine.hasOption("a")) { appsHome = commandLine.getOptionValue("a"); } if (commandLine.hasOption("d")) { clockType = commandLine.getOptionValue("d"); } if (commandLine.hasOption("e")) { extsHome = commandLine.getOptionValue("e"); } String configType = "typical"; if (commandLine.hasOption("t")) { configType = commandLine.getOptionValue("t"); } long seedTime = 0; if (commandLine.hasOption("s")) { seedTime = Long.parseLong(commandLine.getOptionValue("s")); } File coreHomeFile = new File(coreHome); if (!coreHomeFile.isDirectory()) { System.err.println("Bad core home: " + coreHome); System.exit(1); } File appsHomeFile = new File(appsHome); if (!appsHomeFile.isDirectory()) { System.err.println("Bad applications home: " + appsHome); System.exit(1); } if (instanceId > -1) { System.setProperty("instanceId", "" + instanceId); } else { System.setProperty("instanceId", "" + S4Util.getPID()); } List loArgs = commandLine.getArgList(); if (loArgs.size() < 1) { // System.err.println("No bean configuration file specified"); // System.exit(1); } // String s4ConfigXml = (String) loArgs.get(0); // System.out.println("s4ConfigXml is " + s4ConfigXml); ClassPathResource propResource = new ClassPathResource("s4-core.properties"); Properties prop = new Properties(); if (propResource.exists()) { prop.load(propResource.getInputStream()); } else { System.err.println("Unable to find s4-core.properties. It must be available in classpath"); System.exit(1); } ApplicationContext coreContext = null; String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType; String configPath = ""; List<String> coreConfigUrls = new ArrayList<String>(); File configFile = null; // load clock configuration configPath = configBase + File.separatorChar + clockType + "-clock.xml"; coreConfigUrls.add(configPath); // load core config xml configPath = configBase + File.separatorChar + "s4-core-conf.xml"; configFile = new File(configPath); if (!configFile.exists()) { System.err.printf("S4 core config file %s does not exist\n", configPath); System.exit(1); } coreConfigUrls.add(configPath); String[] coreConfigFiles = new String[coreConfigUrls.size()]; coreConfigUrls.toArray(coreConfigFiles); String[] coreConfigFileUrls = new String[coreConfigFiles.length]; for (int i = 0; i < coreConfigFiles.length; i++) { coreConfigFileUrls[i] = "file:" + coreConfigFiles[i]; } coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext); ApplicationContext context = coreContext; Clock clock = (Clock) context.getBean("clock"); if (clock instanceof EventClock && seedTime > 0) { EventClock s4EventClock = (EventClock) clock; s4EventClock.updateTime(seedTime); System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime()); } PEContainer peContainer = (PEContainer) context.getBean("peContainer"); Watcher w = (Watcher) context.getBean("watcher"); w.setConfigFilename(configPath); // load extension modules String[] configFileNames = getModuleConfigFiles(extsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); } // load application modules configFileNames = getModuleConfigFiles(appsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); // attach any beans that implement ProcessingElement to the PE // Container String[] processingElementBeanNames = context.getBeanNamesForType(AbstractPE.class); for (String processingElementBeanName : processingElementBeanNames) { AbstractPE bean = (AbstractPE) context.getBean(processingElementBeanName); bean.setClock(clock); try { bean.setSafeKeeper((SafeKeeper) context.getBean("safeKeeper")); } catch (NoSuchBeanDefinitionException ignored) { // no safe keeper = no checkpointing / recovery } // if the application did not specify an id, use the Spring bean name if (bean.getId() == null) { bean.setId(processingElementBeanName); } System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id " + ((AbstractPE) bean).getId()); peContainer.addProcessor((AbstractPE) bean); } } }
From source file:io.personium.recovery.Recovery.java
/** * main./*from w w w . j av a 2s. com*/ * @param args */ public static void main(String[] args) { loadProperties(); Option optIndex = new Option("i", "index", true, "?"); Option optProp = new Option("p", "prop", true, ""); // t?????????????????????? Option optType = new Option("t", "type", true, "??type"); Option optClear = new Option("c", "clear", false, "???elasticsearch?"); Option optReplicas = new Option("r", "replicas", true, "??"); Option optVersion = new Option("v", "version", false, "??"); // // optIndex.setRequired(true); // optProp.setRequired(true); Options options = new Options(); options.addOption(optIndex); options.addOption(optProp); options.addOption(optType); options.addOption(optClear); options.addOption(optReplicas); options.addOption(optVersion); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; try { commandLine = parser.parse(options, args, true); } catch (ParseException e) { (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options); log.warn("Recovery failure"); System.exit(1); } if (commandLine.hasOption("v")) { log.info("Version:" + versionNumber); System.exit(0); } if (!commandLine.hasOption("p")) { (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options); log.warn("Recovery failure"); System.exit(1); } if (commandLine.hasOption("t")) { log.info("Command line option \"t\" or \"type\" is deprecated. Option ignored."); } if (!commandLine.hasOption("r")) { (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options); log.warn("Command line option \"r\" is required."); System.exit(1); } RecoveryManager recoveryManager = new RecoveryManager(); // ??index recoveryManager.setIndexNames(commandLine.getOptionValue("i")); // elasticsearch recoveryManager.setClear(commandLine.hasOption("c")); // ?? // 0 ?ES??????????int??????? try { int replicas = Integer.parseInt(commandLine.getOptionValue("r")); if (replicas < 0) { log.warn("Command line option \"r\"'s value is not integer."); System.exit(1); } recoveryManager.setReplicas(replicas); } catch (NumberFormatException e) { log.warn("Command line option \"r\"'s value is not integer."); System.exit(1); } try { // Properties? Properties properties = new Properties(); // ? properties.load(new FileInputStream(commandLine.getOptionValue("p"))); if ((!properties.containsKey(ES_HOSTS)) || (!properties.containsKey(ES_CLUSTER_NAME)) || (!properties.containsKey(ADS_JDBC_URL)) || (!properties.containsKey(ADS_JDBC_USER)) || (!properties.containsKey(ADS_JDBC_PASSWORD)) || (!properties.containsKey(ES_ROUTING_FLAG))) { log.warn("properties file error"); log.warn("Recovery failure"); System.exit(1); } else { recoveryManager.setEsHosts(properties.getProperty(ES_HOSTS)); recoveryManager.setEsClusetrName(properties.getProperty(ES_CLUSTER_NAME)); recoveryManager.setAdsJdbcUrl(properties.getProperty(ADS_JDBC_URL)); recoveryManager.setAdsUser(properties.getProperty(ADS_JDBC_USER)); recoveryManager.setAdsPassword(properties.getProperty(ADS_JDBC_PASSWORD)); recoveryManager.setExecuteCnt(properties.getProperty(EXECUTE_COUNT)); recoveryManager.setCheckCount(properties.getProperty(CHECK_COUNT)); recoveryManager.setUnitPrefix(properties.getProperty(UNIT_PREFIX)); } } catch (FileNotFoundException e) { e.printStackTrace(); log.warn("properties file error"); log.warn("Recovery failure"); System.exit(1); } catch (IOException e) { e.printStackTrace(); log.warn("properties file error"); log.warn("Recovery failure"); System.exit(1); } String[] indexList = recoveryManager.getIndexNames(); boolean isClear = recoveryManager.isClear(); if (isClear && (indexList != null && null != indexList[0])) { String ad = recoveryManager.getUnitPrefix() + "_" + EsIndex.CATEGORY_AD; if (Arrays.asList(indexList).contains(ad)) { log.warn("Cannot specify both -c and -i " + recoveryManager.getUnitPrefix() + "_ad option."); log.warn("Recovery failure"); System.exit(1); } } // ?????? try { LockUtility.lock(); } catch (AlreadyStartedException e) { log.info("Recovery has already started"); log.info("Recovery failure"); return; } catch (Exception e) { log.error("Failed to get lock for the double start control"); e.printStackTrace(); LockUtility.release(); log.error("Recovery failure"); System.exit(1); } // ?? try { recoveryManager.recovery(); } catch (Exception e) { LockUtility.release(); log.error("Recovery failure"); System.exit(1); } LockUtility.release(); log.info("Recovery Success"); return; }
From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java
public static void main(String[] args) { CommandLineParser parser = new DefaultParser(); Options options = new Options(); // Most of the following defaults should be changed in // the --conf or "conf.properties" file String sqlURL = null;/*from www . ja v a 2 s .c om*/ String sqlUser = null; String sqlPass = null; String sqlDb = null; String sqlHost = "127.0.0.1"; String backupDirStr = null; String laterThanStr = ""; String fullBackupPathStr = null; String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak"; String fullBackupDatePatternStr = "yyyyMMddHHmm"; String sqlProcessUser = null; String logBackupPatternStr = "(.*)\\.trn"; String logBackupDatePatternStr = "yyyyMMddHHmmss"; boolean doFullRestore = false; Boolean useLogFileLastMode = null; Boolean monitorLogBackupDir = null; options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build()); options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build()); options.addOption(Option.builder().longOpt("restore-full") .desc("Restore the full backup before continuing.").build()); options.addOption(Option.builder().longOpt("use-lastmod") .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build()); options.addOption(Option.builder().longOpt("monitor-backup-dir") .desc("Monitor the backup directory for new log backups, and apply them.").build()); CommandLine line = null; try { try { line = parser.parse(options, args); } catch (ParseException ex) { throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()), ex); } String confFile = null; // Process the command line arguments Iterator cmdI = line.iterator(); while (cmdI.hasNext()) { Option currOpt = (Option) cmdI.next(); String currOptName = currOpt.getLongOpt(); switch (currOptName) { case "conf": // Parse the configuration file confFile = currOpt.getValue(); break; case "laterthan": // "Later Than" file date filter laterThanStr = currOpt.getValue(); break; case "restore-full": // Do a full backup restore before restoring logs doFullRestore = true; break; case "monitor-backup-dir": // Monitor the backup directory for new logs monitorLogBackupDir = true; break; case "use-lastmod": // Use the last-modified date on Log Backup files for sorting/filtering useLogFileLastMode = true; break; } } Properties confProperties = null; if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) { throw new MSSQLApplyLogException( "Missing or unreadable configuration file. Please specify --conf"); } else { // Process the conf.properties file confProperties = new Properties(); try { confProperties.load(Files.newBufferedReader(Paths.get(confFile))); } catch (IOException ex) { throw new MSSQLApplyLogException("Error loading properties file", ex); } sqlURL = confProperties.getProperty("sqlURL", ""); sqlUser = confProperties.getProperty("sqlUser", ""); sqlPass = confProperties.getProperty("sqlPass", ""); sqlDb = confProperties.getProperty("sqlDb", ""); sqlHost = confProperties.getProperty("sqlHost", ""); backupDirStr = confProperties.getProperty("backupDir", ""); if (StringUtils.isBlank(laterThanStr)) { laterThanStr = confProperties.getProperty("laterThan", ""); } fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr); fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr); fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern", fullBackupDatePatternStr); sqlProcessUser = confProperties.getProperty("sqlProcessUser", ""); logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr); logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern", logBackupDatePatternStr); if (useLogFileLastMode == null) { String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false"); useLogFileLastMode = Boolean .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr))); } if (monitorLogBackupDir == null) { String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false"); monitorLogBackupDir = Boolean .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr))); } } } catch (MSSQLApplyLogException ex) { try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { pw.append(String.format("Error : '%s'\n\n", ex.getMessage())); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ", "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options, 0, 2, " All Rights Reserved.", true); System.out.println(sw.toString()); } catch (IOException iex) { LOGGER.debug("Error processing usage", iex); } System.exit(1); } MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr, fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr, logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser, useLogFileLastMode, doFullRestore, monitorLogBackupDir); MSSQLApplyLog logProc = MSSQLApplyLog.from(config); BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build(); ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory); Future<Integer> currRunTask = mainThreadExe.submit(logProc); mainThreadExe.shutdown(); Integer resp = 0; try { resp = currRunTask.get(); } catch (InterruptedException ex) { LOGGER.error("Application 'main' thread was interrupted", ex); } catch (ExecutionException ex) { LOGGER.error("Application 'main' thread execution error", ex); } finally { // If main leaves for any reason, shutdown all threads mainThreadExe.shutdownNow(); } System.exit(resp); }
From source file:com.simple.sftpfetch.App.java
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Options options = getOptions();/* www . j a va 2s . c om*/ List<String> requiredProperties = asList("c"); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { printUsage(options); System.exit(0); } for (String opt : requiredProperties) { if (!commandLine.hasOption(opt)) { System.err.println("The option: " + opt + " is required."); printUsage(options); System.exit(1); } } Pattern pattern; if (commandLine.hasOption("p")) { pattern = Pattern.compile(commandLine.getOptionValue("p")); } else { pattern = MATCH_EVERYTHING; } String filename = commandLine.getOptionValue("c"); Properties properties = new Properties(); try { InputStream stream = new FileInputStream(new File(filename)); properties.load(stream); } catch (IOException ioe) { System.err.println("Unable to read properties from: " + filename); System.exit(2); } String routingKey = ""; if (commandLine.hasOption("r")) { routingKey = commandLine.getOptionValue("r"); } else if (properties.containsKey("rabbit.routingkey")) { routingKey = properties.getProperty("rabbit.routingkey"); } int daysToFetch; if (commandLine.hasOption("d")) { daysToFetch = Integer.valueOf(commandLine.getOptionValue("d")); } else { daysToFetch = Integer.valueOf(properties.getProperty(FETCH_DAYS)); } FileDecrypter decrypter = null; if (properties.containsKey("decryption.key.path")) { decrypter = new PGPFileDecrypter(new File(properties.getProperty("decryption.key.path"))); } else { decrypter = new NoopDecrypter(); } SftpClient sftpClient = new SftpClient(new JSch(), new SftpConnectionInfo(properties)); try { App app = new App(sftpClient, s3FromProperties(properties), new RabbitClient(new ConnectionFactory(), new RabbitConnectionInfo(properties)), decrypter, System.out); app.run(routingKey, daysToFetch, pattern, commandLine.hasOption("n"), commandLine.hasOption("o")); } finally { sftpClient.close(); } System.exit(0); } catch (UnrecognizedOptionException uoe) { System.err.println(uoe.getMessage()); printUsage(options); System.exit(10); } }
From source file:com.soulgalore.velocity.MergeXMLWithVelocity.java
/** * Merge a xml file with Velocity template. The third parameter is the properties file, where the * key/value is added to the velocity context. The fourth parameter is the output file. If not * included, the result is printed to system.out. * /*from ww w. j ava2 s. c om*/ * @param args are file.xml template.vm properties.prop [output.file] * @throws JDOMException if the xml file couldn't be parsed * @throws IOException couldn't find one of the files */ public static void main(String[] args) throws JDOMException, IOException { if (args.length < 3) { System.out.println( "Missing input files. XMLToVelocity file.xml template.vm prop.properties [output.file]"); return; } final Properties properties = new Properties(); final File prop = new File(args[2]); if (prop.exists()) properties.load(new FileReader(prop)); else throw new IOException("Couldn't find the property file:" + prop.getAbsolutePath()); final MergeXMLWithVelocity xtv = new MergeXMLWithVelocity(properties); xtv.create(args); }
From source file:edu.indiana.d2i.htrc.corpus.analysis.LDAAnalysisDriver.java
public static void main(String[] args) throws Exception { GenericOptionsParser parser = new GenericOptionsParser(new Configuration(), args); CommandLine commandLine = parser.getCommandLine(); Option[] options = commandLine.getOptions(); /**/*from w w w.ja v a2 s.c om*/ * appArgs[0] = <path/to/input/directory> (where sequence files reside) * appArgs[1] = <path/to/output/directory/prefix> (where LDA state file * should go) appArgs[2] = <path/local/property/file> * * Note: the passed in <path/to/output/directory/prefix> is only a * prefix, we automatically append the iteration number suffix */ String[] appArgs = parser.getRemainingArgs(); // load property file Properties prop = new Properties(); prop.load(new FileInputStream(appArgs[2])); int maxIterationNum = Integer.parseInt( prop.getProperty(Constants.LDA_ANALYSIS_MAX_ITER, Constants.LDA_ANALYSIS_DEFAULT_MAX_ITER)); int iterationCount = 0; /** * in the first iteration (iteration 0), there is no LDA state */ String[] arguments = generateArgs(options, new String[0], appArgs[0], appArgs[1] + "-iter-" + iterationCount); /** * iterate until convergence or maximum iteration number reached */ while (true) { int exitCode = ToolRunner.run(new LDAAnalysisDriver(), arguments); System.out.println(String.format("LDA analysis finished iteration %d, with exitCode = %d", iterationCount, exitCode)); /** * LDA state is the output (sequence file) from current iteration * and is used to initialize the words-topics table and * topics-documents table for the next iteration */ String ldaStateFilePath = appArgs[1] + "-iter-" + iterationCount + File.separator + "part-r-00000"; /** * load LDA state to check whether it is converged */ if (isAnalysisConverged(ldaStateFilePath)) { System.out.println(String.format("LDA analysis converged at iteration %d", iterationCount)); break; } if ((iterationCount + 1) >= maxIterationNum) { System.out.println(String.format( "LDA analysis reached the maximum iteration number %d, going to stop", maxIterationNum)); break; } String[] otherOps = { "-D", "user.args.lda.state.filepath=" + ldaStateFilePath }; /** * generate arguments for the next iteration and increase iteration * count */ arguments = generateArgs(options, otherOps, appArgs[0], appArgs[1] + "-iter-" + ++iterationCount); } }
From source file:edu.indiana.d2i.sloan.internal.CreateVMSimulator.java
public static void main(String[] args) { CreateVMSimulator simulator = new CreateVMSimulator(); CommandLineParser parser = new PosixParser(); try {//from w w w . ja v a 2 s . com CommandLine line = simulator.parseCommandLine(parser, args); String imagePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH)); int vcpu = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU))); int mem = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM))); if (!HypervisorCmdSimulator.resourceExist(imagePath)) { logger.error(String.format("Cannot find requested image: %s", imagePath)); System.exit(ERROR_CODE.get(ERROR_STATE.IMAGE_NOT_EXIST)); } if (!hasEnoughCPUs(vcpu)) { logger.error(String.format("Don't have enough cpus, requested %d", vcpu)); System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_CPU)); } if (!hasEnoughMem(mem)) { logger.error(String.format("Don't have enough memory, requested %d", mem)); System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_MEM)); } String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR)); if (HypervisorCmdSimulator.resourceExist(wdir)) { logger.error(String.format("Working directory %s already exists ", wdir)); System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_EXIST)); } // copy VM image to working directory File imageFile = new File(imagePath); FileUtils.copyFile(imageFile, new File(HypervisorCmdSimulator.cleanPath(wdir) + imageFile.getName())); // write state as property file so that we can query later Properties prop = new Properties(); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH), imagePath); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU), String.valueOf(vcpu)); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM), String.valueOf(mem)); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR), wdir); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD))); // write VM state as shutdown prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString()); // write VM mode as undefined prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), VMMode.NOT_DEFINED.toString()); prop.store( new FileOutputStream(new File( HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME)), ""); // do other related settings try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error(e.getMessage()); } // 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.yahoo.pulsar.client.cli.PulsarClientTool.java
public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: pulsar-client CONF_FILE_PATH [options] [command] [command options]"); System.exit(-1);/* ww w . ja va2 s. c om*/ } String configFile = args[0]; Properties properties = new Properties(); if (configFile != null) { FileInputStream fis = null; try { fis = new FileInputStream(configFile); properties.load(fis); } finally { if (fis != null) { fis.close(); } } } PulsarClientTool clientTool = new PulsarClientTool(properties); int exit_code = clientTool.run(Arrays.copyOfRange(args, 1, args.length)); System.exit(exit_code); }
From source file:uk.co.moonsit.rmi.GraphClient.java
@SuppressWarnings("SleepWhileInLoop") public static void main(String args[]) { Properties p = new Properties(); try {/*from www. ja v a2s . c o m*/ p.load(new FileReader("graph.properties")); } catch (IOException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } //String[] labels = p.getProperty("labels").split(","); GraphClient demo = null; int type = 0; boolean log = false; if (args[0].equals("-l")) { log = true; } switch (type) { case 0: try { System.setProperty("java.security.policy", "file:./client.policy"); if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); } String name = "GraphServer"; String host = p.getProperty("host"); System.out.println(host); Registry registry = LocateRegistry.getRegistry(host); String[] list = registry.list(); for (String s : list) { System.out.println(s); } GraphDataInterface gs = null; boolean bound = false; while (!bound) { try { gs = (GraphDataInterface) registry.lookup(name); bound = true; } catch (NotBoundException e) { System.err.println("GraphServer exception:" + e.toString()); Thread.sleep(500); } } @SuppressWarnings("null") String config = gs.getConfig(); System.out.println(config); /*float[] fs = gs.getValues(); for (float f : fs) { System.out.println(f); }*/ demo = new GraphClient(gs, 1000, 700, Float.parseFloat(p.getProperty("frequency")), log); demo.init(config); demo.run(); } catch (RemoteException e) { System.err.println("GraphClient exception:" + e.toString()); } catch (FileNotFoundException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } finally { if (demo != null) { demo.close(); } } break; case 1: try { demo = new GraphClient(1000, 700, Float.parseFloat(p.getProperty("frequency"))); demo.init("A^B|Time|Error|-360|360"); demo.addData(0, 1, 100); demo.addData(0, 2, 200); demo.addData(1, 1, 50); demo.addData(1, 2, 450); } catch (FileNotFoundException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(GraphClient.class.getName()).log(Level.SEVERE, null, ex); } break; } }
From source file:ca.uwaterloo.iss4e.algorithm.PARX.java
public static void main(String[] args) { String url = "jdbc:postgresql://localhost/essex"; Properties props = new Properties(); props.setProperty("user", "xiliu"); props.setProperty("password", "Abcd1234"); try {/* w w w . j av a2 s.co m*/ /* Random generator = new Random(); BigDecimal[] d = new BigDecimal[40]; for (int i=0; i<40; ++i){ d[i] = new BigDecimal(generator.nextInt(10)); System.out.print(d[i].doubleValue()+"("+i+") |"); } System.out.println("\n ---------------"); Pair<double[], double[][]> values = PARX.prepareVariable(d, 11, 12, 2, 4); double[] Y = values.getKey(); double X[][] = values.getValue(); for (int i=0; i<Y.length; ++i){ for (int j=0; j<X[i].length; ++j) { System.out.print(X[i][j] + " |"); } System.out.print("|" +Y[i]); System.out.println(); } */ Class.forName("org.postgresql.Driver"); Connection conn = DriverManager.getConnection(url, props); PreparedStatement pstmt = conn.prepareStatement( "select array_agg(A.reading) from (select reading from meterreading where homeid=? and readdate between ? and ? order by readdate desc, readtime desc) A "); pstmt.setInt(1, 19419); pstmt.setDate(2, java.sql.Date.valueOf("2011-04-03")); pstmt.setDate(3, java.sql.Date.valueOf("2011-09-07")); ResultSet rs = pstmt.executeQuery(); int order = 3; int numOfSeasons = 24; int intervalOfUpdateModel = 4; //Every four hours int startPredict = 6 * 24; int numOfPointsForTraining = 24 * 5; double[] pointsForPredict = new double[order]; if (rs.next()) { BigDecimal[] readings = (BigDecimal[]) (rs.getArray(1).getArray()); double[][] data = new double[2][readings.length + 1]; int i = 0; for (; i < startPredict; ++i) { data[0][i] = readings[i].doubleValue(); data[1][i] = 0.0; } double[] beta = null; int updateModelCount = 0; for (; i < readings.length; ++i) { // if (updateModelCount%intervalOfUpdateModel==0) { // beta = PARX.computePARModel(readings, i, i+1, order, numOfSeasons); ++updateModelCount; //} for (int p = 0; p < order; ++p) { pointsForPredict[order - 1 - p] = readings[i - p].doubleValue(); } data[0][i] = readings[i].doubleValue(); // data[1][i+1] = PARX.predict(pointsForPredict, order, beta); } for (int j = 0; j < readings.length + 1; ++j) { System.out.println(data[0][j] + ", " + data[1][j]); } } } catch (Exception e) { e.printStackTrace(); } }