List of usage examples for java.util Properties setProperty
public synchronized Object setProperty(String key, String value)
From source file:Main.java
public static void main(String[] argv) throws Exception { Properties properties = new Properties(); try {/*from ww w . ja v a 2s .c om*/ properties.load(new FileInputStream("filename.properties")); } catch (IOException e) { } String string = properties.getProperty("a.b"); properties.setProperty("a.b", "new value"); }
From source file:edu.hawaii.soest.hioos.storx.StorXEmailUtil.java
/** * @param args//www .j a v a 2 s . com */ public static void main(String[] args) { // get a connection to the mail server Properties props = System.getProperties(); props.setProperty("mail.store.protocol", protocol); props.setProperty("mail.imaps.partialfetch", prefetch); log.debug("\n\nACCOUNT DETAILS: \n" + "accountName : " + accountName + "\n" + "server : " + server + "\n" + "username : " + username + "\n" + "password : " + password + "\n" + "protocol : " + protocol + "\n" + "dataMailbox : " + sourceMailbox + "\n" + "prefetch : " + prefetch + "\n"); try { // create the imaps mail session mailSession = Session.getDefaultInstance(props, null); mailStore = mailSession.getStore(protocol); mailStore.connect(server, username, password); // get folder references for the inbox and processed data box //createFolders(targetMailbox); organizeMessages(sourceMailbox, targetMailbox); } catch (NoSuchProviderException nspe) { nspe.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } finally { try { mailStore.close(); } catch (MessagingException e) { e.printStackTrace(); } } }
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 {/* www . j a v a 2s . com*/ /* 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(); } }
From source file:com.github.jcustenborder.kafka.connect.spooldir.SchemaGenerator.java
public static void main(String... args) throws Exception { ArgumentParser parser = ArgumentParsers.newArgumentParser("CsvSchemaGenerator").defaultHelp(true) .description("Generate a schema based on a file."); parser.addArgument("-t", "--type").required(true).choices("csv", "json") .help("The type of generator to use."); parser.addArgument("-c", "--config").type(File.class); parser.addArgument("-f", "--file").type(File.class).required(true) .help("The data file to generate the schema from."); parser.addArgument("-i", "--id").nargs("*").help("Field(s) to use as an identifier."); parser.addArgument("-o", "--output").type(File.class) .help("Output location to write the configuration to. Stdout is default."); Namespace ns = null;/*from w w w.j a v a 2 s . c o m*/ try { ns = parser.parseArgs(args); } catch (ArgumentParserException ex) { parser.handleError(ex); System.exit(1); } File inputFile = ns.get("file"); List<String> ids = ns.getList("id"); if (null == ids) { ids = ImmutableList.of(); } Map<String, Object> settings = new LinkedHashMap<>(); File inputPropertiesFile = ns.get("config"); if (null != inputPropertiesFile) { Properties inputProperties = new Properties(); try (FileInputStream inputStream = new FileInputStream(inputPropertiesFile)) { inputProperties.load(inputStream); } for (String s : inputProperties.stringPropertyNames()) { Object v = inputProperties.getProperty(s); settings.put(s, v); } } final SchemaGenerator generator; final String type = ns.getString("type"); if ("csv".equalsIgnoreCase(type)) { generator = new CsvSchemaGenerator(settings); } else if ("json".equalsIgnoreCase(type)) { generator = new JsonSchemaGenerator(settings); } else { throw new UnsupportedOperationException( String.format("'%s' is not a supported schema generator type", type)); } Map.Entry<Schema, Schema> kvp = generator.generate(inputFile, ids); Properties properties = new Properties(); properties.putAll(settings); properties.setProperty(SpoolDirSourceConnectorConfig.KEY_SCHEMA_CONF, ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getKey())); properties.setProperty(SpoolDirSourceConnectorConfig.VALUE_SCHEMA_CONF, ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getValue())); String output = ns.getString("output"); final String comment = "Configuration was dynamically generated. Please verify before submitting."; if (Strings.isNullOrEmpty(output)) { properties.store(System.out, comment); } else { try (FileOutputStream outputStream = new FileOutputStream(output)) { properties.store(outputStream, comment); } } }
From source file:com.impetus.kundera.ycsb.benchmark.CouchDBNativeClient.java
public static void main(String[] args) { CouchDBNativeClient cli = new CouchDBNativeClient(); Properties props = new Properties(); props.setProperty("hosts", "localhost"); props.setProperty("port", "5984"); cli.setProperties(props);//w ww .j a v a 2 s . c o m try { cli.init(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>(); vals.put("age", new StringByteIterator("57")); vals.put("middlename", new StringByteIterator("bradley")); vals.put("favoritecolor", new StringByteIterator("blue")); int res = cli.insert("usertable", "BrianFrankCooper", vals); System.out.println("Result of insert: " + res); HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>(); HashSet<String> fields = new HashSet<String>(); fields.add("middlename"); fields.add("age"); fields.add("favoritecolor"); res = cli.read("usertable", "BrianFrankCooper", null, result); System.out.println("Result of read: " + res); for (String s : result.keySet()) { System.out.println("[" + s + "]=[" + result.get(s) + "]"); } res = cli.delete("usertable", "BrianFrankCooper"); System.out.println("Result of delete: " + res); }
From source file:io.s4.latin.adapter.TwitterFeedListener.java
public static void main(String[] args) { Properties props = new Properties(); props.setProperty("user", ""); props.setProperty("password", ""); props.setProperty("url", "http://stream.twitter.com/1/statuses/sample.json"); props.setProperty("stream", "TestStream"); TwitterFeedListener a = new TwitterFeedListener(props); a.init();//from w w w . j av a 2s . c o m }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSwingHttpCLI.CFAsteriskSwingHttpCLI.java
public static void main(String args[]) { final String S_ProcName = "CFAsteriskSwingHttpCLI.main() "; initConsoleLog();/*from w ww.java2 s. co m*/ boolean fastExit = false; String homeDirName = System.getProperty("HOME"); if (homeDirName == null) { homeDirName = System.getProperty("user.home"); if (homeDirName == null) { log.message(S_ProcName + "ERROR: Home directory not set"); return; } } File homeDir = new File(homeDirName); if (!homeDir.exists()) { log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist"); return; } if (!homeDir.isDirectory()) { log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory"); return; } CFAsteriskClientConfigurationFile cFAsteriskClientConfig = new CFAsteriskClientConfigurationFile(); String cFAsteriskClientConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskclientrc"; cFAsteriskClientConfig.setFileName(cFAsteriskClientConfigFileName); File cFAsteriskClientConfigFile = new File(cFAsteriskClientConfigFileName); if (!cFAsteriskClientConfigFile.exists()) { String cFAsteriskKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks"; cFAsteriskClientConfig.setKeyStore(cFAsteriskKeyStoreFileName); InetAddress localHost; try { localHost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { localHost = null; } if (localHost == null) { log.message(S_ProcName + "ERROR: LocalHost is null"); return; } String hostName = localHost.getHostName(); if ((hostName == null) || (hostName.length() <= 0)) { log.message("ERROR: LocalHost.HostName is null or empty"); return; } String userName = System.getProperty("user.name"); if ((userName == null) || (userName.length() <= 0)) { log.message("ERROR: user.name is null or empty"); return; } String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-" + userName.replaceAll("[^\\w]", "_").toLowerCase(); cFAsteriskClientConfig.setDeviceName(deviceName); cFAsteriskClientConfig.save(); log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file " + cFAsteriskClientConfigFileName); fastExit = true; } if (!cFAsteriskClientConfigFile.isFile()) { log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFAsteriskClientConfigFileName + " is not a file."); fastExit = true; } if (!cFAsteriskClientConfigFile.canRead()) { log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file " + cFAsteriskClientConfigFileName); fastExit = true; } cFAsteriskClientConfig.load(); if (fastExit) { return; } // Configure logging Properties sysProps = System.getProperties(); sysProps.setProperty("log4j.rootCategory", "WARN"); sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger"); Logger httpLogger = Logger.getLogger("org.apache.http"); httpLogger.setLevel(Level.WARN); // The Invoker and it's implementation CFAsteriskXMsgClientHttpSchema invoker = new CFAsteriskXMsgClientHttpSchema(); // And now for the client side cache implementation that invokes it ICFAsteriskSchemaObj clientSchemaObj = new CFAsteriskSchemaObj() { public void logout() { CFAsteriskXMsgClientHttpSchema invoker = (CFAsteriskXMsgClientHttpSchema) getBackingStore(); try { invoker.logout(getAuthorization()); } catch (RuntimeException e) { } setAuthorization(null); } }; clientSchemaObj.setBackingStore(invoker); // And stitch the response handler to reference our client instance invoker.setResponseHandlerSchemaObj(clientSchemaObj); // And now we can stitch together the CLI to the SAX loader code CFAsteriskSwingHttpCLI cli = new CFAsteriskSwingHttpCLI(); cli.setXMsgClientHttpSchema(invoker); cli.setSchema(clientSchemaObj); ICFAsteriskSwingSchema swing = cli.getSwingSchema(); swing.setClientConfigurationFile(cFAsteriskClientConfig); swing.setSchema(clientSchemaObj); swing.setClusterName("system"); swing.setTenantName("system"); swing.setSecUserName("system"); JFrame jframe = cli.getDesktop(); jframe.setVisible(true); jframe.toFront(); }
From source file:at.riemers.velocity2js.velocity.Velocity2Js.java
/** * @param args the command line arguments *//*from ww w.j a va 2 s . c o m*/ public static void main(String[] args) { try { if (args.length == 0) { printUsage(); return; } if (args[0].equals("-d") && args.length >= 3) { String resource = null; if (args.length >= 4) { resource = args[3]; } List<I18NBundle> bundles = getBundles(resource); Velocity2Js.generateDir(args[1], args[2], bundles); return; } if (args[0].equals("-f") && args.length >= 4) { Properties p = new Properties(); p.setProperty("resource.loader", "file"); p.setProperty("file.resource.loader.description", "Velocity File Resource Loader"); p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); p.setProperty("file.resource.loader.path", args[1]); Velocity2Js.init(p); String function = createFunctionName(args[2]); String resource = null; if (args.length >= 5) { resource = args[4]; } List<I18NBundle> bundles = getBundles(resource); for (I18NBundle bundle : bundles) { String fname = args[3]; int e = args[3].lastIndexOf('.'); if (e <= 0 || e > args[3].length()) e = args[3].length(); fname = args[3].substring(0, e) + bundle.getLocale() + args[3].substring(e); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(fname), "UTF8")); Velocity2Js.generate(args[2], function, writer, bundle.getBundle()); writer.flush(); writer.close(); } return; } printUsage(); return; } catch (ResourceNotFoundException rnfe) { log.error("[velocity2js] : cannot find template : " + rnfe.getMessage()); } catch (ParseErrorException pee) { log.error("[velocity2js] : Syntax error in template :" + pee); } catch (Exception ex) { System.out.flush(); log.error("[velocity2js] : unknown error " + ex.getMessage()); ex.printStackTrace(System.out); System.out.println(ex.getLocalizedMessage()); System.exit(1); } }
From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java
public static void main(String[] args) throws Exception { Parser parser = new PosixParser(); Options options = new Options(); options.addOption("r", "repo", true, "Repository type to search: local|central"); options.addOption("c", "client-concurrency", true, "Max threads to allow each client tester to run tests, defaults to 10"); options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5"); options.addOption("m", "max-time", true, "Max time (in minutes) to allow tests to complete, defaults to 10"); options.addOption("v", "version", false, "Print version and exit"); options.addOption("h", "help", false, "This help text"); CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { System.out.println(options); System.exit(0);// ww w . j a va 2 s .c om } if (commandLine.hasOption("v")) { System.out.println("How the hell should I know?"); System.exit(0); } // 1. Find all testers in given repos List<RepoSearcher> repoSearchers = new ArrayList<>(); for (String repo : commandLine.getOptionValues("r")) { if ("local".equals(repo.toLowerCase())) { repoSearchers.add(new LocalRepoSearcher()); } else if ("central".equals(repo.toLowerCase())) { repoSearchers.add(new CentralRepoSearcher()); } else { System.err.println("Unrecognized repo: " + repo); System.err.println(options); System.exit(1); } } int clientConcurrency = 10; if (commandLine.hasOption("c")) { try { clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c")); } catch (NumberFormatException nfe) { System.err.println( "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'"); System.exit(1); } } int testConcurrency = 5; if (commandLine.hasOption("t")) { try { testConcurrency = Integer.parseInt(commandLine.getOptionValue("t")); } catch (NumberFormatException nfe) { System.err.println( "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'"); System.exit(1); } } int maxMinutes = 10; if (commandLine.hasOption("m")) { try { maxMinutes = Integer.parseInt(commandLine.getOptionValue("m")); } catch (NumberFormatException nfe) { System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'"); System.exit(1); } } Properties clientProps = new Properties(); clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency)); File baseRunDir = new File(System.getProperty("user.dir") + "/run"); baseRunDir.mkdirs(); File tmpDir = new File(baseRunDir, "jars"); tmpDir.mkdirs(); List<ServerRunner> serverRunners = new ArrayList<>(); List<ClientRunner> clientRunners = new ArrayList<>(); for (RepoSearcher searcher : repoSearchers) { List<File> jars = searcher.findAndCache(tmpDir); for (File f : jars) { ServerRunner serverRunner = new ServerRunner(f, baseRunDir); System.out.println("Found tester: " + serverRunner.getVersion()); serverRunners.add(serverRunner); clientRunners.add(new ClientRunner(f, baseRunDir, clientProps)); } } // 2. Start servers and collect ports System.out.println(); System.out.println("Starting " + serverRunners.size() + " servers..."); for (ServerRunner server : serverRunners) { server.startServer(); } System.out.println(); List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size()); for (ServerRunner server : serverRunners) { for (ClientRunner client : clientRunners) { tests.add(new TestCombo(server, client)); } } System.out.println("Enqueued " + tests.size() + " test combos to run..."); long startTime = System.currentTimeMillis(); // 3. Run every client against every server, collecting results BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size()); ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000, TimeUnit.MILLISECONDS, workQueue); service.prestartAllCoreThreads(); workQueue.addAll(tests); while (!workQueue.isEmpty()) { Thread.sleep(1000); } service.shutdown(); service.awaitTermination(maxMinutes, TimeUnit.MINUTES); long endTime = System.currentTimeMillis(); long totalTimeSecs = Math.round((endTime - startTime) / 1000.0); for (ServerRunner server : serverRunners) { server.shutdownServer(); } System.out.println(); System.out.println("======="); System.out.println("Results"); System.out.println("-------"); // print a summary int totalTests = 0; int totalSuccess = 0; for (TestCombo combo : tests) { String clientVer = combo.getClientVersion(); String serverVer = combo.getServerVersion(); String results = combo.getClientResults(); ObjectMapper mapper = new ObjectMapper(new JsonFactory()); JsonNode node = mapper.reader().readTree(results); JsonNode resultsArray = node.get("results"); int numTests = resultsArray.size(); int numSuccess = 0; for (int i = 0; i < numTests; i++) { if ("success".equals(resultsArray.get(i).get("result").asText())) { numSuccess++; } } totalSuccess += numSuccess; totalTests += numTests; System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds"); } System.out.println("-------"); System.out.println( "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds"); FileWriter out = new FileWriter("results.json"); PrintWriter pw = new PrintWriter(out); // 4. Output full results pw.println("{\n \"results\": ["); for (TestCombo combo : tests) { combo.emitResults(pw, " "); } pw.println(" ],"); pw.println(" \"servers\": ["); for (ServerRunner server : serverRunners) { server.emitInfo(pw, " "); } pw.println(" ],"); pw.close(); }
From source file:jp.mamesoft.mailsocketchat.Mailsocketchat.java
public static void main(String argv[]) { System.out.println("MailSocketChat Ver." + version); if (argv.length != 6) { System.out.println(//from ww w . j a v a2 s. c om "ERROR! ? <?URL> <???> <GMail??> <GMail> <(Simple???Normal???All)> <????(Subject???Text)> ???????"); System.exit(0); } TimerTask newversion = new NewVersion(); Timer timer = new Timer(); timer.schedule(newversion, 0, 6 * 60 * 60 * 1000); //6?????? chat_url = argv[0]; chat_name = argv[1]; mail_user = argv[2]; mail_pass = argv[3]; if (argv[4].equals("Simple")) { logformat = "simple"; } else if (argv[4].equals("Normal")) { logformat = "normal"; } else if (argv[4].equals("All")) { logformat = "all"; } else { System.out.println( "ERROR! (5)???????Simple???Normal???All???????"); System.exit(0); } if (argv[5].equals("Subject")) { subjectname = true; } else if (argv[5].equals("Text")) { subjectname = false; } else { System.out.println( "ERROR! ????(6)???????Subject???Text???????"); System.exit(0); } try { Properties headers = new Properties(); headers.setProperty("user-agent", "MailSocketChat/" + version + " (" + osName + " " + osVer + ") Java/" + javaver + " (Mamesoft Web)"); socket = new SocketIO(chat_url, headers); socket.connect(new IOCallback() { @Override public void onMessage(JSONObject json, IOAcknowledge ack) { try { } catch (JSONException e) { e.printStackTrace(); } } @Override public void onMessage(String data, IOAcknowledge ack) { } @Override public void onError(SocketIOException socketIOException) { System.out.println("??????"); System.err.println(socketIOException); System.exit(0); } @Override public void onDisconnect() { System.out.println("???????"); System.exit(0); } @Override public void onConnect() { socket.emit("register", new JSONObject().put("mode", "client").put("lastid", 1)); System.out.println("SocketChat?????"); Thread mail = new Mail(); mail.start(); } @Override public void on(String event, IOAcknowledge ack, Object... args) { if (event.equals("log")) { JSONObject jsondata = (JSONObject) args[0]; Logperse(jsondata); } if (event.equals("init")) { JSONObject jsondata = (JSONObject) args[0]; JSONArray logs = jsondata.getJSONArray("logs"); for (int i = logs.length() - 1; i >= 0; i--) { JSONObject log = logs.getJSONObject(i); Logperse(log); } socket.emit("inout", new JSONObject().put("name", chat_name)); } if (event.equals("result")) { JSONObject jsondata = (JSONObject) args[0]; System.out.println(jsondata); } if (event.equals("users")) { JSONObject jsondata = (JSONObject) args[0]; JSONArray users = jsondata.getJSONArray("users"); for (int i = 0; i < users.length(); i++) { JSONObject user = users.getJSONObject(i); userchange(user); } } if (event.equals("newuser")) { JSONObject jsondata = (JSONObject) args[0]; userchange(jsondata); } if (event.equals("inout")) { JSONObject jsondata = (JSONObject) args[0]; userchange(jsondata); } if (event.equals("deluser")) { Integer id = (Integer) args[0]; if (users.containsKey(id)) { users.remove(id); } if (roms.containsKey(id)) { roms.remove(id); } } if (event.equals("userinfo")) { JSONObject jsondata = (JSONObject) args[0]; if (jsondata.getBoolean("rom")) { in = false; } else { in = true; } } } }); } catch (MalformedURLException e1) { e1.printStackTrace(); System.out.println("URL????????"); return; } }