List of usage examples for java.lang Long parseLong
public static long parseLong(String s) throws NumberFormatException
From source file:gov.nasa.jpl.xdata.nba.impoexpo.manager.GameManager.java
/** * @param args/*from w w w . j a v a2 s . c om*/ */ public static void main(String[] args) throws Exception { if (args.length < 2) { System.err.println(USAGE); System.exit(1); } GameManager manager = new GameManager(); if ("-aquire".equals(args[0])) { manager.aquire(args); } else if ("-get".equals(args[0])) { manager.get(Long.parseLong(args[1])); } else if ("-query".equals(args[0])) { if (args.length == 2) manager.query(Long.parseLong(args[1])); else manager.query(Long.parseLong(args[1]), Long.parseLong(args[2])); } else if ("-delete".equals(args[0])) { manager.delete(Long.parseLong(args[1])); } else if ("-deleteByQuery".equalsIgnoreCase(args[0])) { manager.deleteByQuery(Long.parseLong(args[1]), Long.parseLong(args[2])); } else { System.err.println(USAGE); System.exit(1); } manager.close(); }
From source file:com.github.rinde.rinsim.examples.core.taxi.TaxiExample.java
/** * Starts the {@link TaxiExample}.// w w w .j a v a 2 s. c o m * @param args The first option may optionally indicate the end time of the * simulation. */ public static void main(@Nullable String[] args) { final long endTime = args != null && args.length >= 1 ? Long.parseLong(args[0]) : Long.MAX_VALUE; final String graphFile = args != null && args.length >= 2 ? args[1] : MAP_FILE; run(false, endTime, graphFile, null /* new Display() */, null, null); }
From source file:cz.muni.fi.pa165.creatures.rest.client.CreaturesRESTClient.java
public static void main(String[] args) { CommandLineParser parser = new PosixParser(); Options options = OptionsProvider.getInstance().getOptions(); try {//from w ww. j av a 2s . c o m CommandLine line = parser.parse(options, args); if (!CommandLineValidator.validate(line)) { throw new ParseException("Command line arguments are not valid. Please refer the help"); } if (line.hasOption("h")) { CreaturesRESTClient.printHelp(options); System.exit(0); } CRUDService crudService; String operation = line.getOptionValue("o"); String uri; if (line.hasOption("u")) { uri = normalizeURI(line.getOptionValue("u")); } else { uri = DEFAULT_URI; } // weapon mode if (line.hasOption("w")) { crudService = new WeaponCRUDServiceImpl(uri + WEAPON_URI_PART); if (operation.equals("C")) { WeaponDTO dto = (WeaponDTO) DTOBuilder.get(WeaponDTO.class, line); crudService.create(dto); } else if (operation.equals("R")) { Long id = Long.parseLong(line.getOptionValue("i")); crudService.getById(id); } else if (operation.equals("U")) { WeaponDTO dto = (WeaponDTO) DTOBuilder.get(WeaponDTO.class, line); crudService.update(dto); } else if (operation.equals("D")) { Long id = Long.parseLong(line.getOptionValue("i")); crudService.delete(id); } else if (operation.equals("A")) { crudService.getAll(); } else if (operation.equals("N")) { crudService.getCount(); } // region mode } else if (line.hasOption("r")) { crudService = new RegionCRUDServiceImpl(uri + REGION_URI_PART); if (operation.equals("C")) { RegionDTO dto = (RegionDTO) DTOBuilder.get(RegionDTO.class, line); crudService.create(dto); } else if (operation.equals("R")) { Long id = Long.parseLong(line.getOptionValue("i")); crudService.getById(id); } else if (operation.equals("U")) { RegionDTO dto = (RegionDTO) DTOBuilder.get(RegionDTO.class, line); crudService.update(dto); } else if (operation.equals("D")) { Long id = Long.parseLong(line.getOptionValue("i")); crudService.delete(id); } else if (operation.equals("A")) { crudService.getAll(); } else if (operation.equals("N")) { crudService.getCount(); } } } catch (ParseException ex) { CreaturesRESTClient.printHelp(options); System.exit(1); } catch (IllegalArgumentException ex) { System.exit(1); } catch (JAXBException ex) { System.exit(1); } catch (Exception ex) { System.exit(1); } }
From source file:uidmsgshow.java
public static void main(String argv[]) { long uid = -1; int optind;//from www. j a va 2 s . c om for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-f")) { mbox = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println( "Usage: uidmsgshow [-L url] [-T protocol] [-H host] [-U user] [-P password] [-f mailbox] [uid] [-v]"); System.exit(1); } else { break; } } try { if (optind < argv.length) uid = Long.parseLong(argv[optind]); // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); // session.setDebug(true); // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } folder = folder.getFolder(mbox); if (!folder.exists()) { System.out.println(mbox + " does not exist"); System.exit(1); } if (!(folder instanceof UIDFolder)) { System.out.println("This Provider or this folder does not support UIDs"); System.exit(1); } UIDFolder ufolder = (UIDFolder) folder; folder.open(Folder.READ_WRITE); int totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("-------------------------------"); } if (uid == -1) { // Attributes & Flags for ALL messages .. Message[] msgs = ufolder.getMessagesByUID(1, UIDFolder.LASTUID); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE UID #" + ufolder.getUID(msgs[i]) + ":"); dumpEnvelope(msgs[i]); // dumpPart(msgs[i]); } } else { System.out.println("Getting message UID: " + uid); Message m = ufolder.getMessageByUID(uid); if (m != null) dumpPart(m); else System.out.println("This Message does not exist on this folder"); } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); } System.exit(1); }
From source file:cloudworker.RemoteWorker.java
public static void main(String[] args) throws Exception { //Command interpreter CommandLineInterface cmd = new CommandLineInterface(args); final int poolSize = Integer.parseInt(cmd.getOptionValue("s")); long idle_time = Long.parseLong(cmd.getOptionValue("i")); //idle time = 60 sec init();/*from ww w . j a va2 s .co m*/ System.out.println("Initialized one remote worker.\n"); //Create thread pool ExecutorService threadPool = Executors.newFixedThreadPool(poolSize); BlockingExecutor blockingPool = new BlockingExecutor(threadPool, poolSize); //Get queue url GetQueueUrlResult urlResult = sqs.getQueueUrl("JobQueue"); String jobQueueUrl = urlResult.getQueueUrl(); // Receive messages //System.out.println("Receiving messages from JobQueue.\n"); //...Check idle state boolean terminate = false; boolean startClock = true; long start_time = 0, end_time; JSONParser parser = new JSONParser(); Runtime runtime = Runtime.getRuntime(); String task_id = null; boolean runAnimoto = false; while (!terminate || idle_time == 0) { while (getQueueSize(sqs, jobQueueUrl) > 0) { //Batch retrieving messages ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest().withQueueUrl(jobQueueUrl) .withMaxNumberOfMessages(10); List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages(); for (Message message : messages) { //System.out.println(" Message"); // System.out.println(" MessageId: " + message.getMessageId()); // System.out.println(" ReceiptHandle: " + message.getReceiptHandle()); // System.out.println(" MD5OfBody: " + message.getMD5OfBody()); //System.out.println(" Body: " + message.getBody()); //Get task String messageBody = message.getBody(); JSONObject json = (JSONObject) parser.parse(messageBody); task_id = json.get("task_id").toString(); String task = json.get("task").toString(); try { //Check duplicate task dynamoDB.addTask(task_id, task); //Execute task, will be blocked if no more thread is currently available blockingPool.submitTask(new Animoto(task_id, task, sqs)); // Delete the message String messageRecieptHandle = message.getReceiptHandle(); sqs.deleteMessage(new DeleteMessageRequest(jobQueueUrl, messageRecieptHandle)); } catch (ConditionalCheckFailedException ccf) { //DO something... } } startClock = true; } //Start clock to measure idle time if (startClock) { startClock = false; start_time = System.currentTimeMillis(); } else { end_time = System.currentTimeMillis(); long elapsed_time = (end_time - start_time) / 1000; if (elapsed_time > idle_time) { terminate = true; } } } //System.out.println(); threadPool.shutdown(); // Wait until all threads are finished while (!threadPool.isTerminated()) { } //Terminate running instance cleanUpInstance(); }
From source file:com.muni.fi.pa165.survive.rest.client.SurviveRESTClient.java
public static void main(String[] args) { File file = new File("err.txt"); FileOutputStream fos = null;//from w w w . java2s .co m try { fos = new FileOutputStream(file); } catch (FileNotFoundException ex) { Logger.getLogger(SurviveRESTClient.class.getName()).log(Level.SEVERE, null, ex); } PrintStream ps = new PrintStream(fos); System.setErr(ps); CommandLineParser parser = new PosixParser(); Options options = OptionsProvider.getInstance().getOptions(); try { CommandLine line = parser.parse(options, args); List<String> validate = CommandLineValidator.validate(line); if (!validate.isEmpty()) { System.out.println("The following errors occured when parsing the command:"); for (String string : validate) { System.out.println(string); } System.out.println(""); printHelp(options); System.exit(1); } if (line.hasOption("h")) { printHelp(options); System.exit(0); } CustomRestService crudService; String operation = line.getOptionValue("o"); // weapon mode if (line.hasOption("w")) { crudService = new WeaponServiceImpl(); switch (operation) { case "C": { WeaponDto dto = DtoBuilder.getWeaponDto(line); Object byId = crudService.create(dto); printEntity(crudService.getResponse(), "Creating a weapon", byId); break; } case "R": { Long id = Long.parseLong(line.getOptionValue("i")); Object byId = crudService.getById(id); printEntity(crudService.getResponse(), "Reading a weapon with id " + id, byId); break; } case "U": { WeaponDto dto = DtoBuilder.getWeaponDto(line); Object byId = crudService.update(dto); printEntity(crudService.getResponse(), "Updating a weapon with id " + line.getOptionValue("i"), byId); break; } case "D": { Long id = Long.parseLong(line.getOptionValue("i")); Response delete = crudService.delete(id); printEntity(crudService.getResponse(), "Deleting a weapon with id " + line.getOptionValue("i"), crudService.getResponse().getStatusInfo()); break; } case "A": List<AbstractDto> all = crudService.getAll(); printEntities(crudService.getResponse(), "Reading all weapons", all); break; } } else if (line.hasOption("a")) { crudService = new AreaServiceImpl(); switch (operation) { case "C": { AreaDto dto = DtoBuilder.getAreaDto(line); Object byId = crudService.create(dto); printEntity(crudService.getResponse(), "Creating an area", byId); break; } case "R": { Long id = Long.parseLong(line.getOptionValue("i")); Object byId = crudService.getById(id); printEntity(crudService.getResponse(), "Reading an area with id " + id, byId); break; } case "U": { AreaDto dto = DtoBuilder.getAreaDto(line); Object byId = crudService.update(dto); printEntity(crudService.getResponse(), "Updating an area with id " + line.getOptionValue("i"), byId); break; } case "D": { Long id = Long.parseLong(line.getOptionValue("i")); Object byId = crudService.delete(id); printEntity(crudService.getResponse(), "Deleting an area with id " + line.getOptionValue("i"), crudService.getResponse().getStatusInfo()); break; } case "A": List<AbstractDto> all = crudService.getAll(); printEntities(crudService.getResponse(), "Reading all areas", all); break; } } else { printHelp(options); } } catch (ParseException ex) { System.out.println(ex.getMessage()); printHelp(options); System.exit(1); } catch (NumberFormatException ex) { System.out.println(ex.getMessage()); printHelp(options); System.exit(2); } catch (MessageBodyProviderNotFoundException ex) { System.out.println("Couldn't connect to the server! Please make sure that the server side is running."); System.exit(3); } catch (ProcessingException ex) { System.out.println("Couldn't connect to the server! Please make sure that the server side is running."); System.exit(4); } catch (Exception ex) { System.out.println( "There was an error when connecting to the server. Please make sure that the server side is running."); } }
From source file:com.nextdoor.bender.S3SnsNotifier.java
public static void main(String[] args) throws ParseException, InterruptedException, IOException { formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZoneUTC(); /*//w ww . j ava 2s. co m * Parse cli arguments */ Options options = new Options(); options.addOption(Option.builder().longOpt("bucket").hasArg().required() .desc("Name of S3 bucket to list s3 objects from").build()); options.addOption(Option.builder().longOpt("key-file").hasArg().required() .desc("Local file of S3 keys to process").build()); options.addOption( Option.builder().longOpt("sns-arn").hasArg().required().desc("SNS arn to publish to").build()); options.addOption(Option.builder().longOpt("throttle-ms").hasArg() .desc("Amount of ms to wait between publishing to SNS").build()); options.addOption(Option.builder().longOpt("processed-file").hasArg() .desc("Local file to use to store procssed S3 object names").build()); options.addOption(Option.builder().longOpt("skip-processed").hasArg(false) .desc("Whether to skip S3 objects that have been processed").build()); options.addOption( Option.builder().longOpt("dry-run").hasArg(false).desc("If set do not publish to SNS").build()); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); String bucket = cmd.getOptionValue("bucket"); String keyFile = cmd.getOptionValue("key-file"); String snsArn = cmd.getOptionValue("sns-arn"); String processedFile = cmd.getOptionValue("processed-file", null); boolean skipProcessed = cmd.hasOption("skip-processed"); dryRun = cmd.hasOption("dry-run"); long throttle = Long.parseLong(cmd.getOptionValue("throttle-ms", "-1")); if (processedFile != null) { File file = new File(processedFile); if (!file.exists()) { logger.debug("creating local file to store processed s3 object names: " + processedFile); file.createNewFile(); } } /* * Import S3 keys that have been processed */ if (skipProcessed && processedFile != null) { try (BufferedReader br = new BufferedReader(new FileReader(processedFile))) { String line; while ((line = br.readLine()) != null) { alreadyPublished.add(line.trim()); } } } /* * Setup writer for file containing processed S3 keys */ FileWriter fw = null; BufferedWriter bw = null; if (processedFile != null) { fw = new FileWriter(processedFile, true); bw = new BufferedWriter(fw); } /* * Create clients */ AmazonS3Client s3Client = new AmazonS3Client(); AmazonSNSClient snsClient = new AmazonSNSClient(); /* * Get S3 object list */ try (BufferedReader br = new BufferedReader(new FileReader(keyFile))) { String line; while ((line = br.readLine()) != null) { String key = line.trim(); if (alreadyPublished.contains(key)) { logger.info("skipping " + key); } ObjectMetadata om = s3Client.getObjectMetadata(bucket, key); S3EventNotification s3Notification = getS3Notification(key, bucket, om.getContentLength()); String json = s3Notification.toJson(); /* * Publish to SNS */ if (publish(snsArn, json, snsClient, key) && processedFile != null) { bw.write(key + "\n"); bw.flush(); } if (throttle != -1) { Thread.sleep(throttle); } } } if (processedFile != null) { bw.close(); fw.close(); } }
From source file:SDRecord.java
public static void main(String[] args) { boolean recordToInf = false; long recordTo = 0, txsize = 0, wr = 0, max = 0; int sourcePort = 0, destPort = 0; String val; OutputStream writer = null;/*from w w w.j a v a2 s. co m*/ InetAddress rhost = null, lhost = null; DatagramSocket socket = null; //Default values int buffSize = 1500; try { lhost = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException e1) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } recordToInf = true; sourcePort = 7355; Options options = new Options(); options.addOption("m", true, "Minutes to record, default is no limit"); options.addOption("l", true, "Bind to a specific local address, default is 0.0.0.0"); options.addOption("p", true, "Local port to use, default is 7355"); options.addOption("r", true, "Remote address where to send data"); options.addOption("d", true, "Remote port, to use with -r option"); options.addOption("f", true, "Output file where to save the recording"); options.addOption("s", true, "Stop recording when reaching specified MBs"); options.addOption("h", false, "Help"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e1) { System.err.println("ERROR!: Error while parsing the command line"); System.exit(1); } if (cmd.hasOption("m")) { val = cmd.getOptionValue("m"); try { if (Long.parseLong(val) < 0) { System.err.println("ERROR!: -m argument value cannot be negative"); System.exit(3); } recordTo = System.currentTimeMillis() + (Long.parseLong(val) * 60000); recordToInf = false; } catch (NumberFormatException e) { System.err.println("ERROR!: -m argument not an integer"); System.exit(3); } } if (cmd.hasOption("l")) { val = cmd.getOptionValue("l"); try { lhost = InetAddress.getByName(val); } catch (UnknownHostException e) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } } if (cmd.hasOption("p")) { val = cmd.getOptionValue("p"); try { sourcePort = Integer.parseInt(val); } catch (NumberFormatException e) { System.err.println("ERROR!: -p argument not an integer"); System.exit(3); } } if (cmd.hasOption("r")) { val = cmd.getOptionValue("r"); try { rhost = InetAddress.getByName(val); } catch (UnknownHostException e) { System.err.println("ERROR!: Host not reconized"); System.exit(3); } } if (cmd.hasOption("d")) { val = cmd.getOptionValue("d"); try { destPort = Integer.parseInt(val); } catch (NumberFormatException e) { System.err.println("-ERROR!: -d argument not an integer"); System.exit(3); } } if (cmd.hasOption("f")) { val = cmd.getOptionValue("f"); try { writer = new FileOutputStream(val); } catch (FileNotFoundException e) { System.err.println("ERROR!: File not found"); System.exit(3); } } if (cmd.hasOption("s")) { val = cmd.getOptionValue("s"); try { max = (long) (Double.parseDouble(val) * 1000000); } catch (NumberFormatException e) { System.err.println("ERROR!: -s argument not valid"); System.exit(3); } if (Double.parseDouble(val) < 0) { System.err.println("ERROR!: -s argument value cannot be negative"); System.exit(3); } } if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("SDRecord", options); System.exit(0); } try { socket = new DatagramSocket(sourcePort, lhost); //socket options socket.setReuseAddress(true); } catch (SocketException e) { e.printStackTrace(); System.exit(3); } byte[] buffer = new byte[buffSize]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); System.err.println("Listening " + lhost.toString() + " on port " + sourcePort); while (recordToInf == true || System.currentTimeMillis() <= recordTo) { //Stop recording when reaching max bytes if (max != 0 && txsize >= max) break; packet.setData(buffer); try { socket.receive(packet); } catch (IOException e) { e.printStackTrace(); System.exit(4); } //Ignoring packets with no data if (basicFilter(packet) == null) continue; if (writer == null && rhost == null) wr = recordToStdout(packet); if (writer != null) wr = recordToFile(packet, writer); if (rhost != null) wr = recordToSocket(packet, socket, rhost, destPort); txsize += wr; System.err .print("\r" + formatSize(txsize) + " transferred" + "\033[K" + "\t Press Ctrl+c to terminate"); } //closing socket and exit System.err.print("\r" + formatSize(txsize) + " transferred" + "\033[K"); socket.close(); System.out.println(); System.exit(0); }
From source file:io.hops.metadata.util.DistributedRTClientEvaluation.java
public static void main(String[] args) throws IOException, YarnException, InterruptedException { LOG.info("version 2.0"); if (args.length == 0) { //TODO display help return;//from w ww. java 2s.c o m } if (args[0].equals("run")) { String rtAddress = args[1]; int nbSimulatedNM = Integer.parseInt(args[2]); int hbPeriod = Integer.parseInt(args[3]); long duration = Long.parseLong(args[4]); int startingPort = Integer.parseInt(args[5]); int nbNMTotal = Integer.parseInt(args[6]); String output = args[7]; DistributedRTClientEvaluation client = new DistributedRTClientEvaluation(rtAddress, nbSimulatedNM, hbPeriod, duration, output, startingPort, nbNMTotal); } }
From source file:io.s4.MainApp.java
public static void main(String args[]) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c")); options.addOption(/*from ww w .ja v a 2 s .c o m*/ OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a")); options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d")); options.addOption(OptionBuilder.withArgName("seedtime").hasArg() .withDescription("event clock initialization time").create("s")); options.addOption( OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e")); options.addOption( OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i")); options.addOption( OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t")); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; String clockType = "wall"; try { commandLine = parser.parse(options, args); } catch (ParseException pe) { System.err.println(pe.getLocalizedMessage()); System.exit(1); } int instanceId = -1; if (commandLine.hasOption("i")) { String instanceIdStr = commandLine.getOptionValue("i"); try { instanceId = Integer.parseInt(instanceIdStr); } catch (NumberFormatException nfe) { System.err.println("Bad instance id: %s" + instanceIdStr); System.exit(1); } } if (commandLine.hasOption("c")) { coreHome = commandLine.getOptionValue("c"); } if (commandLine.hasOption("a")) { appsHome = commandLine.getOptionValue("a"); } if (commandLine.hasOption("d")) { clockType = commandLine.getOptionValue("d"); } if (commandLine.hasOption("e")) { extsHome = commandLine.getOptionValue("e"); } String configType = "typical"; if (commandLine.hasOption("t")) { configType = commandLine.getOptionValue("t"); } long seedTime = 0; if (commandLine.hasOption("s")) { seedTime = Long.parseLong(commandLine.getOptionValue("s")); } File coreHomeFile = new File(coreHome); if (!coreHomeFile.isDirectory()) { System.err.println("Bad core home: " + coreHome); System.exit(1); } File appsHomeFile = new File(appsHome); if (!appsHomeFile.isDirectory()) { System.err.println("Bad applications home: " + appsHome); System.exit(1); } if (instanceId > -1) { System.setProperty("instanceId", "" + instanceId); } else { System.setProperty("instanceId", "" + S4Util.getPID()); } List loArgs = commandLine.getArgList(); if (loArgs.size() < 1) { // System.err.println("No bean configuration file specified"); // System.exit(1); } // String s4ConfigXml = (String) loArgs.get(0); // System.out.println("s4ConfigXml is " + s4ConfigXml); ClassPathResource propResource = new ClassPathResource("s4-core.properties"); Properties prop = new Properties(); if (propResource.exists()) { prop.load(propResource.getInputStream()); } else { System.err.println("Unable to find s4-core.properties. It must be available in classpath"); System.exit(1); } ApplicationContext coreContext = null; String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType; String configPath = ""; List<String> coreConfigUrls = new ArrayList<String>(); File configFile = null; // load clock configuration configPath = configBase + File.separatorChar + clockType + "-clock.xml"; coreConfigUrls.add(configPath); // load core config xml configPath = configBase + File.separatorChar + "s4-core-conf.xml"; configFile = new File(configPath); if (!configFile.exists()) { System.err.printf("S4 core config file %s does not exist\n", configPath); System.exit(1); } coreConfigUrls.add(configPath); String[] coreConfigFiles = new String[coreConfigUrls.size()]; coreConfigUrls.toArray(coreConfigFiles); String[] coreConfigFileUrls = new String[coreConfigFiles.length]; for (int i = 0; i < coreConfigFiles.length; i++) { coreConfigFileUrls[i] = "file:" + coreConfigFiles[i]; } coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext); ApplicationContext context = coreContext; Clock s4Clock = (Clock) context.getBean("clock"); if (s4Clock instanceof EventClock && seedTime > 0) { EventClock s4EventClock = (EventClock) s4Clock; s4EventClock.updateTime(seedTime); System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime()); } PEContainer peContainer = (PEContainer) context.getBean("peContainer"); Watcher w = (Watcher) context.getBean("watcher"); w.setConfigFilename(configPath); // load extension modules String[] configFileNames = getModuleConfigFiles(extsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); } // load application modules configFileNames = getModuleConfigFiles(appsHome, prop); if (configFileNames.length > 0) { String[] configFileUrls = new String[configFileNames.length]; for (int i = 0; i < configFileNames.length; i++) { configFileUrls[i] = "file:" + configFileNames[i]; } context = new FileSystemXmlApplicationContext(configFileUrls, context); // attach any beans that implement ProcessingElement to the PE // Container String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class); for (String processingElementBeanName : processingElementBeanNames) { Object bean = context.getBean(processingElementBeanName); try { Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock"); if (getS4ClockMethod.getReturnType().equals(Clock.class)) { if (getS4ClockMethod.invoke(bean) == null) { Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class); setS4ClockMethod.invoke(bean, coreContext.getBean("clock")); } } } catch (NoSuchMethodException mnfe) { // acceptable } System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id " + ((ProcessingElement) bean).getId()); peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName); } } }