List of usage examples for java.util Properties Properties
public Properties()
From source file:com.callidusrobotics.irc.NaNoBot.java
public static void main(final String[] args) throws FileNotFoundException, IOException, NickAlreadyInUseException, IrcException { if (args.length > 0 && "--version".equals(args[0])) { System.out.println("NaNoBot version: " + getImplementationVersion()); System.exit(0);//from ww w. j a v a2 s . c o m } final String fileName = args.length > 0 ? args[0] : "./NaNoBot.properties"; final Properties properties = new Properties(); properties.load(new FileInputStream(new File(fileName))); final NaNoBot naNoBot = new NaNoBot(properties); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { naNoBot.shutdown(); } }); naNoBot.run(); }
From source file:JDOCreateDataStore.java
public static void main(String[] args) throws IOException { Properties p = new Properties(); p.load(new FileInputStream("jdo.properties")); p.setProperty("com.sun.jdori.option.ConnectionCreate", "true"); PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(p); PersistenceManager pm = pmf.getPersistenceManager(); Transaction tx = pm.currentTransaction(); tx.begin();/*from w w w .j a v a2 s. c om*/ tx.commit(); }
From source file:net.prhin.mailman.MailMan.java
public static void main(String[] args) { Properties props = new Properties(); props.setProperty(resourceBundle.getString("mailman.mail.store"), resourceBundle.getString("mailman.protocol")); Session session = Session.getInstance(props); try {//w ww. java 2 s . co m Store store = session.getStore(); store.connect(resourceBundle.getString("mailman.host"), resourceBundle.getString("mailman.user"), resourceBundle.getString("mailman.password")); Folder inbox = store.getFolder(resourceBundle.getString("mailman.folder")); inbox.open(Folder.READ_ONLY); inbox.getUnreadMessageCount(); Message[] messages = inbox.getMessages(); for (int i = 0; i <= messages.length / 2; i++) { Message tmpMessage = messages[i]; Multipart multipart = (Multipart) tmpMessage.getContent(); System.out.println("Multipart count: " + multipart.getCount()); for (int j = 0; j < multipart.getCount(); j++) { BodyPart bodyPart = multipart.getBodyPart(j); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) { if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) { MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent(); for (int k = 0; k < mimeMultipart.getCount(); k++) { if (mimeMultipart.getBodyPart(k).getFileName() != null) { printFileContents(mimeMultipart.getBodyPart(k)); } } } } else { printFileContents(bodyPart); } } } inbox.close(false); store.close(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java
public static void main(String... args) throws IOException { CommandLineParser parser = new DefaultParser(); Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert") .longOpt("source").hasArg(true).build()); options.addOption(Option.builder("t").argName("target").desc("the target file to store in") .longOpt("target").hasArg(true).build()); options.addOption(Option.builder("h").desc("print help").build()); try {/* w ww . j a v a2 s. co m*/ CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { formatter.printHelp("converter", options); } File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir"))); String name = source.getName(); if (source.isDirectory()) { PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter(); String[] ext = { "properties" }; Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true); while (fileIterator.hasNext()) { File next = fileIterator.next(); System.out.println(next); String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath()); System.out.println(s); String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0]; System.out.println("key = " + f); Properties p = new Properties(); try { p.load(new FileReader(next)); yamlConverter.addProperties(f, p); } catch (IOException e) { e.printStackTrace(); } } FileWriter fileWriter = new FileWriter( new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml")); yamlConverter.writeYaml(fileWriter); fileWriter.close(); } else { Properties p = new Properties(); p.load(new FileReader(source)); FileWriter fileWriter = new FileWriter( new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml")); new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter); fileWriter.close(); } } catch (ParseException e) { e.printStackTrace(); formatter.printHelp("converter", options); } }
From source file:net.ontopia.persistence.rdbms.DDLExecuter.java
public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging();/*from ww w. j a va 2s. co m*/ // Initialize command line option parser and listeners CmdlineOptions options = new CmdlineOptions("DDLExecuter", argv); // Register logging options CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length < 2) { System.err.println("Error: wrong number of arguments."); usage(); System.exit(1); } String schema = args[0]; String dbprops = args[1]; String action = args[2]; if (!("create".equals(action) || "drop".equals(action) || "recreate".equals(action))) { System.err.println("Error: unknown action: " + action); usage(); System.exit(1); } // Load property file Properties props = new Properties(); props.load(new FileInputStream(dbprops)); // Get database properties from property file String[] platforms = StringUtils.split(props.getProperty("net.ontopia.topicmaps.impl.rdbms.Platforms"), ","); Project project = DatabaseProjectReader.loadProject(schema); //! //! if (dbtype.equals("generic")) //! //! producer = new GenericSQLProducer(project, StringUtils.split(dbtype, ",")); //! //! else //! if (dbtype.equals("mysql")) //! producer = new MySqlSQLProducer(project); //! else if (dbtype.equals("oracle")) //! producer = new OracleSQLProducer(project); //! else { //! producer = new GenericSQLProducer(project, StringUtils.split(dbtype, ",")); //! //! System.err.println("Error: unknown database type: " + dbtype); //! //! usage(); //! //! System.exit(1); //! } // Create SQL producer GenericSQLProducer producer = getSQLProducer(project, platforms); log.debug("Using SQL producer: " + producer); // Create database connection DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false); Connection conn = cfactory.requestConnection(); // Execute statements try { if ("create".equals(action)) producer.executeCreate(conn); else if ("drop".equals(action)) producer.executeDrop(conn); else if ("recreate".equals(action)) { producer.executeDrop(conn); producer.executeCreate(conn); } conn.commit(); } finally { if (conn != null) conn.close(); } }
From source file:registry.java
public static void main(String[] args) { Properties props = new Properties(); // set smtp and imap to be our default // transport and store protocols, respectively props.put("mail.transport.protocol", "smtp"); props.put("mail.store.protocol", "imap"); // //w w w . j av a 2 s . c o m props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport"); props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore"); Session session = Session.getInstance(props, null); // session.setDebug(true); // Retrieve all configured providers from the Session System.out.println("\n------ getProviders()----------"); Provider[] providers = session.getProviders(); for (int i = 0; i < providers.length; i++) { System.out.println("** " + providers[i]); // let's remember some providers so that we can use them later // (I'm explicitly showing multiple ways of testing Providers) // BTW, no Provider "ACME Corp" will be found in the default // setup b/c its not in any javamail.providers resource files String s = null; if (((s = providers[i].getVendor()) != null) && s.startsWith("ACME Corp")) { _aProvider = providers[i]; } // this Provider won't be found by default either if (providers[i].getClassName().endsWith("application.smtp")) _bProvider = providers[i]; // this Provider will be found since com.sun.mail.imap.IMAPStore // is configured in javamail.default.providers if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")) { _sunIMAP = providers[i]; } // this Provider will be found as well since there is a // Sun Microsystems SMTP transport configured by // default in javamail.default.providers if (((s = providers[i].getVendor()) != null) && s.startsWith("Sun Microsystems") && providers[i].getType() == Provider.Type.TRANSPORT && providers[i].getProtocol().equalsIgnoreCase("smtp")) { _sunSMTP = providers[i]; } } System.out.println("\n------ initial protocol defaults -------"); try { System.out.println("imap: " + session.getProvider("imap")); System.out.println("smtp: " + session.getProvider("smtp")); // the NNTP provider will fail since we don't have one configured System.out.println("nntp: " + session.getProvider("nntp")); } catch (NoSuchProviderException mex) { System.out.println(">> This exception is OK since there is no NNTP Provider configured by default"); mex.printStackTrace(); } System.out.println("\n------ set new protocol defaults ------"); // set some new defaults try { // since _aProvider isn't configured, this will fail session.setProvider(_aProvider); // will fail } catch (NoSuchProviderException mex) { System.out.println(">> Exception expected: _aProvider is null"); mex.printStackTrace(); } try { // _sunIMAP provider should've configured correctly; should work session.setProvider(_sunIMAP); } catch (NoSuchProviderException mex) { mex.printStackTrace(); } try { System.out.println("imap: " + session.getProvider("imap")); System.out.println("smtp: " + session.getProvider("smtp")); } catch (NoSuchProviderException mex) { mex.printStackTrace(); } System.out.println("\n\n----- get some stores ---------"); // multiple ways to retrieve stores. these will print out the // string "imap:" since its the URLName for the store try { System.out.println("getStore(): " + session.getStore()); System.out.println("getStore(Provider): " + session.getStore(_sunIMAP)); } catch (NoSuchProviderException mex) { mex.printStackTrace(); } try { System.out.println("getStore(imap): " + session.getStore("imap")); // pop3 will fail since it doesn't exist System.out.println("getStore(pop3): " + session.getStore("pop3")); } catch (NoSuchProviderException mex) { System.out.println(">> Exception expected: no pop3 provider"); mex.printStackTrace(); } System.out.println("\n\n----- now for transports/addresses ---------"); // retrieve transports; these will print out "smtp:" (like stores did) try { System.out.println("getTransport(): " + session.getTransport()); System.out.println("getTransport(Provider): " + session.getTransport(_sunSMTP)); System.out.println("getTransport(smtp): " + session.getTransport("smtp")); System.out.println( "getTransport(Address): " + session.getTransport(new InternetAddress("mspivak@apilon"))); // News will fail since there's no news provider configured System.out.println("getTransport(News): " + session.getTransport(new NewsAddress("rec.humor"))); } catch (MessagingException mex) { System.out.println(">> Exception expected: no news provider configured"); mex.printStackTrace(); } }
From source file:ab.demo.MainEntry.java
public static void main(String args[]) { LoggingHandler.initConsoleLog();/*from w ww .j a v a 2 s . c o m*/ //args = new String[]{"-su"}; Options options = new Options(); options.addOption("s", "standalone", false, "runs the reinforcement learning agent in standalone mode"); options.addOption("p", "proxyPort", true, "the port which is to be used by the proxy"); options.addOption("h", "help", false, "displays this help"); options.addOption("n", "naiveAgent", false, "runs the naive agent in standalone mode"); options.addOption("c", "competition", false, "runs the naive agent in the server/client competition mode"); options.addOption("u", "updateDatabaseTables", false, "executes CREATE TABLE IF NOT EXIST commands"); options.addOption("l", "level", true, "if set the agent is playing only in this one level"); options.addOption("m", "manual", false, "runs the empirical threshold determination agent in standalone mode"); options.addOption("r", "real", false, "shows the recognized shapes in a new frame"); CommandLineParser parser = new DefaultParser(); CommandLine cmd; StandaloneAgent agent; Properties properties = new Properties(); InputStream configInputStream = null; try { Class.forName("org.sqlite.JDBC"); //parse configuration file configInputStream = new FileInputStream("config.properties"); properties.load(configInputStream); } catch (IOException exception) { exception.printStackTrace(); } catch (ClassNotFoundException exception) { exception.printStackTrace(); } finally { if (configInputStream != null) { try { configInputStream.close(); } catch (IOException exception) { exception.printStackTrace(); } } } String dbPath = properties.getProperty("db_path"); String dbUser = properties.getProperty("db_user"); String dbPass = properties.getProperty("db_pass"); DBI dbi = new DBI(dbPath, dbUser, dbPass); QValuesDAO qValuesDAO = dbi.open(QValuesDAO.class); GamesDAO gamesDAO = dbi.open(GamesDAO.class); MovesDAO movesDAO = dbi.open(MovesDAO.class); ProblemStatesDAO problemStatesDAO = dbi.open(ProblemStatesDAO.class); try { cmd = parser.parse(options, args); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } int proxyPort = 9000; if (cmd.hasOption("proxyPort")) { proxyPort = Integer.parseInt(cmd.getOptionValue("proxyPort")); logger.info("Set proxy port to " + proxyPort); } Proxy.setPort(proxyPort); LoggingHandler.initFileLog(); if (cmd.hasOption("standalone")) { agent = new ReinforcementLearningAgent(gamesDAO, movesDAO, problemStatesDAO, qValuesDAO); } else if (cmd.hasOption("naiveAgent")) { agent = new NaiveStandaloneAgent(); } else if (cmd.hasOption("manual")) { agent = new ManualGamePlayAgent(gamesDAO, movesDAO, problemStatesDAO); } else if (cmd.hasOption("competition")) { System.out.println("We haven't implemented a competition ready agent yet."); return; } else { System.out.println("Please specify which solving strategy we should be using."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } if (cmd.hasOption("updateDatabaseTables")) { qValuesDAO.createTable(); gamesDAO.createTable(); movesDAO.createTable(); problemStatesDAO.createTable(); problemStatesDAO.createObjectsTable(); } if (cmd.hasOption("level")) { agent.setFixedLevel(Integer.parseInt(cmd.getOptionValue("level"))); } if (cmd.hasOption("real")) { ShowSeg.useRealshape = true; Thread thread = new Thread(new ShowSeg()); thread.start(); } } catch (UnrecognizedOptionException e) { System.out.println("Unrecognized commandline option: " + e.getOption()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } catch (ParseException e) { System.out.println( "There was an error while parsing your command line input. Did you rechecked your syntax before running?"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); return; } agent.run(); }
From source file:com.joliciel.jochre.search.JochreSearch.java
/** * @param args/* w w w.j a v a 2s . co m*/ */ public static void main(String[] args) { try { Map<String, String> argMap = new HashMap<String, String>(); for (String arg : args) { int equalsPos = arg.indexOf('='); String argName = arg.substring(0, equalsPos); String argValue = arg.substring(equalsPos + 1); argMap.put(argName, argValue); } String command = argMap.get("command"); argMap.remove("command"); String logConfigPath = argMap.get("logConfigFile"); if (logConfigPath != null) { argMap.remove("logConfigFile"); Properties props = new Properties(); props.load(new FileInputStream(logConfigPath)); PropertyConfigurator.configure(props); } LOG.debug("##### Arguments:"); for (Entry<String, String> arg : argMap.entrySet()) { LOG.debug(arg.getKey() + ": " + arg.getValue()); } SearchServiceLocator locator = SearchServiceLocator.getInstance(); SearchService searchService = locator.getSearchService(); if (command.equals("buildIndex")) { String indexDirPath = argMap.get("indexDir"); String documentDirPath = argMap.get("documentDir"); File indexDir = new File(indexDirPath); indexDir.mkdirs(); File documentDir = new File(documentDirPath); JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir); builder.updateDocument(documentDir); } else if (command.equals("updateIndex")) { String indexDirPath = argMap.get("indexDir"); String documentDirPath = argMap.get("documentDir"); boolean forceUpdate = false; if (argMap.containsKey("forceUpdate")) { forceUpdate = argMap.get("forceUpdate").equals("true"); } File indexDir = new File(indexDirPath); indexDir.mkdirs(); File documentDir = new File(documentDirPath); JochreIndexBuilder builder = searchService.getJochreIndexBuilder(indexDir); builder.updateIndex(documentDir, forceUpdate); } else if (command.equals("search")) { HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator.getInstance(locator); HighlightService highlightService = highlightServiceLocator.getHighlightService(); String indexDirPath = argMap.get("indexDir"); File indexDir = new File(indexDirPath); JochreQuery query = searchService.getJochreQuery(argMap); JochreIndexSearcher searcher = searchService.getJochreIndexSearcher(indexDir); TopDocs topDocs = searcher.search(query); Set<Integer> docIds = new LinkedHashSet<Integer>(); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { docIds.add(scoreDoc.doc); } Set<String> fields = new HashSet<String>(); fields.add("text"); Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher()); HighlightManager highlightManager = highlightService .getHighlightManager(searcher.getIndexSearcher()); highlightManager.setDecimalPlaces(query.getDecimalPlaces()); highlightManager.setMinWeight(0.0); highlightManager.setIncludeText(true); highlightManager.setIncludeGraphics(true); Writer out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8)); if (command.equals("highlight")) { highlightManager.highlight(highlighter, docIds, fields, out); } else { highlightManager.findSnippets(highlighter, docIds, fields, out); } } else { throw new RuntimeException("Unknown command: " + command); } } catch (RuntimeException e) { LogUtils.logError(LOG, e); throw e; } catch (IOException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } }
From source file:msgsendsample.java
public static void main(String[] args) { if (args.length != 4) { usage();/*w w w. j a v a 2 s .c om*/ System.exit(1); } System.out.println(); String to = args[0]; String from = args[1]; String host = args[2]; boolean debug = Boolean.valueOf(args[3]).booleanValue(); // create some properties and get the default Session Properties props = new Properties(); props.put("mail.smtp.host", host); if (debug) props.put("mail.debug", args[3]); Session session = Session.getInstance(props, null); session.setDebug(debug); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject("JavaMail APIs Test"); msg.setSentDate(new Date()); // If the desired charset is known, you can use // setText(text, charset) msg.setText(msgText); Transport.send(msg); } catch (MessagingException mex) { System.out.println("\n--Exception handling in msgsendsample.java"); mex.printStackTrace(); System.out.println(); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { System.out.println(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) System.out.println(" " + invalid[i]); } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { System.out.println(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) System.out.println(" " + validUnsent[i]); } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) System.out.println(" " + validSent[i]); } } System.out.println(); if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); } }
From source file:com.cloud.test.utils.SubmitCert.java
public static void main(String[] args) { // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); if (arg.equals("-c")) { certFileName = iter.next();//from w w w. j a va 2 s . c o m } if (arg.equals("-s")) { secretKey = iter.next(); } if (arg.equals("-a")) { apiKey = iter.next(); } if (arg.equals("-action")) { url = "Action=" + iter.next(); } } Properties prop = new Properties(); try { prop.load(new FileInputStream("conf/tool.properties")); } catch (IOException ex) { s_logger.error("Error reading from conf/tool.properties", ex); System.exit(2); } host = prop.getProperty("host"); port = prop.getProperty("port"); if (url.equals("Action=SetCertificate") && certFileName == null) { s_logger.error("Please set path to certificate (including file name) with -c option"); System.exit(1); } if (secretKey == null) { s_logger.error("Please set secretkey with -s option"); System.exit(1); } if (apiKey == null) { s_logger.error("Please set apikey with -a option"); System.exit(1); } if (host == null) { s_logger.error("Please set host in tool.properties file"); System.exit(1); } if (port == null) { s_logger.error("Please set port in tool.properties file"); System.exit(1); } TreeMap<String, String> param = new TreeMap<String, String>(); String req = "GET\n" + host + ":" + prop.getProperty("port") + "\n/" + prop.getProperty("accesspoint") + "\n"; String temp = ""; if (certFileName != null) { cert = readCert(certFileName); param.put("cert", cert); } param.put("AWSAccessKeyId", apiKey); param.put("Expires", prop.getProperty("expires")); param.put("SignatureMethod", prop.getProperty("signaturemethod")); param.put("SignatureVersion", "2"); param.put("Version", prop.getProperty("version")); StringTokenizer str1 = new StringTokenizer(url, "&"); while (str1.hasMoreTokens()) { String newEl = str1.nextToken(); StringTokenizer str2 = new StringTokenizer(newEl, "="); String name = str2.nextToken(); String value = str2.nextToken(); param.put(name, value); } //sort url hash map by key Set c = param.entrySet(); Iterator it = c.iterator(); while (it.hasNext()) { Map.Entry me = (Map.Entry) it.next(); String key = (String) me.getKey(); String value = (String) me.getValue(); try { temp = temp + key + "=" + URLEncoder.encode(value, "UTF-8") + "&"; } catch (Exception ex) { s_logger.error("Unable to set parameter " + value + " for the command " + param.get("command"), ex); } } temp = temp.substring(0, temp.length() - 1); String requestToSign = req + temp; String signature = UtilsForTest.signRequest(requestToSign, secretKey); String encodedSignature = ""; try { encodedSignature = URLEncoder.encode(signature, "UTF-8"); } catch (Exception ex) { ex.printStackTrace(); } String url = "http://" + host + ":" + prop.getProperty("port") + "/" + prop.getProperty("accesspoint") + "?" + temp + "&Signature=" + encodedSignature; s_logger.info("Sending request with url: " + url + "\n"); sendRequest(url); }