List of usage examples for java.lang System setProperty
public static String setProperty(String key, String value)
From source file:org.apache.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 w w w .j a v a2 s . co 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 clock = (Clock) context.getBean("clock"); if (clock instanceof EventClock && seedTime > 0) { EventClock s4EventClock = (EventClock) clock; 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(AbstractPE.class); for (String processingElementBeanName : processingElementBeanNames) { AbstractPE bean = (AbstractPE) context.getBean(processingElementBeanName); bean.setClock(clock); try { bean.setSafeKeeper((SafeKeeper) context.getBean("safeKeeper")); } catch (NoSuchBeanDefinitionException ignored) { // no safe keeper = no checkpointing / recovery } // if the application did not specify an id, use the Spring bean name if (bean.getId() == null) { bean.setId(processingElementBeanName); } System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id " + ((AbstractPE) bean).getId()); peContainer.addProcessor((AbstractPE) bean); } } }
From source file:org.apache.s4.adapter.Adapter.java
public static void main(String args[]) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c")); options.addOption(//from w ww.jav a2 s . c o m OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i")); options.addOption( OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t")); options.addOption(OptionBuilder.withArgName("userconfig").hasArg() .withDescription("user-defined legacy data adapter configuration file").create("d")); CommandLineParser parser = new GnuParser(); CommandLine commandLine = null; 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"); } String configType = "typical"; if (commandLine.hasOption("t")) { configType = commandLine.getOptionValue("t"); } String userConfigFilename = null; if (commandLine.hasOption("d")) { userConfigFilename = commandLine.getOptionValue("d"); } File userConfigFile = new File(userConfigFilename); if (!userConfigFile.isFile()) { System.err.println("Bad user configuration file: " + userConfigFilename); System.exit(1); } File coreHomeFile = new File(coreHome); if (!coreHomeFile.isDirectory()) { System.err.println("Bad core home: " + coreHome); System.exit(1); } if (instanceId > -1) { System.setProperty("instanceId", "" + instanceId); } else { System.setProperty("instanceId", "" + S4Util.getPID()); } String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType; String configPath = configBase + File.separatorChar + "adapter-conf.xml"; File configFile = new File(configPath); if (!configFile.exists()) { System.err.printf("adapter config file %s does not exist\n", configPath); System.exit(1); } // load adapter config xml ApplicationContext coreContext; coreContext = new FileSystemXmlApplicationContext("file:" + configPath); ApplicationContext context = coreContext; Adapter adapter = (Adapter) context.getBean("adapter"); ApplicationContext appContext = new FileSystemXmlApplicationContext( new String[] { "file:" + userConfigFilename }, context); Map listenerBeanMap = appContext.getBeansOfType(EventProducer.class); if (listenerBeanMap.size() == 0) { System.err.println("No user-defined listener beans"); System.exit(1); } EventProducer[] eventListeners = new EventProducer[listenerBeanMap.size()]; int index = 0; for (Iterator it = listenerBeanMap.keySet().iterator(); it.hasNext(); index++) { String beanName = (String) it.next(); System.out.println("Adding producer " + beanName); eventListeners[index] = (EventProducer) listenerBeanMap.get(beanName); } adapter.setEventListeners(eventListeners); }
From source file:de.freese.base.swing.mac_os_x.MyApp.java
/** * @param args String[][]//from ww w . ja v a2 s .c o m */ public static void main(final String[] args) { SwingUtilities.invokeLater(new Runnable() { /** * @see java.lang.Runnable#run() */ @Override public void run() { System.setProperty("apple.laf.useScreenMenuBar", "true"); new MyApp().setVisible(true); } }); }
From source file:net.orzo.App.java
/** * *///www . j a v a 2s .c o m public static void main(final String[] args) { final App app = new App(); Logger log = null; CommandLine cmd; try { cmd = app.init(args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "orzo [options] user_script [user_arg1 [user_arg2 [...]]]\n(to generate a template: orzo -t [file path])", app.cliOptions); } else if (cmd.hasOption("v")) { System.out.printf("Orzo.js version %s\n", app.props.get("orzo.version")); } else if (cmd.hasOption("t")) { String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js"); File tplFile = new File(cmd.getOptionValue("t")); FileWriter tplWriter = new FileWriter(tplFile); tplWriter.write(templateSrc); tplWriter.close(); File dtsFile = new File( String.format("%s/orzojs.d.ts", new File(tplFile.getAbsolutePath()).getParent())); FileWriter dtsWriter = new FileWriter(dtsFile); String dtsSrc = new ResourceLoader().getResourceAsString("net/orzo/orzojs.d.ts"); dtsWriter.write(dtsSrc); dtsWriter.close(); } else if (cmd.hasOption("T")) { String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js"); System.out.println(templateSrc); } else { // Logger initialization if (cmd.hasOption("g")) { System.setProperty("logback.configurationFile", cmd.getOptionValue("g")); } else { System.setProperty("logback.configurationFile", "./logback.xml"); } log = LoggerFactory.getLogger(App.class); if (cmd.hasOption("s")) { // Orzo.js as a REST and AMQP service FullServiceConfig conf = new Gson().fromJson(new FileReader(cmd.getOptionValue("s")), FullServiceConfig.class); Injector injector = Guice.createInjector(new CoreModule(conf), new RestServletModule()); HttpServer httpServer = new HttpServer(conf, new JerseyGuiceServletConfig(injector)); app.services.add(httpServer); if (conf.getAmqpResponseConfig() != null) { // response AMQP service must be initialized before receiving one app.services.add(injector.getInstance(AmqpResponseConnection.class)); } if (conf.getAmqpConfig() != null) { app.services.add(injector.getInstance(AmqpConnection.class)); app.services.add(injector.getInstance(AmqpService.class)); } if (conf.getRedisConf() != null) { app.services.add(injector.getInstance(RedisStorage.class)); } Runtime.getRuntime().addShutdownHook(new ShutdownHook(app)); app.startServices(); } else if (cmd.hasOption("d")) { // Demo mode final String scriptId = "demo"; final SourceCode demoScript = SourceCode.fromResource(DEMO_SCRIPT); System.err.printf("Running demo script %s.", demoScript.getName()); CmdConfig conf = new CmdConfig(scriptId, demoScript, null, cmd.getOptionValue("p", null)); TaskManager tm = new TaskManager(conf); tm.startTaskSync(tm.registerTask(scriptId, new String[0])); } else if (cmd.getArgs().length > 0) { // Command line mode File userScriptFile = new File(cmd.getArgs()[0]); String optionalModulesPath = null; String[] inputValues; SourceCode userScript; // custom CommonJS modules path if (cmd.hasOption("m")) { optionalModulesPath = cmd.getOptionValue("m"); } if (cmd.getArgs().length > 0) { inputValues = Arrays.copyOfRange(cmd.getArgs(), 1, cmd.getArgs().length); } else { inputValues = new String[0]; } userScript = SourceCode.fromFile(userScriptFile); CmdConfig conf = new CmdConfig(userScript.getName(), userScript, optionalModulesPath, cmd.getOptionValue("p", null)); TaskManager tm = new TaskManager(conf); String taskId = tm.registerTask(userScript.getName(), inputValues); tm.startTaskSync(taskId); if (tm.getTask(taskId).getStatus() == TaskStatus.ERROR) { tm.getTask(taskId).getFirstError().getErrors().stream().forEach(System.err::println); } } else { System.err.println("Invalid parameters. Try -h for more information."); System.exit(1); } } } catch (Exception ex) { System.err.printf("Orzo.js crashed with error: %s\nSee the log for details.\n", ex.getMessage()); if (log != null) { log.error(ex.getMessage(), ex); } else { ex.printStackTrace(); } } }
From source file:edu.harvard.i2b2.eclipse.plugins.analysis.ontologyMessaging.SelectServiceDriver.java
public static void main(String args[]) { System.setProperty("ontologywebservice", "http://localhost:8080/i2b2/services/Select"); SelectServiceDriver driver = new SelectServiceDriver(); Document input = driver.buildSelectParameters("I2B2"); driver.printResultsAsXML(input);/*from w ww . ja v a 2 s. c o m*/ }
From source file:com.evolveum.midpoint.web.boot.MidPointSpringApplication.java
public static void main(String[] args) { System.setProperty("xml.catalog.className", CatalogImpl.class.getName()); String mode = args != null && args.length > 0 ? args[0] : null; if (LOGGER.isDebugEnabled()) { LOGGER.debug("PID:" + ManagementFactory.getRuntimeMXBean().getName() + " Application mode:" + mode + " context:" + applicationContext); }//ww w . ja va 2 s .c o m if (applicationContext != null && mode != null && "stop".equals(mode)) { System.exit(SpringApplication.exit(applicationContext, new ExitCodeGenerator() { @Override public int getExitCode() { return 0; } })); } else { applicationContext = configureApplication(new SpringApplicationBuilder()).run(args); if (LOGGER.isDebugEnabled()) { LOGGER.debug("PID:" + ManagementFactory.getRuntimeMXBean().getName() + " Application started context:" + applicationContext); } } }
From source file:au.com.jwatmuff.eventmanager.Main.java
/** * Main method.//from w ww.j av a 2s.co m */ public static void main(String args[]) { LogUtils.setupUncaughtExceptionHandler(); /* Set timeout for RMI connections - TODO: move to external file */ System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000"); updateRmiHostName(); /* * Set up menu bar for Mac */ System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager"); /* * Set look and feel to 'system' style */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.info("Failed to set system look and feel"); } /* * Set workingDir to a writable folder for storing competitions, settings etc. */ String applicationData = System.getenv("APPDATA"); if (applicationData != null) { workingDir = new File(applicationData, "EventManager"); if (workingDir.exists() || workingDir.mkdirs()) { // redirect logging to writable folder LogUtils.reconfigureFileAppenders("log4j.properties", workingDir); } else { workingDir = new File("."); } } // log version for debugging log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")"); /* * Copy license if necessary */ File license1 = new File("license.lic"); File license2 = new File(workingDir, "license.lic"); if (license1.exists() && !license2.exists()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } if (license1.exists() && license2.exists()) { if (license1.lastModified() > license2.lastModified()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } } /* * Check if run lock exists, if so ask user if it is ok to continue */ if (!obtainRunLock(false)) { int response = JOptionPane.showConfirmDialog(null, "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?", "Run-lock detected", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) obtainRunLock(true); else System.exit(0); } try { LoadWindow loadWindow = new LoadWindow(); loadWindow.setVisible(true); loadWindow.addMessage("Reading settings.."); /* * Read properties from file */ final Properties props = new Properties(); try { Properties defaultProps = PropertiesLoaderUtils .loadProperties(new ClassPathResource("eventmanager.properties")); props.putAll(defaultProps); } catch (IOException ex) { log.error(ex); } props.putAll(System.getProperties()); File databaseStore = new File(workingDir, "comps"); int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port")); loadWindow.addMessage("Loading Peer Manager.."); log.info("Loading Peer Manager"); ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService(); JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat")); peerManager.addDiscoveryService(manualDiscoveryService); monitorNetworkInterfaceChanges(peerManager); loadWindow.addMessage("Loading Database Manager.."); log.info("Loading Database Manager"); DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager); LicenseManager licenseManager = new LicenseManager(workingDir); loadWindow.addMessage("Loading Load Competition Dialog.."); log.info("Loading Load Competition Dialog"); LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager, peerManager); loadCompetitionWindow.setTitle(WINDOW_TITLE); loadWindow.dispose(); log.info("Starting Load Competition Dialog"); while (true) { // reset permission checker to use our license licenseManager.updatePermissionChecker(); GUIUtils.runModalJFrame(loadCompetitionWindow); if (loadCompetitionWindow.getSuccess()) { DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo(); if (!databaseManager.checkLock(info.id)) { String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n" + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n" + "3) Delete the competition from this computer\n" + "4) If possible, reload this competition from another computer on the network\n" + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked."; String title = "WARNING: Potential Data Corruption Detected"; int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)"); if (status == 0) continue; // return to load competition window } SynchronizingWindow syncWindow = new SynchronizingWindow(); syncWindow.setVisible(true); long t = System.nanoTime(); DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash); long dt = System.nanoTime() - t; log.debug(String.format("Initial sync in %dms", TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS))); syncWindow.dispose(); if (loadCompetitionWindow.isNewDatabase()) { GregorianCalendar calendar = new GregorianCalendar(); Date today = calendar.getTime(); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DAY_OF_MONTH, 31); Date endOfYear = new java.sql.Date(calendar.getTimeInMillis()); CompetitionInfo ci = new CompetitionInfo(); ci.setName(info.name); ci.setStartDate(today); ci.setEndDate(today); ci.setAgeThresholdDate(endOfYear); //ci.setPasswordHash(info.passwordHash); License license = licenseManager.getLicense(); if (license != null) { ci.setLicenseName(license.getName()); ci.setLicenseType(license.getType().toString()); ci.setLicenseContact(license.getContactPhoneNumber()); } database.add(ci); } // Set PermissionChecker to use database's license type String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType(); PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType)); TransactionNotifier notifier = new TransactionNotifier(); database.setListener(notifier); MainWindow mainWindow = new MainWindow(); mainWindow.setDatabase(database); mainWindow.setNotifier(notifier); mainWindow.setPeerManager(peerManager); mainWindow.setLicenseManager(licenseManager); mainWindow.setManualDiscoveryService(manualDiscoveryService); mainWindow.setTitle(WINDOW_TITLE); mainWindow.afterPropertiesSet(); TestUtil.setActivatedDatabase(database); // show main window (modally) GUIUtils.runModalJFrame(mainWindow); // shutdown procedures // System.exit(); database.shutdown(); databaseManager.deactivateDatabase(1500); if (mainWindow.getDeleteOnExit()) { for (File file : info.localDirectory.listFiles()) if (!file.isDirectory()) file.delete(); info.localDirectory.deleteOnExit(); } } else { // This can cause an RuntimeException - Peer is disconnected peerManager.stop(); System.exit(0); } } } catch (Throwable e) { log.error("Error in main function", e); String message = e.getMessage(); if (message == null) message = ""; if (message.length() > 100) message = message.substring(0, 97) + "..."; GUIUtils.displayError(null, "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message); System.exit(0); } }
From source file:com.clustercontrol.agent.Agent.java
/** * ?//from w w w . ja va2s . c o m * * @param args ?? */ public static void main(String[] args) throws Exception { // ? if (args.length != 1) { System.out.println("Usage : java Agent [Agent.properties File Path]"); System.exit(1); } try { // System m_log.info("starting Hinemos Agent..."); m_log.info("java.vm.version = " + System.getProperty("java.vm.version")); m_log.info("java.vm.vendor = " + System.getProperty("java.vm.vendor")); m_log.info("java.home = " + System.getProperty("java.home")); m_log.info("os.name = " + System.getProperty("os.name")); m_log.info("os.arch = " + System.getProperty("os.arch")); m_log.info("os.version = " + System.getProperty("os.version")); m_log.info("user.name = " + System.getProperty("user.name")); m_log.info("user.dir = " + System.getProperty("user.dir")); m_log.info("user.country = " + System.getProperty("user.country")); m_log.info("user.language = " + System.getProperty("user.language")); m_log.info("file.encoding = " + System.getProperty("file.encoding")); // System(SET) String limitKey = "jdk.xml.entityExpansionLimit"; // TODO JRE??????????????????? System.setProperty(limitKey, "0"); m_log.info(limitKey + " = " + System.getProperty(limitKey)); // TODO ???agentHome // ?????????? File file = new File(args[0]); agentHome = file.getParentFile().getParent() + "/"; m_log.info("agentHome=" + agentHome); // long startDate = HinemosTime.currentTimeMillis(); m_log.info("start date = " + new Date(startDate) + "(" + startDate + ")"); agentInfo.setStartupTime(startDate); // Agent?? m_log.info("Agent.properties = " + args[0]); // ? File scriptDir = new File(agentHome + "script/"); if (scriptDir.exists()) { File[] listFiles = scriptDir.listFiles(); if (listFiles != null) { for (File f : listFiles) { boolean ret = f.delete(); if (ret) { m_log.debug("delete script : " + f.getName()); } else { m_log.warn("delete script error : " + f.getName()); } } } else { m_log.warn("listFiles is null"); } } else { //???????? boolean ret = scriptDir.mkdir(); if (!ret) { m_log.warn("mkdir error " + scriptDir.getPath()); } } // queue? m_sendQueue = new SendQueue(); // Agent? Agent agent = new Agent(args[0]); //----------------- //-- //----------------- m_log.debug("exec() : create topic "); m_receiveTopic = new ReceiveTopic(m_sendQueue); m_receiveTopic.setName("ReceiveTopicThread"); m_log.info("receiveTopic start 1"); m_receiveTopic.start(); m_log.info("receiveTopic start 2"); // ? agent.exec(); m_log.info("Hinemos Agent started"); // ? agent.waitAwakeAgent(); } catch (Throwable e) { m_log.error("Agent.java: Runtime Exception Occurred. " + e.getClass().getName() + ", " + e.getMessage(), e); } }
From source file:com.yhfudev.SimulatorForSelfStabilizing.java
public static void main(String[] args) { // command line lib: apache CLI http://commons.apache.org/proper/commons-cli/ // command line arguments: // -- input file // -- output line to a csv file // -- algorithm: Ding's linear or randomized // single thread parsing ... Options options = new Options(); options.addOption("h", false, "print this message"); //heuristic//from w w w .j ava2 s .c o m options.addOption("u", false, "(rand) heuristic on"); options.addOption("y", true, "show the graph with specified delay (ms)"); options.addOption("i", true, "the input file name"); options.addOption("o", true, "the results is save to a attachable output cvs file"); options.addOption("l", true, "the graph activities trace log file name"); options.addOption("s", true, "save the graph to a file"); options.addOption("a", true, "the algorithm name, ding or rand"); // options specified to generator options.addOption("g", true, "the graph generator algorithm name: fan1l, fan2l, rand, doro, flower, watt, lobster"); options.addOption("n", true, "the number of nodes"); options.addOption("d", true, "(rand) the node degree (max)"); options.addOption("f", false, "(rand) if the degree value is fix or not"); options.addOption("p", true, "(watt) the probability of beta"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { e.printStackTrace(); return; } if (cmd.hasOption("h")) { showHelp(options); return; } int delay_time = 0; if (cmd.hasOption("y")) { delay_time = Integer.parseInt(cmd.getOptionValue("y")); } String sFileName = null; sFileName = null; FileWriter writer = null; if (cmd.hasOption("o")) { sFileName = cmd.getOptionValue("o"); } if ((null != sFileName) && (!"".equals(sFileName))) { try { writer = new FileWriter(sFileName, true); // true: append } catch (IOException e) { e.printStackTrace(); System.out.println("Error: unable to open the output file " + sFileName); return; } } FileWriter wrGraph = null; sFileName = null; if (cmd.hasOption("s")) { sFileName = cmd.getOptionValue("s"); } if ((null != sFileName) && (!"".equals(sFileName))) { try { wrGraph = new FileWriter(sFileName, true); // true: append } catch (IOException e) { e.printStackTrace(); System.out.println("Error: unable to open the saveGraph file " + sFileName); return; } } sFileName = null; if (cmd.hasOption("i")) { sFileName = cmd.getOptionValue("i"); } String genname = null; if (cmd.hasOption("g")) { genname = cmd.getOptionValue("g"); } if ((null == genname) && (null == sFileName)) { System.out.println("Error: not specify the input file or graph generator"); showHelp(options); return; } if ((null != genname) && (null != sFileName)) { System.out.println("Error: do not specify the input file and graph generator at the same time"); showHelp(options); return; } if (delay_time > 0) { // create and display a graph System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer"); } Graph graph = new SingleGraph("test"); //graph.setNullAttributesAreErrors(true); // to throw an exception instead of returning null (in getAttribute()). if (delay_time > 0) { graph.addAttribute("ui.quality"); graph.addAttribute("ui.antialias"); graph.addAttribute("ui.stylesheet", "url(data/selfstab-mwcds.css);"); graph.display(); } // save the trace to file FileSinkDGS dgs = null; if (cmd.hasOption("l")) { dgs = new FileSinkDGS(); graph.addSink(dgs); try { dgs.begin(cmd.getOptionValue("l")); } catch (IOException e) { e.printStackTrace(); } } Generator generator = null; if (null != sFileName) { System.out.println("DEBUG: the input file=" + sFileName); FileSource source = new FileSourceDGS(); source.addSink(graph); int count_edge_error = 0; try { //source.begin("data/selfstab-mwcds.dgs"); // Ding's paper example //source.begin("data/selfstab-ds.dgs"); // DS example //source.begin("data/selfstab-doro-1002.dgs"); // DorogovtsevMendes //source.begin("data/selfstab-rand-p10-10002.dgs"); // random connected graph with degree = 10% nodes //source.begin("data/selfstab-rand-f5-34.dgs"); // random connected graph with degree = 5 source.begin(sFileName); while (true) { try { if (false == source.nextEvents()) { break; } } catch (EdgeRejectedException e) { // ignore count_edge_error++; System.out.println("DEBUG: adding edge error: " + e.toString()); } if (delay_time > 0) { delay(delay_time); } } source.end(); //} catch (InterruptedException e) { // e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("DEBUG: END read from source. # of edges ignored=" + count_edge_error); } else { // assert (genname != null); // graph generator //generator = new ChvatalGenerator(); // fix size //generator = new FullGenerator(); // full connected, 2 steps,1 node in dominate set //generator = new GridGenerator(); // only one result //generator = new HypercubeGenerator(); // one result //generator = new IncompleteGridGenerator(); // error //generator = new PetersenGraphGenerator(); // fix size //generator = new PointsOfInterestGenerator(); // error //generator = new RandomEuclideanGenerator(); // linear algo endless loop //generator = new RandomFixedDegreeDynamicGraphGenerator(); // //generator = new RandomGenerator(); // //generator = new URLGenerator("http://www.cnbeta.com"); // //generator = new WikipediaGenerator("Antarctica"); // no end //generator = new DorogovtsevMendesGenerator(); // ok //generator = new FlowerSnarkGenerator(); // ok //generator = new WattsStrogatzGenerator(maxSteps, 30, 0.5); // small world, ok //generator = new LobsterGenerator(); // tree like, ok int i; int n = 12; // the number of nodes if (cmd.hasOption("n")) { n = Integer.parseInt(cmd.getOptionValue("n")); } int d = 3; // the degree of nodes if (cmd.hasOption("d")) { d = Integer.parseInt(cmd.getOptionValue("d")); } boolean isFix = false; if (cmd.hasOption("f")) { isFix = true; } if ("".equals(genname)) { System.out.println("Error: not set generator name"); return; } else if ("fan1l".equals(genname)) { generator = new FanGenerator(); } else if ("fan2l".equals(genname)) { generator = new Fan2lGenerator(graph, d); } else if ("doro".equals(genname)) { generator = new DorogovtsevMendesGenerator(); } else if ("flower".equals(genname)) { generator = new FlowerSnarkGenerator(); } else if ("lobster".equals(genname)) { generator = new LobsterGenerator(); } else if ("rand".equals(genname)) { generator = new ConnectionGenerator(graph, d, false, isFix); } else if ("watt".equals(genname)) { // WattsStrogatzGenerator(n,k,beta) // a ring of n nodes // each node is connected to its k nearest neighbours, k must be even // n >> k >> log(n) >> 1 // beta being a probability it must be between 0 and 1. int k; double beta = 0.5; if (cmd.hasOption("p")) { beta = Double.parseDouble(cmd.getOptionValue("p")); } k = (n / 20) * 2; if (k < 2) { k = 2; } if (n < 2 * 6) { n = 2 * 6; } generator = new WattsStrogatzGenerator(n, k, beta); } /*int listf5[][] = { {12, 5}, {34, 5}, {102, 5}, {318, 5}, {1002, 5}, {3164, 5}, {10002, 5}, }; int listp3[][] = { {12, 2}, {34, 2}, {102, 3}, {318, 9}, {1002, 30}, {3164, 90}, {10002, 300}, }; int listp10[][] = { {12, 2}, {34, 3}, {102, 10}, {318, 32}, {1002, 100}, {3164, 316}, {10002, 1000}, }; i = 6; maxSteps = listf5[i][0]; int degree = listf5[i][1]; generator = new ConnectionGenerator(graph, degree, false, true); */ generator.addSink(graph); generator.begin(); for (i = 1; i < n; i++) { generator.nextEvents(); } generator.end(); delay(500); } if (cmd.hasOption("a")) { SinkAlgorithm algorithm = null; String algo = "rand"; algo = cmd.getOptionValue("a"); if ("ding".equals(algo)) { algorithm = new SelfStabilizingMWCDSLinear(); } else if ("ds".equals(algo)) { algorithm = new SelfStabilizingDSLinear(); } else { algorithm = new SelfStabilizingMWCDSRandom(); } algorithm.init(graph); algorithm.setSource("0"); if (delay_time > 0) { algorithm.setAnimationDelay(delay_time); } if (cmd.hasOption("u")) { algorithm.heuristicOn(true); } else { algorithm.heuristicOn(false); } algorithm.compute(); GraphVerificator verificator = new MWCDSGraphVerificator(); if (verificator.verify(graph)) { System.out.println("DEBUG: PASS MWCDSGraphVerificator verficiation."); } else { System.out.println("DEBUG: FAILED MWCDSGraphVerificator verficiation!"); } if (null != writer) { AlgorithmResult result = algorithm.getResult(); result.SaveTo(writer); try { writer.flush(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } algorithm.terminate(); } if (null != generator) { generator.removeSink(graph); } if (dgs != null) { graph.removeSink(dgs); try { dgs.end(); } catch (IOException e) { e.printStackTrace(); } } if (null != wrGraph) { try { saveGraph(graph, wrGraph); wrGraph.flush(); wrGraph.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:com.da.daum.DaumCafeBungList.java
public static void main(String[] args) { DaumCafeBungList cfl = new DaumCafeBungList(); log.warn("Logging Works"); System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug"); try {//ww w . j a v a2 s .c o m // https://msp.f-secure.com/web-test/common/test.html // String body = // CHttpUtil.DownloadHtml("https://logins.daum.net/accounts/loginform.do?mobilefull=1&t__nil_footer=login&url=http%3a%2f%2fm%2edaum%2enet%2f"); /* * String body = CHttpUtil.DownloadHtml( * "https://logins.daum.net/accounts/mobile.do?url=http%3A%2F%2Fm.daum.net%2F&relative=&mobilefull=1&weblogin=1&id=changwng&pw=cw89040310&stln=on&saved_id=on" * ); System.out.println(body); */ String nPage = "1"; String p_author_id = "bluesman"; String p_gnum = ""; // ga String p_host_url = ""; // ga if (args.length > 0) { nPage = args[0]; } if (args.length > 1) { p_author_id = args[1]; } if (args.length > 2) { STORY_DIR = args[2]; } if (args.length > 3) { p_host_url = args[3]; SO_URL = p_host_url; /* * host_url = "http://www."+SO_URL; photo_url = * "http://photo."+SO_URL+"/album/theme/"; story_url = * "http://story."+SO_URL+"/honor/"; */ } cfl.executeURL(nPage, p_author_id, p_gnum); // cfl.executeAuthorList(nPage, p_author_id, p_gnum); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } }