List of usage examples for java.lang Thread Thread
public Thread(String name)
From source file:com.salaboy.rolo.hardware.test.HardwareTestCommandServer.java
public static void main(String[] args) throws Exception { Weld weld = new Weld(); WeldContainer container = weld.initialize(); HardwareTestCommandServer roloCommandServer = container.instance().select(HardwareTestCommandServer.class) .get();// w w w . j a v a 2 s .c o m // create Options object Options options = new Options(); // add t option options.addOption("t", true, "sensors latency"); options.addOption("ip", true, "host"); options.addOption("port", true, "port"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); String sensorLatency = cmd.getOptionValue("t"); if (sensorLatency == null) { System.out.println(" The Default Latency will be used: " + defaultLatency); } else { System.out.println(" The Latency will be set to: " + sensorLatency); defaultLatency = new Long(sensorLatency); } String ip = cmd.getOptionValue("ip"); if (ip == null) { System.out.println(" The Default IP will be used: 127.0.0.1"); roloCommandServer.setHost("127.0.0.1"); } else { System.out.println(" The IP will be set to: " + ip); roloCommandServer.setHost(ip); } String port = cmd.getOptionValue("port"); if (port == null) { System.out.println(" The Default Port will be used: 5445"); roloCommandServer.setPort(5445); } else { System.out.println(" The Port will be set to: " + port); roloCommandServer.setPort(Integer.parseInt(port)); } System.out.println("Starting Rolo ..."); Thread thread = new Thread(roloCommandServer); thread.start(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Shutdown Hook is running !"); readDistanceSensors = false; readLightSensors = false; readTouchSensors = false; } }); }
From source file:co.paralleluniverse.photon.Photon.java
public static void main(final String[] args) throws InterruptedException, IOException { final Options options = new Options(); options.addOption("rate", true, "Requests per second (default " + rateDefault + ")"); options.addOption("duration", true, "Minimum test duration in seconds: will wait for <duration> * <rate> requests to terminate or, if progress check enabled, no progress after <duration> (default " + durationDefault + ")"); options.addOption("maxconnections", true, "Maximum number of open connections (default " + maxConnectionsDefault + ")"); options.addOption("timeout", true, "Connection and read timeout in millis (default " + timeoutDefault + ")"); options.addOption("print", true, "Print cycle in millis, 0 to disable intermediate statistics (default " + printCycleDefault + ")"); options.addOption("check", true, "Progress check cycle in millis, 0 to disable progress check (default " + checkCycleDefault + ")"); options.addOption("stats", false, "Print full statistics when finish (default false)"); options.addOption("minmax", false, "Print min/mean/stddev/max stats when finish (default false)"); options.addOption("name", true, "Test name to print in the statistics (default '" + testNameDefault + "')"); options.addOption("help", false, "Print help"); try {//from w w w . ja va 2 s. c o m final CommandLine cmd = new BasicParser().parse(options, args); final String[] ar = cmd.getArgs(); if (cmd.hasOption("help") || ar.length != 1) printUsageAndExit(options); final String url = ar[0]; final int timeout = Integer.parseInt(cmd.getOptionValue("timeout", timeoutDefault)); final int maxConnections = Integer .parseInt(cmd.getOptionValue("maxconnections", maxConnectionsDefault)); final int duration = Integer.parseInt(cmd.getOptionValue("duration", durationDefault)); final int printCycle = Integer.parseInt(cmd.getOptionValue("print", printCycleDefault)); final int checkCycle = Integer.parseInt(cmd.getOptionValue("check", checkCycleDefault)); final String testName = cmd.getOptionValue("name", testNameDefault); final int rate = Integer.parseInt(cmd.getOptionValue("rate", rateDefault)); final MetricRegistry metrics = new MetricRegistry(); final Meter requestMeter = metrics.meter("request"); final Meter responseMeter = metrics.meter("response"); final Meter errorsMeter = metrics.meter("errors"); final Logger log = LoggerFactory.getLogger(Photon.class); final ConcurrentHashMap<String, AtomicInteger> errors = new ConcurrentHashMap<>(); final HttpGet request = new HttpGet(url); final StripedTimeSeries<Long> sts = new StripedTimeSeries<>(30000, false); final StripedHistogram sh = new StripedHistogram(60000, 5); log.info("name: " + testName + " url:" + url + " rate:" + rate + " duration:" + duration + " maxconnections:" + maxConnections + ", " + "timeout:" + timeout); final DefaultConnectingIOReactor ioreactor = new DefaultConnectingIOReactor(IOReactorConfig.custom() .setConnectTimeout(timeout).setIoThreadCount(10).setSoTimeout(timeout).build()); Runtime.getRuntime().addShutdownHook(new Thread(() -> { final List<ExceptionEvent> events = ioreactor.getAuditLog(); if (events != null) events.stream().filter(event -> event != null).forEach(event -> { System.err.println( "Apache Async HTTP Client I/O Reactor Error Time: " + event.getTimestamp()); //noinspection ThrowableResultOfMethodCallIgnored if (event.getCause() != null) //noinspection ThrowableResultOfMethodCallIgnored event.getCause().printStackTrace(); }); if (cmd.hasOption("stats")) printFinishStatistics(errorsMeter, sts, sh, testName); if (!errors.keySet().isEmpty()) errors.entrySet().stream() .forEach(p -> log.info(testName + " " + p.getKey() + " " + p.getValue() + "ms")); System.out.println( testName + " responseTime(90%): " + sh.getHistogramData().getValueAtPercentile(90) + "ms"); if (cmd.hasOption("minmax")) { final HistogramData hd = sh.getHistogramData(); System.out.format("%s %8s%8s%8s%8s\n", testName, "min", "mean", "sd", "max"); System.out.format("%s %8d%8.2f%8.2f%8d\n", testName, hd.getMinValue(), hd.getMean(), hd.getStdDeviation(), hd.getMaxValue()); } })); final PoolingNHttpClientConnectionManager mngr = new PoolingNHttpClientConnectionManager(ioreactor); mngr.setDefaultMaxPerRoute(maxConnections); mngr.setMaxTotal(maxConnections); final CloseableHttpAsyncClient ahc = HttpAsyncClientBuilder.create().setConnectionManager(mngr) .setDefaultRequestConfig(RequestConfig.custom().setLocalAddress(null).build()).build(); try (final CloseableHttpClient client = new FiberHttpClient(ahc)) { final int num = duration * rate; final CountDownLatch cdl = new CountDownLatch(num); final Semaphore sem = new Semaphore(maxConnections); final RateLimiter rl = RateLimiter.create(rate); spawnStatisticsThread(printCycle, cdl, log, requestMeter, responseMeter, errorsMeter, testName); for (int i = 0; i < num; i++) { rl.acquire(); if (sem.availablePermits() == 0) log.debug("Maximum connections count reached, waiting..."); sem.acquireUninterruptibly(); new Fiber<Void>(() -> { requestMeter.mark(); final long start = System.nanoTime(); try { try (final CloseableHttpResponse ignored = client.execute(request)) { responseMeter.mark(); } catch (final Throwable t) { markError(errorsMeter, errors, t); } } catch (final Throwable t) { markError(errorsMeter, errors, t); } finally { final long now = System.nanoTime(); final long millis = TimeUnit.NANOSECONDS.toMillis(now - start); sts.record(start, millis); sh.recordValue(millis); sem.release(); cdl.countDown(); } }).start(); } spawnProgressCheckThread(log, duration, checkCycle, cdl); cdl.await(); } } catch (final ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); } }
From source file:di.uniba.it.tee2.wiki.Wikidump2IndexMT.java
/** * language xml_dump output_dir n_thread encoding * * @param args the command line arguments *///from w w w .j a v a 2 s . com public static void main(String[] args) { try { CommandLine cmd = cmdParser.parse(options, args); if (cmd.hasOption("l") && cmd.hasOption("d") && cmd.hasOption("o")) { encoding = cmd.getOptionValue("e", "UTF-8"); minTextLegth = Integer.parseInt(cmd.getOptionValue("m", "4000")); /*if (cmd.hasOption("p")) { pageLimit = Integer.parseInt(cmd.getOptionValue("p")); }*/ int nt = Integer.parseInt(cmd.getOptionValue("n", "2")); Wikidump2IndexMT builder = new Wikidump2IndexMT(); builder.init(cmd.getOptionValue("l"), cmd.getOptionValue("o"), nt); //attach a shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { try { Wikidump2IndexMT.tee.close(); } catch (Exception ex) { Logger.getLogger(Wikidump2IndexMT.class.getName()).log(Level.SEVERE, null, ex); } } })); builder.build(cmd.getOptionValue("d"), cmd.getOptionValue("l")); } else { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("Index Wikipedia dump (multi threads)", options, true); } } catch (Exception ex) { Logger.getLogger(Wikidump2IndexMT.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:es.tid.fiware.fiwareconnectors.cygnus.nodes.CygnusApplication.java
/** * Main application to be run when this CygnusApplication is invoked. The only differences with the original one * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in * the command line.// w ww .j a v a 2 s . c om * @param args */ public static void main(String[] args) { try { Options options = new Options(); Option option = new Option("n", "name", true, "the name of this agent"); option.setRequired(true); options.addOption(option); option = new Option("f", "conf-file", true, "specify a conf file"); option.setRequired(true); options.addOption(option); option = new Option(null, "no-reload-conf", false, "do not reload " + "conf file if changed"); options.addOption(option); option = new Option("h", "help", false, "display help text"); options.addOption(option); option = new Option("p", "mgmt-if-port", true, "the management interface port"); option.setRequired(false); options.addOption(option); CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); File configurationFile = new File(commandLine.getOptionValue('f')); String agentName = commandLine.getOptionValue('n'); boolean reload = !commandLine.hasOption("no-reload-conf"); if (commandLine.hasOption('h')) { new HelpFormatter().printHelp("flume-ng agent", options, true); return; } // if int mgmtIfPort = 8081; // default value if (commandLine.hasOption('p')) { mgmtIfPort = new Integer(commandLine.getOptionValue('p')).intValue(); } // if // the following is to ensure that by default the agent will fail on startup if the file does not exist if (!configurationFile.exists()) { // if command line invocation, then need to fail fast if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) { String path = configurationFile.getPath(); try { path = configurationFile.getCanonicalPath(); } catch (IOException ex) { logger.error("Failed to read canonical path for file: " + path, ex); } // try catch throw new ParseException("The specified configuration file does not exist: " + path); } // if } // if List<LifecycleAware> components = Lists.newArrayList(); CygnusApplication application; if (reload) { EventBus eventBus = new EventBus(agentName + "-event-bus"); PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider( agentName, configurationFile, eventBus, 30); components.add(configurationProvider); application = new CygnusApplication(components, mgmtIfPort); eventBus.register(application); } else { PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider( agentName, configurationFile); application = new CygnusApplication(mgmtIfPort); application.handleConfigurationEvent(configurationProvider.getConfiguration()); } // if else application.start(); final CygnusApplication appReference = application; Runtime.getRuntime().addShutdownHook(new Thread("agent-shutdown-hook") { @Override public void run() { appReference.stop(); } // run }); } catch (Exception e) { logger.error("A fatal error occurred while running. Exception follows.", e); } // try catch }
From source file:com.mockey.runner.JettyRunner.java
public static void main(String[] args) throws Exception { if (args == null) args = new String[0]; // Initialize the argument parser SimpleJSAP jsap = new SimpleJSAP("java -jar Mockey.jar", "Starts a Jetty server running Mockey"); jsap.registerParameter(new FlaggedOption(ARG_PORT, JSAP.INTEGER_PARSER, "8080", JSAP.NOT_REQUIRED, 'p', ARG_PORT, "port to run Jetty on")); jsap.registerParameter(new FlaggedOption(BSC.FILE, JSAP.STRING_PARSER, MockeyXmlFileManager.MOCK_SERVICE_DEFINITION, JSAP.NOT_REQUIRED, 'f', BSC.FILE, "Relative path to a mockey-definitions file to initialize Mockey, relative to where you're starting Mockey")); jsap.registerParameter(new FlaggedOption(BSC.URL, JSAP.STRING_PARSER, "", JSAP.NOT_REQUIRED, 'u', BSC.URL, "URL to a mockey-definitions file to initialize Mockey")); jsap.registerParameter(new FlaggedOption(BSC.TRANSIENT, JSAP.BOOLEAN_PARSER, "true", JSAP.NOT_REQUIRED, 't', BSC.TRANSIENT, "Read only mode if set to true, no updates are made to the file system.")); jsap.registerParameter(new FlaggedOption(BSC.FILTERTAG, JSAP.STRING_PARSER, "", JSAP.NOT_REQUIRED, 'F', BSC.FILTERTAG,/*from w ww. j av a2 s . c o m*/ "Filter tag for services and scenarios, useful for 'only use information with this tag'. ")); jsap.registerParameter( new Switch(ARG_QUIET, 'q', "quiet", "Runs in quiet mode and does not loads the browser")); jsap.registerParameter(new FlaggedOption(BSC.HEADLESS, JSAP.BOOLEAN_PARSER, "false", JSAP.NOT_REQUIRED, 'H', BSC.HEADLESS, "Headless flag. Default is 'false'. Set to 'true' if you do not want Mockey to spawn a browser thread upon startup.")); // parse the command line options JSAPResult config = jsap.parse(args); // Bail out if they asked for the --help if (jsap.messagePrinted()) { System.exit(1); } // Construct the new arguments for jetty-runner int port = config.getInt(ARG_PORT); boolean transientState = true; // We can add more things to the quite mode. For now we are just not launching browser boolean isQuiteMode = false; try { transientState = config.getBoolean(BSC.TRANSIENT); isQuiteMode = config.getBoolean(ARG_QUIET); } catch (Exception e) { // } // Initialize Log4J file roller appender. StartUpServlet.getDebugFile(); InputStream log4jInputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("WEB-INF/log4j.properties"); Properties log4JProperties = new Properties(); log4JProperties.load(log4jInputStream); PropertyConfigurator.configure(log4JProperties); Server server = new Server(port); WebAppContext webapp = new WebAppContext(); webapp.setContextPath("/"); webapp.setConfigurations(new Configuration[] { new PreCompiledJspConfiguration() }); ClassPathResourceHandler resourceHandler = new ClassPathResourceHandler(); resourceHandler.setContextPath("/"); ContextHandlerCollection contexts = new ContextHandlerCollection(); contexts.addHandler(resourceHandler); contexts.addHandler(webapp); server.setHandler(contexts); server.start(); // Construct the arguments for Mockey String file = String.valueOf(config.getString(BSC.FILE)); String url = String.valueOf(config.getString(BSC.URL)); String filterTag = config.getString(BSC.FILTERTAG); String fTagParam = ""; boolean headless = config.getBoolean(BSC.HEADLESS); if (filterTag != null) { fTagParam = "&" + BSC.FILTERTAG + "=" + URLEncoder.encode(filterTag, "UTF-8"); } // Startup displays a big message and URL redirects after x seconds. // Snazzy. String initUrl = HOMEURL; // BUT...if a file is defined, (which it *should*), // then let's initialize with it instead. if (url != null && url.trim().length() > 0) { URLEncoder.encode(initUrl, "UTF-8"); initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&" + BSC.URL + "=" + URLEncoder.encode(url, "UTF-8") + fTagParam; } else if (file != null && file.trim().length() > 0) { URLEncoder.encode(initUrl, "UTF-8"); initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&" + BSC.FILE + "=" + URLEncoder.encode(file, "UTF-8") + fTagParam; } else { initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&" + BSC.FILE + "=" + URLEncoder.encode(MockeyXmlFileManager.MOCK_SERVICE_DEFINITION, "UTF-8") + fTagParam; } if (!(headless || isQuiteMode)) { new Thread(new BrowserThread("http://127.0.0.1", String.valueOf(port), initUrl, 0)).start(); server.join(); } else { initializeMockey(new URL("http://127.0.0.1" + ":" + String.valueOf(port) + initUrl)); } }
From source file:com.cloud.test.stress.StressTestDirectAttach.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8092"; String devPort = "8080"; String apiUrl = "/client/api"; try {/*from www . j av a 2 s . c o m*/ // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-dp")) { devPort = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-a")) { accountName = iter.next(); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever // cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } if (arg.equals("-w")) { wait = Integer.parseInt(iter.next()); } if (arg.equals("-z")) { zoneId = iter.next(); } if (arg.equals("-so")) { serviceOfferingId = iter.next(); } } final String server = host + ":" + port + "/"; final String developerServer = host + ":" + devPort + apiUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { @Override public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); username = Math.abs(ran.nextInt()) + "-user"; NDC.push(username); s_logger.info("Starting test for the user " + username); int response = executeDeployment(server, developerServer, username); boolean success = false; String reason = null; if (response == 200) { success = true; if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 // seconds so // the windows VM // can boot up and do a sys prep. s_logger.info("Begin Linux SSH test for account " + _account.get()); reason = sshTest(_linuxIP.get(), _linuxPassword.get()); if (reason == null) { s_logger.info( "Linux SSH test successful for account " + _account.get()); } } if (reason == null) { if (internet) { s_logger.info( "Windows SSH test successful for account " + _account.get()); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (usageIterator >= numThreads) { int eventsAndBillingResponseCode = executeEventsAndBilling(server, developerServer); s_logger.info( "events and usage records command finished with response code: " + eventsAndBillingResponseCode); usageIterator = 1; } else { s_logger.info( "Skipping events and usage records for this user: usageIterator " + usageIterator + " and number of Threads " + numThreads); usageIterator++; } if ((users == null) && (accountName == null)) { s_logger.info("Sending cleanup command"); int cleanupResponseCode = executeCleanup(server, developerServer, username); s_logger.info("cleanup command finished with response code: " + cleanupResponseCode); success = (cleanupResponseCode == 200); } else { s_logger.info("Sending stop DomR / destroy VM command"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop(destroy) command finished with response code: " + stopResponseCode); success = (stopResponseCode == 200); } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("SSH test failed for account " + _account.get() + "with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info( "stop command finished with response code: " + stopResponseCode); success = false; // since the SSH test // failed, mark the // whole test as // failure } } else { // Just stop but don't destroy the // VMs/Routers s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop command finished with response code: " + stopResponseCode); success = false; // since the deploy test // failed, mark the // whole test as failure } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } s_logger.info("Sleeping for " + wait + " seconds before starting next iteration"); Thread.sleep(wait); } catch (Exception e) { s_logger.warn("Error in thread", e); try { int stopResponseCode = executeStop(server, developerServer, username); s_logger.info("stop response code: " + stopResponseCode); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:net.fender.crypto.CryptoUtil.java
/** * Verify thread safety of org.apache.commons.codec.binary.Base64. * //from w ww .java2 s. c o m * @TODO Move this to JUnit test case. * @param args * @throws Exception */ public static void main(String[] args) throws Exception { byte[][] strings = new byte[10000][]; // generate a bunch of random "strings" for (int i = 0; i < strings.length; i++) { // generate a random "string" 32 - 64 bytes long byte[] bytes = new byte[random.nextInt(32) + 32]; random.nextBytes(bytes); strings[i] = bytes; } Runner runner = new Runner(strings); for (int i = 0; i < 100; i++) { Thread t = new Thread(runner); t.start(); } }
From source file:com.edduarte.protbox.Protbox.java
public static void main(String... args) { // activate debug / verbose mode if (args.length != 0) { List<String> argsList = Arrays.asList(args); if (argsList.contains("-v")) { Constants.verbose = true;/*from www. j av a 2s . c o m*/ } } // use System's look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { // If the System's look and feel is not obtainable, continue execution with JRE look and feel } // check this is a single instance try { new ServerSocket(1882); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Another instance of Protbox is already running.\n" + "Please close the other instance first.", "Protbox already running", JOptionPane.ERROR_MESSAGE); System.exit(1); } // check if System Tray is supported by this operative system if (!SystemTray.isSupported()) { JOptionPane.showMessageDialog(null, "Your operative system does not support system tray functionality.\n" + "Please try running Protbox on another operative system.", "System tray not supported", JOptionPane.ERROR_MESSAGE); System.exit(1); } // add PKCS11 providers FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")), HiddenFileFilter.VISIBLE); File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter); if (providersConfigFiles != null) { for (File f : providersConfigFiles) { try { List<String> lines = FileUtils.readLines(f); String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get(); lines.remove(aliasLine); String alias = aliasLine.split("=")[1].trim(); StringBuilder sb = new StringBuilder(); for (String s : lines) { sb.append(s); sb.append("\n"); } Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString()))); Security.addProvider(p); pkcs11Providers.put(p.getName(), alias); } catch (IOException | ProviderException ex) { if (ex.getMessage().equals("Initialization failed")) { ex.printStackTrace(); String s = "The following error occurred:\n" + ex.getCause().getMessage() + "\n\nIn addition, make sure you have " + "an available smart card reader connected before opening the application."; JTextArea textArea = new JTextArea(s); textArea.setColumns(60); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setSize(textArea.getPreferredSize().width, 1); JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); System.exit(1); } else { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Error while setting up PKCS11 provider from configuration file " + f.getName() + ".\n" + ex.getMessage(), "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); } } } } // adds a shutdown hook to save instantiated directories into files when the application is being closed Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit)); // get system tray and run tray applet tray = SystemTray.getSystemTray(); SwingUtilities.invokeLater(() -> { if (Constants.verbose) { logger.info("Starting application"); } //Start a new TrayApplet object trayApplet = TrayApplet.getInstance(); }); // prompts the user to choose which provider to use ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> { // loads eID token eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> { user = returnedUser; certificateData = returnedCertificateData; // gets a password to use on the saved registry files (for loading and saving) final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null); consumerHolder.set(password -> { registriesPasswordKey = password; try { // if there are serialized files, load them if they can be decoded by this user's private key final List<SavedRegistry> serializedDirectories = new ArrayList<>(); if (Constants.verbose) { logger.info("Reading serialized registry files..."); } File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles(); if (registryFileList != null) { for (File f : registryFileList) { if (f.isFile()) { byte[] data = FileUtils.readFileToByteArray(f); try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey); byte[] registryDecryptedData = cipher.doFinal(data); serializedDirectories.add(new SavedRegistry(f, registryDecryptedData)); } catch (GeneralSecurityException ex) { if (Constants.verbose) { logger.info("Inserted Password does not correspond to " + f.getName()); } } } } } // if there were no serialized directories, show NewDirectory window to configure the first folder if (serializedDirectories.isEmpty() || registryFileList == null) { if (Constants.verbose) { logger.info("No registry files were found: running app as first time!"); } NewRegistryWindow.start(true); } else { // there were serialized directories loadRegistry(serializedDirectories); trayApplet.repaint(); showTrayApplet(); } } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException | ProtboxException ex) { JOptionPane.showMessageDialog(null, "The inserted password was invalid! Please try another one!", "Invalid password!", JOptionPane.ERROR_MESSAGE); insertPassword(consumerHolder.get()); } }); insertPassword(consumerHolder.get()); }); }); }
From source file:ai.susi.geo.GeoJsonReader.java
public static void main(String[] args) { File f = new File(args[0]); try {//from ww w .ja va 2 s.co m GeoJsonReader reader = new GeoJsonReader(new BufferedInputStream(new FileInputStream(f)), Runtime.getRuntime().availableProcessors() * 2 + 1); new Thread(reader).start(); Feature feature; while ((feature = reader.take()) != POISON_FEATURE) System.out.println(feature.toString()); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }
From source file:org.opencastproject.loadtest.engage.Main.java
/** Runs the load testing against an engage server. **/ public static void main(String[] args) throws Exception { // Create the default settings for the GUI interaction such as user/pass and field names. GuiSettings guiSettings = new GuiSettings(); // Set the default browser to use as Firefox. BrowserToUse browserToUse = BrowserToUse.Firefox; // Create command line options. Options options = createOptions();//from w ww . jav a 2 s . com // Parse the command line options. CommandLineParser parser = new PosixParser(); CommandLine line = null; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("Parsing commandline failed: " + e.getMessage()); System.exit(1); } if (line.hasOption(ENGAGE_URL_KEY)) { engageServerURL = line.getOptionValue(ENGAGE_URL_KEY); } if (line.hasOption(DIGEST_USERNAME_KEY)) { digestUsername = line.getOptionValue(DIGEST_USERNAME_KEY); } if (line.hasOption(DIGEST_PASSWORD_KEY)) { digestPassword = line.getOptionValue(DIGEST_PASSWORD_KEY); } // Get settings for interacting with the gui. if (line.hasOption(GUI_USERNAME_KEY)) { guiSettings.setUsername(line.getOptionValue(GUI_USERNAME_KEY)); } if (line.hasOption(GUI_PASSWORD_KEY)) { guiSettings.setPassword(line.getOptionValue(GUI_PASSWORD_KEY)); } if (line.hasOption(GUI_USERNAME_FIELDNAME_KEY)) { guiSettings.setUsernameFieldName(line.getOptionValue(GUI_USERNAME_FIELDNAME_KEY)); } if (line.hasOption(GUI_PASSWORD_FIELDNAME_KEY)) { guiSettings.setPasswordFieldName(line.getOptionValue(GUI_PASSWORD_FIELDNAME_KEY)); } if (line.hasOption(BROWSER_NUMBER_KEY)) { numberOfBrowsers = Integer.parseInt(line.getOptionValue(BROWSER_NUMBER_KEY)); } if (line.hasOption(WATCH_TIME_KEY)) { timeToWatchVideo = Integer.parseInt(line.getOptionValue(WATCH_TIME_KEY)); } if (line.hasOption(WITH_CHROME_KEY)) { browserToUse = BrowserToUse.Chrome; } if (line.hasOption(WITH_IE_KEY)) { browserToUse = BrowserToUse.IE; } if (line.hasOption(WITH_SAFARI_KEY)) { browserToUse = BrowserToUse.Safari; } if (line.hasOption(WITH_FIREFOX_KEY)) { browserToUse = BrowserToUse.Firefox; } if (line.hasOption(HELP_KEY)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar matterhorn-load-test-engage-<version>-jar-with-dependencies.jar>", options); System.exit(0); } LinkedList<String> episodeList = getListOfEpisodes(); if (episodeList == null || episodeList.size() <= 0) { logger.error("You need at least one episode in the engage player to run this load test. "); System.exit(0); } // Create browsers to run test. LoadTestEngage loadTestEngage = null; Thread thread = null; for (int i = 0; i < numberOfBrowsers; i++) { loadTestEngage = new LoadTestEngage("Browser " + i, engageServerURL, episodeList, timeToWatchVideo, guiSettings, browserToUse); thread = new Thread(loadTestEngage); thread.start(); } }