List of usage examples for java.util Properties getProperty
public String getProperty(String key)
From source file:uk.co.moonsit.rmi.GraphClient.java
@SuppressWarnings("SleepWhileInLoop") public static void main(String args[]) { Properties p = new Properties(); try {/*from w w w . ja v a2s . co 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:com.baidu.rigel.biplatform.ma.file.serv.FileServer.java
/** * /* w w w .j a v a 2s . co m*/ * ???server * * @param args */ public static void main(String[] args) throws Exception { // if (args.length != 1) { // LOGGER.error("can not get enough parameters for starting file server"); // printUsage(); // System.exit(-1); // } FileInputStream fis = null; String classLocation = FileServer.class.getProtectionDomain().getCodeSource().getLocation().toString(); final File configFile = new File(classLocation + "/../conf/fileserver.conf"); Properties properties = new Properties(); try { if (configFile.exists()) { fis = new FileInputStream(configFile); } else if (StringUtils.isNotEmpty(args[0])) { fis = new FileInputStream(args[0]); } else { printUsage(); throw new RuntimeException("can't find correct file server configuration file!"); } properties.load(fis); } finally { if (fis != null) { fis.close(); } } int port = -1; try { port = Integer.valueOf(properties.getProperty(PORT_NUM_KEY)); } catch (NumberFormatException e) { LOGGER.error("parameter is not correct, [port = {}]", args[0]); System.exit(-1); } String location = properties.getProperty(ROOT_DIR_KEY); if (StringUtils.isEmpty(location)) { LOGGER.error("the location can not be empty"); System.exit(-1); } File f = new File(location); if (!f.exists() && !f.mkdirs()) { LOGGER.error("invalidation location [{}] please verify the input", args[1]); System.exit(-1); } startServer(location, port); }
From source file:com.entertailion.java.caster.Main.java
/** * @param args/*from w ww . ja v a 2s . c o m*/ */ public static void main(String[] args) { // http://commons.apache.org/proper/commons-cli/usage.html Option help = new Option("h", "help", false, "Print this help message"); Option version = new Option("V", "version", false, "Print version information"); Option list = new Option("l", "list", false, "List ChromeCast devices"); Option verbose = new Option("v", "verbose", false, "Verbose debug logging"); Option transcode = new Option("t", "transcode", false, "Transcode media; -f also required"); Option rest = new Option("r", "rest", false, "REST API server"); Option url = OptionBuilder.withLongOpt("stream").hasArg().withValueSeparator() .withDescription("HTTP URL for streaming content; -d also required").create("s"); Option server = OptionBuilder.withLongOpt("device").hasArg().withValueSeparator() .withDescription("ChromeCast device IP address").create("d"); Option id = OptionBuilder.withLongOpt("app-id").hasArg().withValueSeparator() .withDescription("App ID for whitelisted device").create("id"); Option mediaFile = OptionBuilder.withLongOpt("file").hasArg().withValueSeparator() .withDescription("Local media file; -d also required").create("f"); Option transcodingParameters = OptionBuilder.withLongOpt("transcode-parameters").hasArg() .withValueSeparator().withDescription("Transcode parameters; -t also required").create("tp"); Option restPort = OptionBuilder.withLongOpt("rest-port").hasArg().withValueSeparator() .withDescription("REST API port; default 8080").create("rp"); Options options = new Options(); options.addOption(help); options.addOption(version); options.addOption(list); options.addOption(verbose); options.addOption(url); options.addOption(server); options.addOption(id); options.addOption(mediaFile); options.addOption(transcode); options.addOption(transcodingParameters); options.addOption(rest); options.addOption(restPort); // create the command line parser CommandLineParser parser = new PosixParser(); //String[] arguments = new String[] { "-vr" }; try { // parse the command line arguments CommandLine line = parser.parse(options, args); Option[] lineOptions = line.getOptions(); if (lineOptions.length == 0) { System.out.println("caster: try 'java -jar caster.jar -h' for more information"); System.exit(0); } Log.setVerbose(line.hasOption("v")); // Custom app-id if (line.hasOption("id")) { Log.d(LOG_TAG, line.getOptionValue("id")); appId = line.getOptionValue("id"); } // Print version if (line.hasOption("V")) { System.out.println("Caster version " + VERSION); } // List ChromeCast devices if (line.hasOption("l")) { final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() { @Override public void discoveringDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveringDevices"); } @Override public void discoveredDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveredDevices"); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { System.out.println(dialServer.toString()); // keep system for output } } }); deviceFinder.discoverDevices(); } // Stream media from internet if (line.hasOption("s") && line.hasOption("d")) { Log.d(LOG_TAG, line.getOptionValue("d")); Log.d(LOG_TAG, line.getOptionValue("s")); try { Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(line.getOptionValue("d"))), new PlaybackListener() { private int time; private int duration; private int state; @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); // Stop the app if the video reaches the end if (time > 0 && time == duration && state == 0) { playback.doStop(); System.exit(0); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } }); playback.stream(line.getOptionValue("s")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // Play local media file if (line.hasOption("f") && line.hasOption("d")) { Log.d(LOG_TAG, line.getOptionValue("d")); Log.d(LOG_TAG, line.getOptionValue("f")); final String file = line.getOptionValue("f"); String device = line.getOptionValue("d"); try { Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(device)), new PlaybackListener() { private int time; private int duration; private int state; @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); // Stop the app if the video reaches the end if (time > 0 && time == duration && state == 0) { playback.doStop(); System.exit(0); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } }); if (line.hasOption("t") && line.hasOption("tp")) { playback.setTranscodingParameters(line.getOptionValue("tp")); } playback.play(file, line.hasOption("t")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // REST API server if (line.hasOption("r")) { final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() { @Override public void discoveringDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveringDevices"); } @Override public void discoveredDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveredDevices"); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { Log.d(LOG_TAG, dialServer.toString()); } } }); deviceFinder.discoverDevices(); int port = 0; if (line.hasOption("rp")) { try { port = Integer.parseInt(line.getOptionValue("rp")); } catch (NumberFormatException e) { Log.e(LOG_TAG, "invalid rest port", e); } } Playback.startWebserver(port, new WebListener() { String[] prefixes = { "/playback", "/devices" }; HashMap<String, Playback> playbackMap = new HashMap<String, Playback>(); HashMap<String, RestPlaybackListener> playbackListenerMap = new HashMap<String, RestPlaybackListener>(); final class RestPlaybackListener implements PlaybackListener { private String device; private int time; private int duration; private int state; public RestPlaybackListener(String device) { this.device = device; } @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); this.state = state; // Stop the app if the video reaches the end if (this.time > 0 && this.time == this.duration && state == 0) { playback.doStop(); playbackMap.remove(device); playbackListenerMap.remove(device); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } } @Override public Response handleRequest(String uri, String method, Properties header, Properties parms) { Log.d(LOG_TAG, "handleRequest: " + uri); if (method.equals("GET")) { if (uri.startsWith(prefixes[0])) { // playback String device = parms.getProperty("device"); if (device != null) { RestPlaybackListener playbackListener = playbackListenerMap.get(device); if (playbackListener != null) { // https://code.google.com/p/json-simple/wiki/EncodingExamples JSONObject obj = new JSONObject(); obj.put("time", playbackListener.getTime()); obj.put("duration", playbackListener.getDuration()); switch (playbackListener.getState()) { case 0: obj.put("state", "idle"); break; case 1: obj.put("state", "stopped"); break; case 2: obj.put("state", "playing"); break; default: obj.put("state", "idle"); break; } return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString()); } else { // Nothing is playing JSONObject obj = new JSONObject(); obj.put("time", 0); obj.put("duration", 0); obj.put("state", "stopped"); return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString()); } } } else if (uri.startsWith(prefixes[1])) { // devices // https://code.google.com/p/json-simple/wiki/EncodingExamples JSONArray list = new JSONArray(); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { JSONObject obj = new JSONObject(); obj.put("name", dialServer.getFriendlyName()); obj.put("ip_address", dialServer.getIpAddress().getHostAddress()); list.add(obj); } return new Response(HttpServer.HTTP_OK, "text/plain", list.toJSONString()); } } else if (method.equals("POST")) { if (uri.startsWith(prefixes[0])) { // playback String device = parms.getProperty("device"); if (device != null) { String stream = parms.getProperty("stream"); String file = parms.getProperty("file"); String state = parms.getProperty("state"); String transcode = parms.getProperty("transcode"); String transcodeParameters = parms.getProperty("transcode-parameters"); Log.d(LOG_TAG, "transcodeParameters=" + transcodeParameters); if (stream != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (playback != null) { playback.stream(stream); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } else if (file != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (transcodeParameters != null) { playback.setTranscodingParameters(transcodeParameters); } if (playback != null) { playback.play(file, transcode != null); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } else if (state != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (playback != null) { // Handle case where current app wasn't started with caster playback.setDialServer(deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device))); // Change the playback state if (state.equals("play")) { playback.doPlay(); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else if (state.equals("pause")) { playback.doPause(); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else if (state.equals("stop")) { playback.doStop(); playbackMap.remove(device); playbackListenerMap.remove(device); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else { Log.e(LOG_TAG, "playback invalid state: " + state); } } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } } } } return new Response(HttpServer.HTTP_BADREQUEST, "text/plain", "Bad Request"); } @Override public String[] uriPrefixes() { return prefixes; } }); Log.d(LOG_TAG, "REST server ready"); // Run forever... while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } // Print help if (line.hasOption("h")) { printHelp(options); } } catch (ParseException exp) { System.out.println("ERROR: " + exp.getMessage()); System.out.println(); printHelp(options); } }
From source file:com.google.oacurl.Fetch.java
public static void main(String[] args) throws Exception { FetchOptions options = new FetchOptions(); CommandLine line = options.parse(args); args = line.getArgs();/* www . j av a 2 s . c o m*/ if (options.isHelp()) { new HelpFormatter().printHelp("url", options.getOptions()); System.exit(0); } if (args.length != 1) { new HelpFormatter().printHelp("url", options.getOptions()); System.exit(-1); } if (options.isInsecure()) { SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); } LoggingConfig.init(options.isVerbose()); if (options.isVerbose()) { LoggingConfig.enableWireLog(); } String url = args[0]; ServiceProviderDao serviceProviderDao = new ServiceProviderDao(); ConsumerDao consumerDao = new ConsumerDao(); AccessorDao accessorDao = new AccessorDao(); Properties loginProperties = null; try { loginProperties = new PropertiesProvider(options.getLoginFileName()).get(); } catch (FileNotFoundException e) { System.err.println(".oacurl.properties file not found in homedir"); System.err.println("Make sure you've run oacurl-login first!"); System.exit(-1); } OAuthServiceProvider serviceProvider = serviceProviderDao.nullServiceProvider(); OAuthConsumer consumer = consumerDao.loadConsumer(loginProperties, serviceProvider); OAuthAccessor accessor = accessorDao.loadAccessor(loginProperties, consumer); OAuthClient client = new OAuthClient(new HttpClient4(SingleClient.HTTP_CLIENT_POOL)); OAuthVersion version = (loginProperties.containsKey("oauthVersion")) ? OAuthVersion.valueOf(loginProperties.getProperty("oauthVersion")) : OAuthVersion.V1; OAuthEngine engine; switch (version) { case V1: engine = new V1OAuthEngine(); break; case V2: engine = new V2OAuthEngine(); break; case WRAP: engine = new WrapOAuthEngine(); break; default: throw new IllegalArgumentException("Unknown version: " + version); } try { OAuthMessage request; List<Entry<String, String>> related = options.getRelated(); Method method = options.getMethod(); if (method == Method.POST || method == Method.PUT) { InputStream bodyStream; if (related != null) { bodyStream = new MultipartRelatedInputStream(related); } else if (options.getFile() != null) { bodyStream = new FileInputStream(options.getFile()); } else { bodyStream = System.in; } request = newRequestMessage(accessor, method, url, bodyStream, engine); request.getHeaders().add(new OAuth.Parameter("Content-Type", options.getContentType())); } else { request = newRequestMessage(accessor, method, url, null, engine); } List<Parameter> headers = options.getHeaders(); addHeadersToRequest(request, headers); HttpResponseMessage httpResponse; if (version == OAuthVersion.V1) { OAuthResponseMessage response; response = client.access(request, ParameterStyle.AUTHORIZATION_HEADER); httpResponse = response.getHttpResponse(); } else { HttpMessage httpRequest = new HttpMessage(request.method, new URL(request.URL), request.getBodyAsStream()); httpRequest.headers.addAll(request.getHeaders()); httpResponse = client.getHttpClient().execute(httpRequest, client.getHttpParameters()); httpResponse = HttpMessageDecoder.decode(httpResponse); } System.err.flush(); if (options.isInclude()) { Map<String, Object> dump = new HashMap<String, Object>(); httpResponse.dump(dump); System.out.print(dump.get(HttpMessage.RESPONSE)); } // Dump the bytes in the response's encoding. InputStream bodyStream = httpResponse.getBody(); byte[] buf = new byte[1024]; int count; while ((count = bodyStream.read(buf)) > -1) { System.out.write(buf, 0, count); } } catch (OAuthProblemException e) { OAuthUtil.printOAuthProblemException(e); } }
From source file:org.objectrepository.MessageConsumerDaemon.java
/** * main//from w w w. ja v a 2 s . co m * <p/> * Accepts one folder as argument: -messageQueues * That folder ought to contain one or more folders ( or symbolic links ) to the files * The folder has the format: [foldername] or [foldername].[maxTasks] * MaxTasks is to indicate the total number of jobs being able to run. * * long * * @param argv */ public static void main(String[] argv) { if (instance == null) { final Properties properties = new Properties(); if (argv.length > 0) { for (int i = 0; i < argv.length; i += 2) { try { properties.put(argv[i], argv[i + 1]); } catch (ArrayIndexOutOfBoundsException arr) { System.out.println("Missing value after parameter " + argv[i]); System.exit(-1); } } } else { log.fatal("Usage: pmq-agent.jar -messageQueues [queues] -heartbeatInterval [interval in ms]\n" + "The queues is a folder that contains symbolic links to the startup scripts."); System.exit(-1); } if (log.isInfoEnabled()) { log.info("Arguments set: "); for (String key : properties.stringPropertyNames()) { log.info("'" + key + "'='" + properties.getProperty(key) + "'"); } } if (!properties.containsKey("-messageQueues")) { log.fatal("Expected case sensitive parameter: -messageQueues"); System.exit(-1); } final File messageQueues = new File((String) properties.get("-messageQueues")); if (!messageQueues.exists()) { log.fatal("Cannot find folder for messageQueues: " + messageQueues.getAbsolutePath()); System.exit(-1); } if (messageQueues.isFile()) { log.fatal( "-messageQueues should point to a folder, not a file: " + messageQueues.getAbsolutePath()); System.exit(-1); } long heartbeatInterval = 600000; if (properties.containsKey("-heartbeatInterval")) { heartbeatInterval = Long.parseLong((String) properties.get("heartbeatInterval")); } String identifier = null; if (properties.containsKey("-id")) { identifier = (String) properties.get("-id"); } else if (properties.containsKey("-identifier")) { identifier = (String) properties.get("-identifier"); } final File[] files = messageQueues.listFiles(); final String[] scriptNames = (properties.containsKey("-startup")) ? new String[] { properties.getProperty("-startup") } : new String[] { "/startup.sh", "\\startup.bat" }; final List<Queue> queues = new ArrayList<Queue>(); for (File file : files) { final String name = file.getName(); final String[] split = name.split("\\.", 2); final String queueName = split[0]; for (String scriptName : scriptNames) { final String shellScript = file.getAbsolutePath() + scriptName; final int maxTask = (split.length == 1) ? 1 : Integer.parseInt(split[1]); log.info("Candidate mq client for " + queueName + " maxTasks " + maxTask); if (new File(shellScript).exists()) { final Queue queue = new Queue(queueName, shellScript, false); queue.setCorePoolSize(1); queue.setMaxPoolSize(maxTask); queue.setQueueCapacity(1); queues.add(queue); break; } else { log.warn("... skipping, because no startup script found at " + shellScript); } } } if (queues.size() == 0) { log.fatal("No queue folders seen in " + messageQueues.getAbsolutePath()); System.exit(-1); } // Add the system queue queues.add(new Queue("Connection", null, true)); getInstance(queues, identifier, heartbeatInterval).run(); } System.exit(0); }
From source file:com.adobe.aem.demomachine.Updates.java
public static void main(String[] args) { String rootFolder = null;//from w w w . ja v a 2 s . c om // Command line options for this tool Options options = new Options(); options.addOption("f", true, "Demo Machine root folder"); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("f")) { rootFolder = cmd.getOptionValue("f"); } } catch (Exception e) { System.exit(-1); } Properties md5properties = new Properties(); try { URL url = new URL( "https://raw.githubusercontent.com/Adobe-Marketing-Cloud/aem-demo-machine/master/conf/checksums.properties"); InputStream in = url.openStream(); Reader reader = new InputStreamReader(in, "UTF-8"); md5properties.load(reader); reader.close(); } catch (Exception e) { System.out.println("Error: Cannot connect to GitHub.com to check for updates"); System.exit(-1); } System.out.println(AemDemoConstants.HR); int nbUpdateAvailable = 0; List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths); for (String[] path : listPaths) { if (path.length == 5) { logger.debug(path[1]); File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : "")); if (pathFolder.exists()) { String newMd5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]), false); logger.debug("MD5 is: " + newMd5); String oldMd5 = md5properties.getProperty("demo.md5." + path[0]); if (oldMd5 == null || oldMd5.length() == 0) { logger.error("Cannot find MD5 for " + path[0]); System.out.println(path[2] + " : Cannot find M5 checksum"); continue; } if (newMd5.equals(oldMd5)) { continue; } else { System.out.println(path[2] + " : New update available" + (path[0].equals("0") ? " (use 'git pull' to get the latest changes)" : "")); nbUpdateAvailable++; } } else { System.out.println(path[2] + " : Not installed"); } } } if (nbUpdateAvailable == 0) { System.out.println("Your AEM Demo Machine is up to date!"); } System.out.println(AemDemoConstants.HR); }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java
public static void main(String[] args) { List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); String oldMSKey = null;//from w w w. j av a 2 s .c om String oldDBKey = null; String newMSKey = null; String newDBKey = null; //Parse command-line args while (iter.hasNext()) { String arg = iter.next(); // Old MS Key if (arg.equals("-m")) { oldMSKey = iter.next(); } // Old DB Key if (arg.equals("-d")) { oldDBKey = iter.next(); } // New MS Key if (arg.equals("-n")) { newMSKey = iter.next(); } // New DB Key if (arg.equals("-e")) { newDBKey = iter.next(); } } if (oldMSKey == null || oldDBKey == null) { System.out.println("Existing MS secret key or DB secret key is not provided"); usage(); return; } if (newMSKey == null && newDBKey == null) { System.out.println("New MS secret key and DB secret are both not provided"); usage(); return; } final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); final Properties dbProps; EncryptionSecretKeyChanger keyChanger = new EncryptionSecretKeyChanger(); StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); keyChanger.initEncryptor(encryptor, oldMSKey); dbProps = new EncryptableProperties(encryptor); PropertiesConfiguration backupDBProps = null; System.out.println("Parsing db.properties file"); try { dbProps.load(new FileInputStream(dbPropsFile)); backupDBProps = new PropertiesConfiguration(dbPropsFile); } catch (FileNotFoundException e) { System.out.println("db.properties file not found while reading DB secret key" + e.getMessage()); } catch (IOException e) { System.out.println("Error while reading DB secret key from db.properties" + e.getMessage()); } catch (ConfigurationException e) { e.printStackTrace(); } String dbSecretKey = null; try { dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret"); } catch (EncryptionOperationNotPossibleException e) { System.out.println("Failed to decrypt existing DB secret key from db.properties. " + e.getMessage()); return; } if (!oldDBKey.equals(dbSecretKey)) { System.out.println("Incorrect MS Secret Key or DB Secret Key"); return; } System.out.println("Secret key provided matched the key in db.properties"); final String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); if (newMSKey == null) { System.out.println("No change in MS Key. Skipping migrating db.properties"); } else { if (!keyChanger.migrateProperties(dbPropsFile, dbProps, newMSKey, newDBKey)) { System.out.println("Failed to update db.properties"); return; } else { //db.properties updated successfully if (encryptionType.equals("file")) { //update key file with new MS key try { FileWriter fwriter = new FileWriter(keyFile); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(newMSKey); bwriter.close(); } catch (IOException e) { System.out.println("Failed to write new secret to file. Please update the file manually"); } } } } boolean success = false; if (newDBKey == null || newDBKey.equals(oldDBKey)) { System.out.println("No change in DB Secret Key. Skipping Data Migration"); } else { EncryptionSecretKeyChecker.initEncryptorForMigration(oldMSKey); try { success = keyChanger.migrateData(oldDBKey, newDBKey); } catch (Exception e) { System.out.println("Error during data migration"); e.printStackTrace(); success = false; } } if (success) { System.out.println("Successfully updated secret key(s)"); } else { System.out.println("Data Migration failed. Reverting db.properties"); //revert db.properties try { backupDBProps.save(); } catch (ConfigurationException e) { e.printStackTrace(); } if (encryptionType.equals("file")) { //revert secret key in file try { FileWriter fwriter = new FileWriter(keyFile); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(oldMSKey); bwriter.close(); } catch (IOException e) { System.out.println("Failed to revert to old secret to file. Please update the file manually"); } } } }
From source file:Evaluator.PerQueryRelDocs.java
public static void main(String[] args) { if (args.length < 1) { args = new String[1]; args[0] = "/home/procheta/NetBeansProjects/InferrdAp/src/Evaluator/init.properties"; }/* w ww. j a v a 2 s .co m*/ try { Properties prop = new Properties(); prop.load(new FileReader(args[0])); EvaluateAll eval = new EvaluateAll(prop); eval.load(); // eval.computeMeanAp(); // eval.storeRunMeanAp(prop.getProperty("storeMeanAp")); eval.storeRunQid(prop.getProperty("storeMeanAp")); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:eu.planets_project.tb.gui.backing.exp.ExpTypeMigrate.java
public static void main(String args[]) { Properties p = System.getProperties(); ByteArrayOutputStream byos = new ByteArrayOutputStream(); try {/*from w w w. ja va 2 s . c o m*/ p.storeToXML(byos, "Automatically generated for PLANETS Service ", "UTF-8"); String res = byos.toString("UTF-8"); System.out.println(res); } catch (IOException e) { e.printStackTrace(); } // This. List<String> pl = new ArrayList<String>(); for (Object key : p.keySet()) { pl.add((String) key); } Collections.sort(pl); // for (String key : pl) { System.out.println(key + " = " + p.getProperty(key)); } /* * http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ThreadMXBean.html#getCurrentThreadCpuTime() * * http://www.java-forums.org/new-java/5303-how-determine-cpu-usage-using-java.html * */ ThreadMXBean TMB = ManagementFactory.getThreadMXBean(); int mscale = 1000000; long time = 0, time2 = 0; long cput = 0, cput2 = 0; double cpuperc = -1; //Begin loop. for (int i = 0; i < 10; i++) { if (TMB.isThreadCpuTimeSupported()) { if (!TMB.isThreadCpuTimeEnabled()) { TMB.setThreadCpuTimeEnabled(true); } // if(new Date().getTime() * mscale - time > 1000000000) //Reset once per second // { System.out.println("Resetting..."); time = System.currentTimeMillis() * mscale; cput = TMB.getCurrentThreadCpuTime(); // cput = TMB.getCurrentThreadUserTime(); // } } //Do cpu intensive stuff for (int k = 0; k < 10; k++) { for (int j = 0; j < 100000; j++) { double a = Math.pow(i, j); double b = a / j + Math.random(); a = b * Math.random(); b = a * Math.random(); } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } if (TMB.isThreadCpuTimeSupported()) { // if(new Date().getTime() * mscale - time != 0) { cput2 = TMB.getCurrentThreadCpuTime(); System.out.println("cpu: " + (cput2 - cput) / (1000.0 * mscale)); // cput2 = TMB.getCurrentThreadUserTime(); time2 = System.currentTimeMillis() * mscale; System.out.println("time: " + (time2 - time) / (1000.0 * mscale)); cpuperc = 100.0 * (cput2 - cput) / (double) (time2 - time); System.out.println("cpu perc = " + cpuperc); // } } //End Loop } System.out.println("Done."); }
From source file:com.marklogic.client.tutorial.util.Bootstrapper.java
/** * Command-line invocation./*from w w w . j a v a2 s . c om*/ * @param args command-line arguments specifying the configuration and REST server */ public static void main(String[] args) throws ClientProtocolException, IOException, XMLStreamException, FactoryConfigurationError { Properties properties = new Properties(); for (int i = 0; i < args.length; i++) { String name = args[i]; if (name.startsWith("-") && name.length() > 1 && ++i < args.length) { name = name.substring(1); if ("properties".equals(name)) { InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name); if (propsStream == null) throw new IOException("Could not read bootstrapper properties"); Properties props = new Properties(); props.load(propsStream); props.putAll(properties); properties = props; } else { properties.put(name, args[i]); } } else { System.err.println("invalid argument: " + name); System.err.println(getUsage()); System.exit(1); } } String invalid = joinList(listInvalidKeys(properties)); if (invalid != null && invalid.length() > 0) { System.err.println("invalid arguments: " + invalid); System.err.println(getUsage()); System.exit(1); } new Bootstrapper().makeServer(properties); System.out.println("Created " + properties.getProperty("restserver") + " server on " + properties.getProperty("restport") + " port for " + properties.getProperty("restdb") + " database"); }