List of usage examples for java.lang System getProperty
public static String getProperty(String key)
From source file:DataIODemo.java
public static void main(String[] args) throws IOException { // write the data out DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt")); double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; int[] units = { 12, 8, 13, 29, 50 }; String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; for (int i = 0; i < prices.length; i++) { out.writeDouble(prices[i]);//from w w w . j a v a2 s.c o m out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n'); } out.close(); // read it in again DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt")); double price; int unit; StringBuffer desc; double total = 0.0; try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab char chr; desc = new StringBuffer(20); char lineSep = System.getProperty("line.separator").charAt(0); while ((chr = in.readChar()) != lineSep) desc.append(chr); System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }
From source file:jms.Main.java
public static void main(String[] args) throws NamingException, JMSException, FileNotFoundException, InterruptedException, ParseException, CloneNotSupportedException { Options options = createOptions();//from w w w. j ava2 s. c om CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args, false); Histogram latencyHist = Main.metrics.histogram(name(ConsumerThread.class, "global", "consumer", "latency")); Meter consumerRate = Main.metrics.meter(name(ConsumerThread.class, "global", "consumer", "rate")); if (cmd.hasOption("c")) { CONFIG_FILE_PATH = cmd.getOptionValue("c"); } else { CONFIG_FILE_PATH = System.getProperty("user.dir") + "/src/main/resources/client.yaml"; } TestConfiguration config = ConfigReader.parseConfig(CONFIG_FILE_PATH); // System.setProperty("qpid.flow_control_wait_failure", "1500000"); // Subscribers startStatReporting(config.getGlobalConfig()); int subscriberCount = config.getTopicSubscriberConfigList().size() + config.getQueueSubscriberConfigList().size() + config.getDurableSubscriberConfigList().size(); final List<Thread> threadList = new ArrayList<Thread>(subscriberCount); TestTopicSubscriber topicSubscriber; for (SubscriberConfig subscriberConfig : config.getTopicSubscriberConfigList()) { topicSubscriber = new TestTopicSubscriber(); topicSubscriber.subscribe(subscriberConfig); Thread subThread = new Thread(new ConsumerThread(topicSubscriber, latencyHist, consumerRate)); subThread.start(); threadList.add(subThread); } SimpleJMSConsumer queueReceiver; for (SubscriberConfig subscriberConfig : config.getQueueSubscriberConfigList()) { queueReceiver = new TestQueueReceiver(); queueReceiver.subscribe(subscriberConfig); Thread subThread = new Thread(new ConsumerThread(queueReceiver, latencyHist, consumerRate)); subThread.start(); threadList.add(subThread); } TestDurableTopicSubscriber durableTopicSubscriber; for (SubscriberConfig subscriberConfig : config.getDurableSubscriberConfigList()) { durableTopicSubscriber = new TestDurableTopicSubscriber(); durableTopicSubscriber.subscribe(subscriberConfig); Thread subThread = new Thread(new ConsumerThread(durableTopicSubscriber, latencyHist, consumerRate)); subThread.start(); threadList.add(subThread); } // Publishers TestTopicPublisher topicPublisher; for (PublisherConfig publisherConfig : config.getTopicPublisherList()) { topicPublisher = new TestTopicPublisher(); topicPublisher.init(publisherConfig); Thread pubThread = new Thread(new PublisherThread(topicPublisher)); pubThread.start(); threadList.add(pubThread); } TestQueueSender queuePublisher; for (PublisherConfig publisherConfig : config.getQueuePublisherConfigList()) { queuePublisher = new TestQueueSender(); queuePublisher.init(publisherConfig); Thread pubThread = new Thread(new PublisherThread(queuePublisher)); pubThread.start(); threadList.add(pubThread); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { log.info("Shutting down test client."); slf4jReporter.report(); csvGaugeReporter.report(); reporter.report(); if (null != jmxReporter) { jmxReporter.close(); } if (null != csvReporter) { csvReporter.report(); csvReporter.close(); } for (Thread t : threadList) { t.interrupt(); } } }); // barrier. wait till all the done for (Thread thread : threadList) { thread.join(); } log.info("Test Complete!"); }
From source file:de.uniluebeck.itm.spyglass.SpyglassApp.java
/** * The stand-alone application's entry point * * @param args an array of arguments/*from ww w . java 2 s.com*/ */ public static void main(final String[] args) { tryToSetLoggingDefaults(); log.debug("java.library.path=" + System.getProperty("java.library.path")); log.debug("java.class.path=" + System.getProperty("java.class.path")); // Set an exception handler which will handle uncaught exceptions Window.setExceptionHandler(new SpyglassExceptionHandler()); if (ENABLE_SLEAK) { // create a customized Device. Since a Device is a singleton object // (at least with currently...) we don't have to save it. Newly created // Shells will use it automatically. final DeviceData data = new DeviceData(); data.tracking = true; data.debug = true; new Display(data); // Open sleak final Sleak sleak = new Sleak(); sleak.open(); } SpyglassApp app = null; try { app = new SpyglassApp(); app.addToolBar(SWT.None); app.addMenuBar(); app.open(); } catch (final Exception e) { log.error(e, e); } finally { if (app != null) { app.shutdown(); } } }
From source file:edu.ehu.galan.lite.Example.java
public static void main(String[] args) { //initizalize ehcache system System.setProperty("net.sf.ehcache.enableShutdownHook", "true"); if (CacheManager.getCacheManager("ehcacheLitet.xml") == null) { CacheManager.create("ehcacheLitet.xml"); }/* w w w . ja v a 2 s . c o m*/ cache = CacheManager.getInstance().getCache("LiteCache"); //load the corpus to process Corpus corpus = new Corpus("en"); //we spedify the directory and the database mapping (wikipedia in this case) corpus.loadCorpus("testCorpus", Document.SourceType.wikipedia); //will read the document using Illinois NLP utilities PlainTextDocumentReaderLBJEn parser = new PlainTextDocumentReaderLBJEn(); AlgorithmRunner runner = new AlgorithmRunner(); String resources = System.getProperty("user.dir") + "/resources/"; //algorithms initializacion CValueAlgortithm cvalue = new CValueAlgortithm(); cvalue.addNewProcessingFilter(new AdjPrepNounFilter()); TFIDFAlgorithm tf = new TFIDFAlgorithm(new CaseStemmer(CaseStemmer.CaseType.lowercase), "en"); ShallowParsingGrammarAlgortithm sha = new ShallowParsingGrammarAlgortithm( System.getProperty("user.dir") + "/resources/lite/" + "grammars/Cg2EnGrammar.grammar", "cg3/"); KPMinerAlgorithm kp = new KPMinerAlgorithm(); RakeAlgorithm ex = new RakeAlgorithm(); ex.loadStopWordsList("resources/lite/stopWordLists/RakeStopLists/SmartStopListEn"); ex.loadPunctStopWord("resources/lite/stopWordLists/RakeStopLists/RakePunctDefaultStopList"); //algorithm submitting to execute them in parallel runner.submitAlgorithm(kp); runner.submitAlgorithm(cvalue); runner.submitAlgorithm(tf); runner.submitAlgorithm(ex); runner.submitAlgorithm(sha); //load stop list List<String> standardStop = null; try { standardStop = Files.readAllLines(Paths.get(resources + "lite/stopWordLists/standardStopList"), StandardCharsets.UTF_8); } catch (IOException e1x) { Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, e1x); } //initialize Wikiminer helper (class that interacts with Wikiminer services) WikiminnerHelper helper = WikiminnerHelper.getInstance(resources); helper.setLanguage("en"); //we may operate in local mode (using Wikiminer as API instead of interacting via REST api // helper.setLocalMode(false,"/home/angel/nfs/wikiminer/configs/wikipedia"); WikiMinerMap wikimapping = new WikiMinerMap(resources, helper); CValueWikiDisambiguator disambiguator = new CValueWikiDisambiguator(resources, helper); CValueWikiRelationship relate = new CValueWikiRelationship(resources, helper); WikipediaData data = new WikipediaData(resources, helper); helper.openConnection(); //process all the documents in the corpus while (!corpus.getDocQueue().isEmpty()) { Document doc = corpus.getDocQueue().poll(); doc.setSource(Document.SourceType.wikipedia); parser.readSource(doc.getPath()); doc.setSentenceList(parser.getSentenceList()); doc.setTokenList(parser.getTokenizedSentenceList()); System.out.println(doc.getName()); runner.runAlgorihms(doc, resources); doc.applyGlobalStopWordList(standardStop); doc.mapThreshold(1.9f, new String[] { "CValue" }); doc.mapThreshold(0.00034554f, new String[] { "TFIDF" }); doc.removeAndMixTerms(); //map document wikimapping.mapCorpus(doc); disambiguator.disambiguateTopics(doc); //we may disambiguate topics that do not disambiguated correctly DuplicateRemoval.disambiguationRemoval(doc); DuplicateRemoval.topicDuplicateRemoval(doc); //obtain the wiki links,labels, etc data.processDocument(doc); //measure domain relatedness relate.relate(doc); //save the results Document.saveJsonToDir("", doc); } //close wikiminer connection and caches helper.closeConnection(); cache.dispose(); CacheManager.getInstance().shutdown(); System.exit(0); }
From source file:emperior.Main.java
public static void main(String[] args) throws Exception { mainFrame = new MainFrame(); operatingSystem = System.getProperty("os.name"); CommandLineParser parser = new BasicParser(); Options options = new Options(); options.addOption("h", "help", false, "Print this usage information"); options.addOption("t", "test", true, "Name of the Bat-File which is executed for Compilation and Unit-Testing"); options.addOption("r", "run", true, "Name of the Bat-File which is executed for Compilation and running the project"); options.addOption("f", "folder", true, "Name of the Folder in which the exercises for the Experiment are stored"); CommandLine commandLine = parser.parse(options, args); // read from command line if (commandLine.getOptions().length > 0) { readCommandLine(commandLine, options); }//from w w w . j ava2 s . co m // read from property file else { readPropertyFile(); } initLogging(); checkBatFile(); addLineToLogFile("[Start] Emperior"); if (resuming) Main.addLineToLogFile("[ResumeTask] Resume task: " + Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask)); else { Main.addLineToLogFile("[StartTask] Start new task: " + Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask)); startedWith = Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask); updateStartedWithTask(Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask)); } mainFrame.init(); mainFrame.setSize(800, 600); mainFrame.setVisible(true); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Main.addLineToLogFile("[PauseTask] Stop task: " + Main.tasktypes.get(Main.activeType) + "_" + Main.tasks.get(Main.activeTask)); addLineToLogFile("[Close] Emperior"); updateResumeTask(tasktypes.get(activeType) + "_" + tasks.get(activeTask)); System.exit(0); } }); mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); //makeContiniousCopys(); }
From source file:Main.java
public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel gui = new JPanel(new BorderLayout(5, 5)); JPanel plafComponents = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 3)); plafComponents.setBorder(new TitledBorder("FlowLayout(FlowLayout.RIGHT, 3,3)")); UIManager.LookAndFeelInfo[] plafInfos = UIManager.getInstalledLookAndFeels(); String[] plafNames = new String[plafInfos.length]; for (int ii = 0; ii < plafInfos.length; ii++) { plafNames[ii] = plafInfos[ii].getName(); }//from ww w.ja v a2 s .co m JComboBox plafChooser = new JComboBox(plafNames); plafComponents.add(plafChooser); JCheckBox pack = new JCheckBox("Pack on PLAF change", true); plafComponents.add(pack); plafChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { int index = plafChooser.getSelectedIndex(); try { UIManager.setLookAndFeel(plafInfos[index].getClassName()); SwingUtilities.updateComponentTreeUI(frame); if (pack.isSelected()) { frame.pack(); frame.setMinimumSize(frame.getSize()); } } catch (Exception e) { e.printStackTrace(); } } }); gui.add(plafComponents, BorderLayout.NORTH); JPanel dynamicLabels = new JPanel(new BorderLayout(4, 4)); dynamicLabels.setBorder(new TitledBorder("BorderLayout(4,4)")); gui.add(dynamicLabels, BorderLayout.WEST); final JPanel labels = new JPanel(new GridLayout(0, 2, 3, 3)); labels.setBorder(new TitledBorder("GridLayout(0,2,3,3)")); JButton addNew = new JButton("Add Another Label"); dynamicLabels.add(addNew, BorderLayout.NORTH); addNew.addActionListener(new ActionListener() { private int labelCount = 0; public void actionPerformed(ActionEvent ae) { labels.add(new JLabel("Label " + ++labelCount)); frame.validate(); } }); dynamicLabels.add(new JScrollPane(labels), BorderLayout.CENTER); String[] header = { "Name", "Value" }; String[] a = new String[0]; String[] names = System.getProperties().stringPropertyNames().toArray(a); String[][] data = new String[names.length][2]; for (int ii = 0; ii < names.length; ii++) { data[ii][0] = names[ii]; data[ii][1] = System.getProperty(names[ii]); } DefaultTableModel model = new DefaultTableModel(data, header); JTable table = new JTable(model); JScrollPane tableScroll = new JScrollPane(table); Dimension tablePreferred = tableScroll.getPreferredSize(); tableScroll.setPreferredSize(new Dimension(tablePreferred.width, tablePreferred.height / 3)); JPanel imagePanel = new JPanel(new GridBagLayout()); JLabel imageLabel = new JLabel("test"); imagePanel.add(imageLabel, null); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tableScroll, new JScrollPane(imagePanel)); gui.add(splitPane, BorderLayout.CENTER); frame.setContentPane(gui); frame.pack(); frame.setVisible(true); }
From source file:ca.uqac.dim.net.verify.NetworkChecker.java
/** * Main loop. Processes command line arguments, loads the network, builds and * sends a file to NuSMV and handles its response. * @param args Command-line arguments/* ww w . ja v a 2 s. c o m*/ */ public static void main(String[] args) { // Configuration variables boolean opt_show_file = false, opt_show_messages = true, opt_show_stats = false; // Create and parse command line options Option opt = null; Options options = new Options(); options.addOption("f", "file", false, "Output NuSMV file to stdout"); options.addOption("s", "time", false, "Display statistics"); options.addOption("h", "help", false, "Show usage information"); options.addOption("q", "quiet", false, "Do not display any message or explanation"); opt = new Option("i", "file", true, "Input directory"); opt.setRequired(true); options.addOption(opt); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Error parsing command line arguments"); showUsage(options); System.exit(1); } if (cmd == null) { System.err.println("Error parsing command line arguments"); showUsage(options); System.exit(1); } // Get options assert cmd != null; opt_show_file = cmd.hasOption("f"); opt_show_messages = !cmd.hasOption("q"); opt_show_stats = cmd.hasOption("s"); if (opt_show_messages) System.err.println( "Distributed anomaly verifier\n(C) 2012 Sylvain Hall, Universit du Qubec Chicoutimi\n"); // Get input directory and blob assert cmd.hasOption("i"); String slash = System.getProperty("file.separator"); String input_dir = cmd.getOptionValue("i"); int loc = input_dir.lastIndexOf(slash); String dir_name = "", blob = ""; if (loc == -1) { dir_name = ""; blob = input_dir; } else { dir_name = input_dir.substring(0, loc); blob = input_dir.substring(loc + 1); } // Load network Network net = null; try { net = loadNetworkFromDirectory(dir_name, blob, slash); } catch (FileNotFoundException e) { System.err.print("Error reading "); System.err.println(e.getMessage()); System.exit(1); } catch (IOException e) { System.err.println(e); System.exit(1); } // Build NuSMV file assert net != null; StringBuilder sb = new StringBuilder(); if (opt_show_file) { sb.append("-- File auto-generated by DistributedChecker\n"); sb.append("-- (C) 2012 Sylvain Hall, Universit du Qubec Chicoutimi\n\n"); } sb.append(net.toSmv(opt_show_file)); // Simple shadowing String f_shadowing = "G (frozen -> !(interval_l <= rule_interval_l & interval_r >= rule_interval_r & decision != rule_decision))"; sb.append("\n\nLTLSPEC\n").append(f_shadowing); // Run NuSMV and parse its return value if (opt_show_file) { System.out.println(sb); System.exit(0); } RuntimeInfos ri = null; try { ri = runNuSMV(sb.toString()); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(1); } catch (InterruptedException e) { System.err.println(e.getMessage()); System.exit(1); } assert ri != null; // If requested, compute and show an explanation from NuSMV's returned contents if (opt_show_messages) { ExplanationTrace t = null; try { t = net.explain(ri.m_return_contents); } catch (NuSmvParseException e) { System.err.println("Error reading NuSMV's answer"); System.exit(1); } if (t == null) { // No explanation => no anomaly found System.out.println("No anomaly found"); } else System.out.println(t); } // If requested, show runtime statistics if (opt_show_stats) { StringBuilder out = new StringBuilder(); out.append(net.getNodeSize()).append(","); out.append(net.getFirewallRuleSize()).append(","); out.append(net.getRoutingTableSize()).append(","); out.append(ri.m_runtime); System.out.println(out); } System.exit(0); }
From source file:com.khubla.jvmbasic.jvmbasicc.JVMBasic.java
/** * start here/* w ww . j a v a 2 s . com*/ * <p> * -file src\test\resources\bas\easy\print.bas -verbose true * </p> */ public static void main(String[] args) { try { System.out.println("khubla.com jvmBASIC Compiler"); /* * options */ final Options options = new Options(); Option oo = Option.builder().argName(OUTPUT_OPTION).longOpt(OUTPUT_OPTION).type(String.class).hasArg() .required(false).desc("target directory to output to").build(); options.addOption(oo); oo = Option.builder().argName(FILE_OPTION).longOpt(FILE_OPTION).type(String.class).hasArg() .required(true).desc("file to compile").build(); options.addOption(oo); oo = Option.builder().argName(VERBOSE_OPTION).longOpt(VERBOSE_OPTION).type(String.class).hasArg() .required(false).desc("verbose output").build(); options.addOption(oo); /* * parse */ final CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (final Exception e) { e.printStackTrace(); final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("posix", options); System.exit(0); } /* * verbose output? */ final Boolean verbose = Boolean.parseBoolean(cmd.getOptionValue(VERBOSE_OPTION)); /* * get the file */ final String filename = cmd.getOptionValue(FILE_OPTION); final String outputDirectory = cmd.getOptionValue(OUTPUT_OPTION); if (null != filename) { /* * filename */ final String basFileName = System.getProperty("user.dir") + "/" + filename; final File fl = new File(basFileName); if (true == fl.exists()) { /* * show the filename */ System.out.println("Compiling: " + fl.getCanonicalFile()); /* * compiler */ final JVMBasicCompiler jvmBasicCompiler = new JVMBasicCompiler(); /* * compile */ jvmBasicCompiler.compileToClassfile(basFileName, null, outputDirectory, verbose, true, true); } else { throw new Exception("Unable to find: '" + basFileName + "'"); } } else { throw new Exception("File was not supplied"); } } catch (final Exception e) { e.printStackTrace(); } }
From source file:com.moss.error_reporting.server.ErrorReportServer.java
public static void main(String[] args) throws Exception { File log4jConfigFile = new File("log4j.xml"); if (log4jConfigFile.exists()) { DOMConfigurator.configureAndWatch(log4jConfigFile.getAbsolutePath(), 1000); System.out.println("Configuring with log file " + log4jConfigFile.getAbsolutePath()); } else {/*from ww w.jav a2 s . c om*/ BasicConfigurator.configure(); Logger.getRootLogger().setLevel(Level.INFO); } ServerConfiguration config; JAXBContext context = JAXBContext.newInstance(ServerConfiguration.class); JAXBHelper helper = new JAXBHelper(context); File configFile = new File("error-report-server.xml"); if (!configFile.exists()) configFile = new File(new File(System.getProperty("user.dir")), ".error-report-server.xml"); if (!configFile.exists()) configFile = new File("/etc/error-report-server.xml"); if (!configFile.exists()) { config = new ServerConfiguration(); helper.writeToFile(helper.writeToXmlString(config), configFile); System.out.println("Created default config file at " + configFile.getAbsolutePath()); } else { System.out.println("Reading config file at " + configFile.getAbsolutePath()); config = helper.readFromFile(configFile); } new ErrorReportServer(config); }
From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java
public static void main(String[] args) { try {// ww w . ja v a 2 s .c o m BasicConfigurator.configure(); //loadProperties(); if (args.length < 2) { System.out.println("Usage: BuildTestbed <testbedID> <inputfile>"); System.exit(0); } int testbedID = Integer.parseInt(args[0]); String filename = args[1]; Connection conn = null; Statement statement = null; MoteSqlAdapter adapter = new MoteSqlAdapter(); Map<Integer, Mote> motes = adapter.readMotes(); log.info(motes); String connStr = System.getProperty("nestbed.options.databaseConnectionString"); log.info("connStr: " + connStr); conn = DriverManager.getConnection(connStr); statement = conn.createStatement(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = in.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); int address = Integer.parseInt(tokenizer.nextToken()); String serial = tokenizer.nextToken(); int xLoc = Integer.parseInt(tokenizer.nextToken()); int yLoc = Integer.parseInt(tokenizer.nextToken()); log.info("Input Mote:\n" + "-----------\n" + "address: " + address + "\n" + "serial: " + serial + "\n" + "xLoc: " + xLoc + "\n" + "yLoc: " + yLoc); for (Mote i : motes.values()) { if (i.getMoteSerialID().equals(serial)) { String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress," + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", " + address + ", " + xLoc + ", " + yLoc + ")"; log.info(query); statement.executeUpdate(query); } } } conn.commit(); } catch (Exception ex) { log.error("Exception in main", ex); } }