List of usage examples for java.util Properties load
public synchronized void load(InputStream inStream) throws IOException
From source file:sample.jetty.SampleJettyApplication.java
public static void main(String[] args) throws Exception { InputStream inputstream = null; try {/*from w w w . jav a 2 s . c om*/ Properties pro = new Properties(); //????? URL url = org.springframework.util.ResourceUtils.getURL("classpath:MySql_general.properties"); inputstream = url.openStream(); pro.load(inputstream); //new EmbedMySqlServer(pro).startup(); String dbPath = (new File("")).getAbsolutePath() + "/db/"; dbPath = dbPath.replaceAll("\\\\", "/"); //??? EmbedMySqlServer mysqldbServer = new EmbedMySqlServer(pro, dbPath /*"C:\\gfworklog\\db\\"*/); SampleJettyApplication.MAIN_THREAD_LOCAL.put("embedMysqlServer", mysqldbServer); mysqldbServer.startup(); } catch (Exception e) { e.printStackTrace(); } finally { try { inputstream.close(); } catch (Exception ex) { } } System.out.println(Thread.currentThread().getName() + " ========================= " + 1 + " ========================="); ConfigurableApplicationContext cac = SpringApplication.run(SampleJettyApplication.class, args); }
From source file:com.cloud.sample.UserCloudAPIExecutor.java
public static void main(String[] args) { // Host/*w ww .ja va 2 s. co m*/ String host = null; // Fully qualified URL with http(s)://host:port String apiUrl = null; // ApiKey and secretKey as given by your CloudStack vendor String apiKey = null; String secretKey = null; try { Properties prop = new Properties(); prop.load(new FileInputStream("usercloud.properties")); // host host = prop.getProperty("host"); if (host == null) { System.out.println( "Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file."); } // apiUrl apiUrl = prop.getProperty("apiUrl"); if (apiUrl == null) { System.out.println( "Please specify a valid API URL in the format of command=¶m1=¶m2=... in your usercloud.properties file."); } // apiKey apiKey = prop.getProperty("apiKey"); if (apiKey == null) { System.out.println( "Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file."); } // secretKey secretKey = prop.getProperty("secretKey"); if (secretKey == null) { System.out.println( "Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file."); } if (apiUrl == null || apiKey == null || secretKey == null) { return; } System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'"); // Step 1: Make sure your APIKey is URL encoded String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8"); // Step 2: URL encode each parameter value, then sort the parameters and apiKey in // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey. // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using // '&' to delimit // the string List<String> sortedParams = new ArrayList<String>(); sortedParams.add("apikey=" + encodedApiKey.toLowerCase()); StringTokenizer st = new StringTokenizer(apiUrl, "&"); String url = null; boolean first = true; while (st.hasMoreTokens()) { String paramValue = st.nextToken(); String param = paramValue.substring(0, paramValue.indexOf("=")); String value = URLEncoder .encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8"); if (first) { url = param + "=" + value; first = false; } else { url = url + "&" + param + "=" + value; } sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase()); } Collections.sort(sortedParams); System.out.println("Sorted Parameters: " + sortedParams); // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key String sortedUrl = null; first = true; for (String param : sortedParams) { if (first) { sortedUrl = param; first = false; } else { sortedUrl = sortedUrl + "&" + param; } } System.out.println("sorted URL : " + sortedUrl); String encodedSignature = signRequest(sortedUrl, secretKey); // Step 4: Construct the final URL we want to send to the CloudStack Management Server // Final result should look like: // http(s)://://client/api?&apiKey=&signature= String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature; System.out.println("final URL : " + finalUrl); // Step 5: Perform a HTTP GET on this URL to execute the command HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(finalUrl); int responseCode = client.executeMethod(method); if (responseCode == 200) { // SUCCESS! System.out.println("Successfully executed command"); } else { // FAILED! System.out.println("Unable to execute command with response code: " + responseCode); } } catch (Throwable t) { System.out.println(t); } }
From source file:com.joliciel.talismane.terminology.Main.java
public static void main(String[] args) throws Exception { String termFilePath = null;/*from ww w .ja v a 2 s.c o m*/ String outFilePath = null; Command command = Command.extract; int depth = -1; String databasePropertiesPath = null; String projectCode = null; Map<String, String> argMap = TalismaneConfig.convertArgs(args); String logConfigPath = argMap.get("logConfigFile"); if (logConfigPath != null) { argMap.remove("logConfigFile"); Properties props = new Properties(); props.load(new FileInputStream(logConfigPath)); PropertyConfigurator.configure(props); } Map<String, String> innerArgs = new HashMap<String, String>(); for (Entry<String, String> argEntry : argMap.entrySet()) { String argName = argEntry.getKey(); String argValue = argEntry.getValue(); if (argName.equals("command")) command = Command.valueOf(argValue); else if (argName.equals("termFile")) termFilePath = argValue; else if (argName.equals("outFile")) outFilePath = argValue; else if (argName.equals("depth")) depth = Integer.parseInt(argValue); else if (argName.equals("databaseProperties")) databasePropertiesPath = argValue; else if (argName.equals("projectCode")) projectCode = argValue; else innerArgs.put(argName, argValue); } if (termFilePath == null && databasePropertiesPath == null) throw new TalismaneException("Required argument: termFile or databasePropertiesPath"); if (termFilePath != null) { String currentDirPath = System.getProperty("user.dir"); File termFileDir = new File(currentDirPath); if (termFilePath.lastIndexOf("/") >= 0) { String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/")); termFileDir = new File(termFileDirPath); termFileDir.mkdirs(); } } long startTime = new Date().getTime(); try { TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance(); TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService(); TerminologyBase terminologyBase = null; if (projectCode == null) throw new TalismaneException("Required argument: projectCode"); File file = new File(databasePropertiesPath); FileInputStream fis = new FileInputStream(file); Properties dataSourceProperties = new Properties(); dataSourceProperties.load(fis); terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties); if (command.equals(Command.analyse) || command.equals(Command.extract)) { if (depth < 0) throw new TalismaneException("Required argument: depth"); if (command.equals(Command.analyse)) { innerArgs.put("command", "analyse"); } else { innerArgs.put("command", "process"); } TalismaneFrench talismaneFrench = new TalismaneFrench(); TalismaneConfig config = new TalismaneConfig(innerArgs, talismaneFrench); PosTagSet tagSet = TalismaneSession.getPosTagSet(); Charset outputCharset = config.getOutputCharset(); TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase); termExtractor.setMaxDepth(depth); termExtractor.setOutFilePath(termFilePath); termExtractor.getIncludeChildren().add(tagSet.getPosTag("P")); termExtractor.getIncludeChildren().add(tagSet.getPosTag("P+D")); termExtractor.getIncludeChildren().add(tagSet.getPosTag("CC")); termExtractor.getIncludeWithParent().add(tagSet.getPosTag("DET")); if (outFilePath != null) { if (outFilePath.lastIndexOf("/") >= 0) { String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/")); File outFileDir = new File(outFileDirPath); outFileDir.mkdirs(); } File outFile = new File(outFilePath); outFile.delete(); outFile.createNewFile(); Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset)); TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer); termExtractor.addTermObserver(termAnalysisWriter); } Talismane talismane = config.getTalismane(); talismane.setParseConfigurationProcessor(termExtractor); talismane.process(); } else if (command.equals(Command.list)) { List<Term> terms = terminologyBase.getTermsByFrequency(2); for (Term term : terms) { LOG.debug("Term: " + term.getText()); LOG.debug("Frequency: " + term.getFrequency()); LOG.debug("Heads: " + term.getHeads()); LOG.debug("Expansions: " + term.getExpansions()); LOG.debug("Contexts: " + term.getContexts()); } } } finally { long endTime = new Date().getTime(); long totalTime = endTime - startTime; LOG.info("Total time: " + totalTime); } }
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 w w w.ja v a 2s . c om*/ } 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:eu.databata.engine.util.PropagatorRecreateUserTool.java
public static void main(String[] args) { if (args.length == 0) { printMessage();// ww w .j a v a 2s . c o m return; } String scriptName = getScriptName(args[0]); if (scriptName == null) { printMessage(); return; } ClassLoader classLoader = PropagatorRecreateUserTool.class.getClassLoader(); InputStream resourceAsStream = classLoader.getResourceAsStream("databata.properties"); Properties propagatorProperties = new Properties(); try { 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")); if ("-idb".equals(args[0])) { 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")); } else { dataSource.setUrl(propagatorProperties.getProperty("db.propagation.sa.connection-url")); dataSource.setUsername(propagatorProperties.getProperty("db.propagation.sa.user")); dataSource.setPassword(propagatorProperties.getProperty("db.propagation.sa.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); return; } String databaseCode = PropagationUtils.getDatabaseCode(databaseName); LOG.info("Database with code '" + databaseCode + "' is identified. for database '" + databaseName + "'"); String submitFileName = "META-INF/databata/" + databaseCode + "_" + scriptName + ".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 + "_" + scriptName + ".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:LauncherBootstrap.java
/** * The main method./*from w w w . j a v a 2 s.co m*/ * * @param args command line arguments */ public static void main(String[] args) { try { // Try to find the LAUNCHER_JAR_FILE_NAME file in the class // loader's and JVM's classpath. URL coreURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.LAUNCHER_JAR_FILE_NAME); if (coreURL == null) throw new FileNotFoundException(LauncherBootstrap.LAUNCHER_JAR_FILE_NAME); // Coerce the coreURL's directory into a file File coreDir = new File(URLDecoder.decode(coreURL.getFile())).getCanonicalFile().getParentFile(); // Try to find the LAUNCHER_PROPS_FILE_NAME file in the same // directory as this class File propsFile = new File(coreDir, LauncherBootstrap.LAUNCHER_PROPS_FILE_NAME); if (!propsFile.canRead()) throw new FileNotFoundException(propsFile.getPath()); // Load the properties in the LAUNCHER_PROPS_FILE_NAME Properties props = new Properties(); FileInputStream fis = new FileInputStream(propsFile); props.load(fis); fis.close(); // Create a class loader that contains the Launcher, Ant, and // JAXP classes. URL[] antURLs = LauncherBootstrap .fileListToURLs((String) props.get(LauncherBootstrap.ANT_CLASSPATH_PROP_NAME)); URL[] urls = new URL[1 + antURLs.length]; urls[0] = coreURL; for (int i = 0; i < antURLs.length; i++) urls[i + 1] = antURLs[i]; ClassLoader parentLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader loader = null; if (parentLoader != null) loader = new URLClassLoader(urls, parentLoader); else loader = new URLClassLoader(urls); // Load the LAUNCHER_MAIN_CLASS_NAME class launcherClass = loader.loadClass(LAUNCHER_MAIN_CLASS_NAME); // Get the LAUNCHER_MAIN_CLASS_NAME class' getLocalizedString() // method as we need it for printing the usage statement Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString", new Class[] { String.class }); // Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method. // If the ant.class.path property is not set correctly in the // LAUNCHER_PROPS_FILE_NAME, this will throw an exception. Method startMethod = launcherClass.getDeclaredMethod("start", new Class[] { String[].class }); int returnValue = ((Integer) startMethod.invoke(null, new Object[] { args })).intValue(); // Always exit cleanly after invoking the start() method System.exit(returnValue); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
From source file:edu.indiana.d2i.sloan.internal.QueryVMSimulator.java
public static void main(String[] args) { QueryVMSimulator simulator = new QueryVMSimulator(); CommandLineParser parser = new PosixParser(); try {// ww w . j av a 2s . c om 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))); VMStatus status = new VMStatus( VMMode.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE))), VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE))), ip, Integer.parseInt(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT))), Integer.parseInt(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT))), Integer.parseInt(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU))), Integer.parseInt(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM)))); // write state query file so shell script can read the vm state info filename = HypervisorCmdSimulator.cleanPath(wdir) + QueryVMSimulator.QUERY_RES_FILE_NAME; FileUtils.writeStringToFile(new File(filename), status.toString(), Charset.forName("UTF-8")); } 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:mcnutty.music.get.MusicGet.java
public static void main(String[] args) throws Exception { //print out music-get System.out.println(" _ _ "); System.out.println(" _ __ ___ _ _ ___(_) ___ __ _ ___| |_ "); System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|"); System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| | __/ |_ "); System.out.println("|_| |_| |_|\\__,_|___/_|\\___| \\__, |\\___|\\__|"); System.out.println(" |___/ \n"); //these will always be initialised later (but the compiler doesn't know that) String directory = ""; Properties prop = new Properties(); try (InputStream input = new FileInputStream("config.properties")) { prop.load(input); if (prop.getProperty("directory") != null) { directory = prop.getProperty("directory"); } else {// ww w .j av a 2 s. c o m System.out.println( "Error reading config property 'directory' - using default value of /tmp/musicserver/\n"); directory = "/tmp/musicserver/"; } if (prop.getProperty("password") == null) { System.out.println("Error reading config property 'password' - no default value, exiting\n"); System.exit(1); } } catch (IOException e) { System.out.println("Error reading config file"); System.exit(1); } //create a queue object ProcessQueue process_queue = new ProcessQueue(); try { if (args.length > 0 && args[0].equals("clean")) { Files.delete(Paths.get("queue.json")); } //load an existing queue if possible String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString(); JSONArray queue_state = new JSONArray(raw_queue); ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>(); JSONArray queue = queue_state.getJSONArray(0); for (int i = 0; i < queue.length(); i++) { JSONObject item = ((JSONObject) queue.get(i)); QueueItem loaded_item = new QueueItem(); loaded_item.ip = item.getString("ip"); loaded_item.real_name = item.getString("name"); loaded_item.disk_name = item.getString("guid"); loaded_queue.add(loaded_item); } process_queue.bucket_queue = loaded_queue; System.out.println("Loaded queue from disk\n"); } catch (Exception ex) { //otherwise clean out the music directory and start a new queue try { Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } }); Files.delete(Paths.get(directory)); } catch (Exception e) { e.printStackTrace(); } Files.createDirectory(Paths.get(directory)); System.out.println("Created a new queue\n"); } //start the web server StartServer start_server = new StartServer(process_queue, directory); new Thread(start_server).start(); //wit for the web server to spool up Thread.sleep(1000); //read items from the queue and play them while (true) { QueueItem next_item = process_queue.next_item(); if (!next_item.equals(new QueueItem())) { //Check the timeout int timeout = 547; try (FileInputStream input = new FileInputStream("config.properties")) { prop.load(input); timeout = Integer.parseInt(prop.getProperty("timeout", "547")); } catch (Exception e) { e.printStackTrace(); } System.out.println("Playing " + next_item.real_name); process_queue.set_played(next_item); process_queue.save_queue(); Process p = Runtime.getRuntime().exec("timeout " + timeout + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name); try { p.waitFor(timeout, TimeUnit.SECONDS); Files.delete(Paths.get(directory + next_item.disk_name)); } catch (Exception e) { e.printStackTrace(); } } else { process_queue.bucket_played.clear(); } Thread.sleep(1000); } }
From source file:com.jdom.mediadownloader.MediaDownloader.java
public static void main(String[] args) { if (args.length != 1) { throw new IllegalArgumentException( "You must pass the location to the properties file to the application!"); }/*from w w w .ja va 2 s . c o m*/ File file = new File(args[0]); Properties properties = new Properties(); FileReader fileReader = null; try { fileReader = new FileReader(file); properties.load(fileReader); } catch (Exception e) { throw new RuntimeException(e); } finally { Closeables.closeQuietly(fileReader); } System.getProperties().putAll(properties); initializeContext(); MediaDownloader mediaDownloader = ctx.getBean(MediaDownloader.class); mediaDownloader.processDownloads(); }
From source file:com.yahoo.pulsar.admin.cli.PulsarAdminTool.java
public static void main(String[] args) throws Exception { String configFile = args[0];/*from www .j av a 2 s . c o m*/ Properties properties = new Properties(); if (configFile != null) { FileInputStream fis = null; try { fis = new FileInputStream(configFile); properties.load(fis); } finally { if (fis != null) fis.close(); } } PulsarAdminTool tool = new PulsarAdminTool(properties); if (tool.run(Arrays.copyOfRange(args, 1, args.length))) { System.exit(0); } else { System.exit(1); } }