List of usage examples for java.lang Thread currentThread
@HotSpotIntrinsicCandidate public static native Thread currentThread();
From source file:org.stem.ClusterManagerDaemon.java
public static void main(String[] args) throws InterruptedException { environmentDetect();/* w w w . j ava 2s . c om*/ ClusterManagerDaemon daemon = new ClusterManagerDaemon(); daemon.start(); Thread.currentThread().join(); }
From source file:com.image32.demo.simpleapi.SimpleApiDemo.java
final public static void main(String[] args) { me = new SimpleApiDemo(); me.contentHandlers = new ContentHandler(); //load configurations try {//from w w w.j a v a 2 s . com Properties prop = new Properties(); InputStream input = SimpleApiDemo.class.getResourceAsStream("/demoConfig.properties"); // load a properties file prop.load(input); image32ApiClientId = prop.getProperty("image32ApiClientId"); image32ApiSecrect = prop.getProperty("image32ApiSecrect"); image32ApiAuthUrl = prop.getProperty("image32ApiAuthUrl"); image32ApiGetStudiesUrl = prop.getProperty("image32ApiGetStudiesUrl"); demoDataFile = prop.getProperty("demoDataFile"); input.close(); } catch (Exception ex) { logger.info("No configuration found."); System.exit(1); } // test port availability while (!checkPortAvailablity(port)) { if (port > 8090) { logger.info("Port is not available. Exiting..."); System.exit(1); } port++; } ; // run server server = new Server(port); HashSessionIdManager hashSessionIdManager = new HashSessionIdManager(); server.setSessionIdManager(hashSessionIdManager); WebAppContext homecontext = new WebAppContext(); homecontext.setContextPath("/home"); ResourceCollection resources = new ResourceCollection(new String[] { "site" }); homecontext.setBaseResource(resources); HashSessionManager manager = new HashSessionManager(); manager.setSecureCookies(true); SessionHandler sessionHandler = new SessionHandler(manager); sessionHandler.setHandler(me.contentHandlers); ContextHandler context = new ContextHandler(); context.setContextPath("/app"); context.setResourceBase("."); context.setClassLoader(Thread.currentThread().getContextClassLoader()); context.setHandler(sessionHandler); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { homecontext, context }); server.setHandler(handlers); try { server.start(); logger.info("Server started on port " + port); logger.info("Please access this demo from browser with this url: http://localhost:" + port); if (Desktop.isDesktopSupported()) Desktop.getDesktop().browse(new URI("http://localhost:" + port + "/home")); server.join(); } catch (Exception exception) { logger.error(exception.getMessage()); } System.exit(1); }
From source file:LauncherBootstrap.java
/** * The main method./*from w w w . j a v a 2s.co m*/ * * @param args command line arguments */ public static void main(String[] args) { try { // Try to find the LAUNCHER_JAR_FILE_NAME file in the class // loader's and JVM's classpath. URL coreURL = LauncherBootstrap.class.getResource("/" + LauncherBootstrap.LAUNCHER_JAR_FILE_NAME); if (coreURL == null) throw new FileNotFoundException(LauncherBootstrap.LAUNCHER_JAR_FILE_NAME); // Coerce the coreURL's directory into a file File coreDir = new File(URLDecoder.decode(coreURL.getFile())).getCanonicalFile().getParentFile(); // Try to find the LAUNCHER_PROPS_FILE_NAME file in the same // directory as this class File propsFile = new File(coreDir, LauncherBootstrap.LAUNCHER_PROPS_FILE_NAME); if (!propsFile.canRead()) throw new FileNotFoundException(propsFile.getPath()); // Load the properties in the LAUNCHER_PROPS_FILE_NAME Properties props = new Properties(); FileInputStream fis = new FileInputStream(propsFile); props.load(fis); fis.close(); // Create a class loader that contains the Launcher, Ant, and // JAXP classes. URL[] antURLs = LauncherBootstrap .fileListToURLs((String) props.get(LauncherBootstrap.ANT_CLASSPATH_PROP_NAME)); URL[] urls = new URL[1 + antURLs.length]; urls[0] = coreURL; for (int i = 0; i < antURLs.length; i++) urls[i + 1] = antURLs[i]; ClassLoader parentLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader loader = null; if (parentLoader != null) loader = new URLClassLoader(urls, parentLoader); else loader = new URLClassLoader(urls); // Load the LAUNCHER_MAIN_CLASS_NAME class launcherClass = loader.loadClass(LAUNCHER_MAIN_CLASS_NAME); // Get the LAUNCHER_MAIN_CLASS_NAME class' getLocalizedString() // method as we need it for printing the usage statement Method getLocalizedStringMethod = launcherClass.getDeclaredMethod("getLocalizedString", new Class[] { String.class }); // Invoke the LAUNCHER_MAIN_CLASS_NAME class' start() method. // If the ant.class.path property is not set correctly in the // LAUNCHER_PROPS_FILE_NAME, this will throw an exception. Method startMethod = launcherClass.getDeclaredMethod("start", new Class[] { String[].class }); int returnValue = ((Integer) startMethod.invoke(null, new Object[] { args })).intValue(); // Always exit cleanly after invoking the start() method System.exit(returnValue); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
From source file:com.glaf.core.util.AnnotationUtils.java
public static void main(String[] args) throws Exception { System.out.println(System.getProperty("java.class.path")); long start = System.currentTimeMillis(); Collection<String> entities = AnnotationUtils.findMapper("com.glaf"); long time = System.currentTimeMillis() - start; for (String str : entities) { System.out.println(str);//from w w w . ja va 2 s . c o m } System.out.println("time:" + time); URL[] urls = ClasspathUrlFinder.findResourceBases("com/glaf/package.properties", Thread.currentThread().getContextClassLoader()); for (URL url2 : urls) { logger.debug("->scan url:" + url2.toURI().toString()); } }
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 ww w . j av a 2 s. com*/ "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:friendsandfollowers.FilesThreaderFriendsIDs.java
public static void main(String[] args) throws InterruptedException { // Check how many arguments were passed in if ((args == null) || (args.length < 4)) { System.err.println("4 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'INPUT: /path/to/files/'"); System.err.println("Second: String 'OUTPUT: /output/path/'"); System.err.println("Third: (int) Total Number Of Jobs"); System.err.println("Fourth: (int) Number of seconds to pause"); System.err//from w ww. j ava 2 s . c o m .println("Fifth: (int) Number of ids to fetch. " + "Provide number which increment by 5000 eg " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 2 75000"); System.exit(-1); } // to write output in a file ThreadPrintStream.replaceSystemOut(); try { INPUT = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } try { OUTPUT = StringEscapeUtils.escapeJava(args[1]); } catch (Exception e) { System.err.println("Argument" + args[1] + " must be an String."); System.exit(-1); } try { TOTAL_JOBS_STR = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an integer."); System.exit(-1); } try { PAUSE_STR = StringEscapeUtils.escapeJava(args[3]); } catch (Exception e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } if (args.length == 5) { try { IDS_TO_FETCH = StringEscapeUtils.escapeJava(args[4]); } catch (Exception e) { System.err.println("Argument" + args[4] + " must be an integer."); System.exit(-1); } } try { PAUSE = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } try { TOTAL_JOBS = Integer.parseInt(TOTAL_JOBS_STR); } catch (NumberFormatException e) { System.err.println("Argument" + TOTAL_JOBS_STR + " must be an integer."); System.exit(-1); } System.out.println("Going to launch jobs. " + "Please see logs files to track jobs."); ExecutorService threadPool = Executors.newFixedThreadPool(TOTAL_JOBS); for (int i = 0; i < TOTAL_JOBS; i++) { final String JOB_NO = Integer.toString(i); threadPool.submit(new Runnable() { public void run() { try { // Creating a text file where System.out.println() // will send its output for this thread. String name = Thread.currentThread().getName(); FileOutputStream fos = null; try { fos = new FileOutputStream(name + "-logs.txt"); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(0); } // Create a PrintStream that will write to the new file. PrintStream stream = new PrintStream(new BufferedOutputStream(fos)); // Install the PrintStream to be used as // System.out for this thread. ((ThreadPrintStream) System.out).setThreadOut(stream); // Output three messages to System.out. System.out.println(name); System.out.println(); System.out.println(); FilesThreaderFriendsIDs.execTask(INPUT, OUTPUT, TOTAL_JOBS_STR, JOB_NO, PAUSE_STR, IDS_TO_FETCH); } catch (IOException | ClassNotFoundException | SQLException | JSONException e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } }); helpers.pause(PAUSE); } threadPool.shutdown(); }
From source file:friendsandfollowers.FilesThreaderFollowersIDs.java
public static void main(String[] args) throws InterruptedException { // Check how many arguments were passed in if ((args == null) || (args.length < 4)) { System.err.println("4 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'INPUT: /path/to/files/'"); System.err.println("Second: String 'OUTPUT: /output/path/'"); System.err.println("Third: (int) Total Number Of Jobs"); System.err.println("Fourth: (int) Number of seconds to pause"); System.err//from w w w . j av a 2 s .com .println("Fifth: (int) Number of ids to fetch. " + "Provide number which increment by 5000 eg " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 2 75000"); System.exit(-1); } // to write output in a file ThreadPrintStream.replaceSystemOut(); try { INPUT = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } try { OUTPUT = StringEscapeUtils.escapeJava(args[1]); } catch (Exception e) { System.err.println("Argument" + args[1] + " must be an String."); System.exit(-1); } try { TOTAL_JOBS_STR = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an integer."); System.exit(-1); } try { PAUSE_STR = StringEscapeUtils.escapeJava(args[3]); } catch (Exception e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } if (args.length == 5) { try { IDS_TO_FETCH = StringEscapeUtils.escapeJava(args[4]); } catch (Exception e) { System.err.println("Argument" + args[4] + " must be an integer."); System.exit(-1); } } try { PAUSE = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } try { TOTAL_JOBS = Integer.parseInt(TOTAL_JOBS_STR); } catch (NumberFormatException e) { System.err.println("Argument" + TOTAL_JOBS_STR + " must be an integer."); System.exit(-1); } System.out.println("Going to launch jobs. " + "Please see logs files to track jobs."); ExecutorService threadPool = Executors.newFixedThreadPool(TOTAL_JOBS); for (int i = 0; i < TOTAL_JOBS; i++) { final String JOB_NO = Integer.toString(i); threadPool.submit(new Runnable() { public void run() { try { // Creating a text file where System.out.println() // will send its output for this thread. String name = Thread.currentThread().getName(); FileOutputStream fos = null; try { fos = new FileOutputStream(name + "-logs.txt"); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(0); } // Create a PrintStream that will write to the new file. PrintStream stream = new PrintStream(new BufferedOutputStream(fos)); // Install the PrintStream to be used as // System.out for this thread. ((ThreadPrintStream) System.out).setThreadOut(stream); // Output three messages to System.out. System.out.println(name); System.out.println(); System.out.println(); FilesThreaderFollowersIDs.execTask(INPUT, OUTPUT, TOTAL_JOBS_STR, JOB_NO, PAUSE_STR, IDS_TO_FETCH); } catch (IOException | ClassNotFoundException | SQLException | JSONException e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } }); helpers.pause(PAUSE); } threadPool.shutdown(); }
From source file:com.ikanow.aleph2.analytics.spark.assets.SparkScalaInterpreterTopology.java
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { final SetOnce<IBucketLogger> logger = new SetOnce<>(); try {/*from w w w .j a v a2 s . c om*/ final Tuple2<IAnalyticsContext, Optional<ProcessingTestSpecBean>> aleph2_tuple = SparkTechnologyUtils .initializeAleph2(args); final IAnalyticsContext context = aleph2_tuple._1(); final Optional<ProcessingTestSpecBean> test_spec = aleph2_tuple._2(); logger.set(context.getLogger(context.getBucket())); // Optional: make really really sure it exists after the specified timeout SparkTechnologyUtils.registerTestTimeout(test_spec, () -> { System.exit(0); }); //INFO: System.out.println("Starting SparkScalaInterpreterTopology logging=" + logger.optional().isPresent()); logger.optional().ifPresent(l -> { l.inefficientLog(Level.INFO, ErrorUtils.buildSuccessMessage("SparkScalaInterpreterTopology", "main", "Starting SparkScalaInterpreterTopology.{0}", Optionals.of(() -> context.getJob().get().name()).orElse("no_name"))); }); final SparkTopologyConfigBean job_config = BeanTemplateUtils .from(context.getJob().map(job -> job.config()).orElse(Collections.emptyMap()), SparkTopologyConfigBean.class) .get(); final String scala_script = Optional.ofNullable(job_config.script()).orElse(""); final String wrapper_script = IOUtils.toString( SparkScalaInterpreterTopology.class.getClassLoader().getResourceAsStream("ScriptRunner.scala"), "UTF-8"); final String to_compile = wrapper_script.replace("USER_SCRIPT", scala_script); final SparkCompilerService scs = new SparkCompilerService(); final Tuple2<ClassLoader, Object> o = scs.buildClass(to_compile, "ScriptRunner", logger.optional()); Thread.currentThread().setContextClassLoader(o._1()); test_spec.ifPresent(spec -> System.out .println("OPTIONS: test_spec = " + BeanTemplateUtils.toJson(spec).toString())); SparkConf spark_context = new SparkConf().setAppName("SparkPassthroughTopology"); final long streaming_batch_interval = (long) spark_context .getInt(SparkTopologyConfigBean.STREAMING_BATCH_INTERVAL, 10); // MAIN PROCESSING final Method m = o._2().getClass().getMethod("runScript", SparkScriptEngine.class); //DEBUG //final boolean test_mode = test_spec.isPresent(); // (serializable thing i can pass into the map) boolean is_streaming = context.getJob().map(j -> j.analytic_type()) .map(t -> MasterEnrichmentType.streaming == t).orElse(false); final Either<JavaSparkContext, JavaStreamingContext> jsc = Lambdas.get(() -> { return is_streaming ? Either.<JavaSparkContext, JavaStreamingContext>right(new JavaStreamingContext( spark_context, Durations.seconds(streaming_batch_interval))) : Either.<JavaSparkContext, JavaStreamingContext>left(new JavaSparkContext(spark_context)); }); try { final JavaSparkContext jsc_batch = jsc.either(l -> l, r -> r.sparkContext()); final Multimap<String, JavaPairRDD<Object, Tuple2<Long, IBatchRecord>>> inputs = SparkTechnologyUtils .buildBatchSparkInputs(context, test_spec, jsc_batch, Collections.emptySet()); final Multimap<String, JavaPairDStream<String, Tuple2<Long, IBatchRecord>>> streaming_inputs = jsc .<Multimap<String, JavaPairDStream<String, Tuple2<Long, IBatchRecord>>>>either( l -> HashMultimap .<String, JavaPairDStream<String, Tuple2<Long, IBatchRecord>>>create(), r -> SparkTechnologyUtils.buildStreamingSparkInputs(context, test_spec, r, Collections.emptySet())); final SparkScriptEngine script_engine_bridge = new SparkScriptEngine(context, inputs, streaming_inputs, test_spec, jsc_batch, jsc.either(l -> null, r -> r), job_config); // Add driver and generated JARs to path: jsc_batch.addJar(LiveInjector.findPathJar(o._2().getClass())); m.invoke(o._2(), script_engine_bridge); jsc.either(l -> { l.stop(); return null; }, r -> { r.stop(); return null; }); logger.optional().ifPresent(l -> { l.inefficientLog(Level.INFO, ErrorUtils.buildSuccessMessage("SparkScalaInterpreterTopology", "main", "Stopping SparkScalaInterpreterTopology.{0}", Optionals.of(() -> context.getJob().get().name()).orElse("no_name"))); }); //INFO: System.out.println("Finished interpreter"); } finally { jsc.either(l -> { l.close(); return null; }, r -> { r.close(); return null; }); } logger.optional().ifPresent(Lambdas.wrap_consumer_u(l -> l.flush().get(10, TimeUnit.SECONDS))); } catch (Throwable t) { logger.optional().ifPresent(l -> { l.inefficientLog(Level.ERROR, ErrorUtils.buildSuccessMessage("SparkScalaInterpreterTopology", "main", ErrorUtils.getLongForm("Error executing SparkScalaInterpreterTopology.unknown: {0}", t))); }); System.out.println(ErrorUtils.getLongForm("ERROR: {0}", t)); logger.optional().ifPresent(Lambdas.wrap_consumer_u(l -> l.flush().get(10, TimeUnit.SECONDS))); System.exit(-1); } }
From source file:de.uniwue.info6.database.SQLParserTest.java
public static void main(String[] args) throws Exception { String test = "Dies ist ein einfacher Test"; System.out.println(StringTools.forgetOneWord(test)); System.exit(0);/*from w w w .ja v a 2 s . c om*/ // SimpleTupel<String, Integer> test1 = new SimpleTupel<String, Integer>("test1", 1); // SimpleTupel<String, Integer> test2 = new SimpleTupel<String, Integer>("test1", 12); // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>(); // test.add(test1); // System.out.println(test1.equals(test2)); // System.exit(0); final boolean resetDb = true; // Falls nur nach einer bestimmten Aufgabe gesucht wird final Integer exerciseID = 39; final Integer scenarioID = null; final int threadSize = 1; final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>(); final Long[] performance = new Long[] { 0L, 0L }; // ------------------------------------------------ // final ScenarioDao scenarioDao = new ScenarioDao(); final ExerciseDao exerciseDao = new ExerciseDao(); final ExerciseGroupDao groupDao = new ExerciseGroupDao(); final UserDao userDao = new UserDao(); final ArrayList<Thread> threads = new ArrayList<Thread>(); // ------------------------------------------------ // try { ConnectionManager.offline_instance(); if (resetDb) { Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true); Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true); new GenerateData().resetDB(); ConnectionTools.inst().addSomeTestData(); } } catch (Exception e) { e.printStackTrace(); } // ------------------------------------------------ // final List<Scenario> scenarios = scenarioDao.findAll(); try { // ------------------------------------------------ // String userID; for (int i = 2; i < 100; i++) { userID = "user_" + i; User userToInsert = new User(); userToInsert.setId(userID); userToInsert.setIsAdmin(false); userDao.insertNewInstance(userToInsert); } // ------------------------------------------------ // for (int i = 0; i < threadSize; i++) { Thread thread = new Thread() { public void run() { // ------------------------------------------------ // try { Thread.sleep(new Random().nextInt(30)); } catch (InterruptedException e) { e.printStackTrace(); } // ------------------------------------------------ // User user = userDao.getRandom(); Thread.currentThread().setName(user.getId()); System.err.println( "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n"); // ------------------------------------------------ // for (Scenario scenario : scenarios) { if (scenarioID != null && !scenario.getId().equals(scenarioID)) { continue; } System.out.println(StringUtils.repeat("#", 90)); System.out.println("SCENARIO: " + scenario.getId()); // ------------------------------------------------ // for (ExerciseGroup group : groupDao.findByScenario(scenario)) { System.out.println(StringUtils.repeat("#", 90)); System.out.println("GROUP: " + group.getId()); System.out.println(StringUtils.repeat("#", 90)); List<Exercise> exercises = exerciseDao.findByExGroup(group); // ------------------------------------------------ // for (Exercise exercise : exercises) { if (exerciseID != null && !exercise.getId().equals(exerciseID)) { continue; } long startTime = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { String userID = "user_" + new Random().nextInt(100000); User userToInsert = new User(); userToInsert.setId(userID); userToInsert.setIsAdmin(false); userDao.insertNewInstance(userToInsert); user = userDao.getById(userID); List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise); String solution = solutions.get(0).getQuery(); ExerciseController exc = new ExerciseController().init_debug(scenario, exercise, user); exc.setUserString(solution); String fd = exc.getFeedbackList().get(0).getFeedback(); System.out.println("Used Query: " + solution); if (fd.trim().toLowerCase().equals("bestanden")) { System.out.println(exercise.getId() + ": " + fd); } else { System.err.println(exercise.getId() + ": " + fd + "\n"); } System.out.println(StringUtils.repeat("-", 90)); } long elapsedTime = System.currentTimeMillis() - startTime; // if (i > 5) { // try { // equivalenceLock.lock(performance); // performance[0] += elapsedTime; // performance[1]++; // } catch (Exception e) { // } finally { // equivalenceLock.release(performance); // } // } } } } System.err .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped"); } }; thread.start(); threads.add(thread); } for (Thread thread : threads) { thread.join(); } // try { // equivalenceLock.lock(performance); // long elapsedTime = (performance[0] / performance[1]); // System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000)); // } catch (Exception e) { // } finally { // equivalenceLock.release(performance); // } } finally { } }
From source file:ValidateLicenseHeaders.java
/** * ValidateLicenseHeaders jboss-src-root * //ww w.java 2s . c o m * @param args */ public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].startsWith("-h")) { log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } int rootArg = 0; if (args.length == 2) { if (args[0].startsWith("-add")) addDefaultHeader = true; else { log.severe("Uknown argument: " + args[0]); log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } rootArg = 1; } File jbossSrcRoot = new File(args[rootArg]); if (jbossSrcRoot.exists() == false) { log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath()); System.exit(1); } URL u = Thread.currentThread().getContextClassLoader() .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory"); System.err.println(u); // Load the valid copyright statements for the licenses File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml"); if (licenseInfo.exists() == false) { log.severe("Failed to find the varia/src/etc/license-info.xml under the src root"); System.exit(1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); Document doc = db.parse(licenseInfo); NodeList licenses = doc.getElementsByTagName("license"); for (int i = 0; i < licenses.getLength(); i++) { Element license = (Element) licenses.item(i); String key = license.getAttribute("id"); ArrayList headers = new ArrayList(); licenseHeaders.put(key, headers); NodeList copyrights = license.getElementsByTagName("terms-header"); for (int j = 0; j < copyrights.getLength(); j++) { Element copyright = (Element) copyrights.item(j); copyright.normalize(); String id = copyright.getAttribute("id"); // The id will be blank if there is no id attribute if (id.length() == 0) continue; String text = getElementContent(copyright); if (text == null) continue; // Replace all duplicate whitespace and '*' with a single space text = text.replaceAll("[\\s*]+", " "); if (text.length() == 1) continue; text = text.toLowerCase().trim(); // Replace any copyright date0-date1,date2 with copyright ... text = text.replaceAll(COPYRIGHT_REGEX, "..."); LicenseHeader lh = new LicenseHeader(id, text); headers.add(lh); } } log.fine(licenseHeaders.toString()); File[] files = jbossSrcRoot.listFiles(dotJavaFilter); log.info("Root files count: " + files.length); processSourceFiles(files, 0); log.info("Processed " + totalCount); log.info("Updated jboss headers: " + jbossCount); // Files with no headers details log.info("Files with no headers: " + noheaders.size()); FileWriter fw = new FileWriter("NoHeaders.txt"); for (Iterator iter = noheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // Files with unknown headers details log.info("Files with invalid headers: " + invalidheaders.size()); fw = new FileWriter("InvalidHeaders.txt"); for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // License usage summary log.info("Creating HeadersSummary.txt"); fw = new FileWriter("HeadersSummary.txt"); for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); fw.write("+++ License type=" + key); fw.write('\n'); List list = (List) entry.getValue(); Iterator jiter = list.iterator(); while (jiter.hasNext()) { LicenseHeader lh = (LicenseHeader) jiter.next(); fw.write('\t'); fw.write(lh.id); fw.write(", count="); fw.write("" + lh.count); fw.write('\n'); } } fw.close(); }