List of usage examples for java.util Locale US
Locale US
To view the source code for java.util Locale US.
Click Source Link
From source file:com.db2eshop.launcher.Launcher.java
/** * <p>main.</p>/*w ww.j ava2s .c o m*/ * * @param args an array of {@link java.lang.String} objects. */ public static void main(String[] args) { LocaleContextHolder.setLocale(Locale.US); }
From source file:com.apress.prospringintegration.corespring.i18n.MainI18n.java
public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("ioc_resource_bundles.xml"); String qMessage = ctx.getMessage("queued", null, Locale.US); System.out.println(qMessage); qMessage = ctx.getMessage("queued", null, Locale.UK); System.out.println(qMessage); String filename = "ProSpringIntegration.xml"; MessageSourceResolvable processed = new DefaultMessageSourceResolvable(new String[] { "complete" }, new String[] { filename }, " Your data has been processed!"); String msrQmessage = ctx.getMessage(processed, Locale.FRANCE); System.out.println(msrQmessage); }
From source file:it.acubelab.smaph.learn.GenerateModel.java
public static void main(String[] args) throws Exception { Locale.setDefault(Locale.US); String freebKey = ""; SmaphConfig.setConfigFile("smaph-config.xml"); String bingKey = SmaphConfig.getDefaultBingKey(); WikipediaApiInterface wikiApi = new WikipediaApiInterface("wid.cache", "redirect.cache"); FreebaseApi freebApi = new FreebaseApi(freebKey, "freeb.cache"); double[][] paramsToTest = new double[][] { /*/* w ww . j a v a 2 s . c o m*/ * {0.035, 0.5 }, {0.035, 1 }, {0.035, 4 }, {0.035, 8 }, {0.035, 10 }, * {0.035, 16 }, {0.714, .5 }, {0.714, 1 }, {0.714, 4 }, {0.714, 8 }, * {0.714, 10 }, {0.714, 16 }, {0.9, .5 }, {0.9, 1 }, {0.9, 4 }, {0.9, 8 * }, {0.9, 10 }, {0.9, 16 }, * * { 1.0/15.0, 1 }, { 1.0/27.0, 1 }, */ /* * {0.01, 1}, {0.01, 5}, {0.01, 10}, {0.03, 1}, {0.03, 5}, {0.03, 10}, * {0.044, 1}, {0.044, 5}, {0.044, 10}, {0.06, 1}, {0.06, 5}, {0.06, * 10}, */ { 0.03, 5 }, }; double[][] weightsToTest = new double[][] { /* * { 3, 4 } */ { 3.8, 3 }, { 3.8, 4 }, { 3.8, 5 }, { 3.8, 6 }, { 3.8, 7 }, { 3.8, 8 }, { 3.8, 9 }, { 3.8, 10 }, }; Integer[][] featuresSetsToTest = new Integer[][] { //{ 1, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }, { 1, 2, 3, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }, /* * { 1, 2, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}, */ }; // < -------------------------------------- MIND THIS int wikiSearckTopK = 10; // <--------------------------- String filePrefix = "_ANW";// <--------------------------- WikipediaToFreebase wikiToFreebase = new WikipediaToFreebase("mapdb"); List<ModelConfigurationResult> mcrs = new Vector<>(); for (double editDistanceThr = 0.7; editDistanceThr <= 0.7; editDistanceThr += 0.7) { SmaphAnnotator bingAnnotator = GenerateTrainingAndTest.getDefaultBingAnnotator(wikiApi, wikiToFreebase, editDistanceThr, wikiSearckTopK, bingKey); WATAnnotator.setCache("wikisense.cache"); SmaphAnnotator.setCache(SmaphConfig.getDefaultBingCache()); BinaryExampleGatherer trainEntityFilterGatherer = new BinaryExampleGatherer(); BinaryExampleGatherer testEntityFilterGatherer = new BinaryExampleGatherer(); GenerateTrainingAndTest.gatherExamplesTrainingAndDevel(bingAnnotator, trainEntityFilterGatherer, testEntityFilterGatherer, wikiApi, wikiToFreebase, freebApi); SmaphAnnotator.unSetCache(); BinaryExampleGatherer trainGatherer = trainEntityFilterGatherer; // ////////////// // <---------------------- BinaryExampleGatherer testGatherer = testEntityFilterGatherer; // ////////////// // <---------------------- int count = 0; for (Integer[] ftrToTestArray : featuresSetsToTest) { // double gamma = 1.0 / ftrToTestArray.length; // // <--------------------- MIND THIS // double C = 1;// < -------------------------------------- MIND // THIS for (double[] paramsToTestArray : paramsToTest) { double gamma = paramsToTestArray[0]; double C = paramsToTestArray[1]; for (double[] weightsPosNeg : weightsToTest) { double wPos = weightsPosNeg[0], wNeg = weightsPosNeg[1]; Vector<Integer> features = new Vector<>(Arrays.asList(ftrToTestArray)); Triple<svm_problem, double[], double[]> ftrsMinsMaxs = TuneModel .getScaledTrainProblem(features, trainGatherer); svm_problem trainProblem = ftrsMinsMaxs.getLeft(); String fileBase = getModelFileNameBaseEF(features.toArray(new Integer[0]), wPos, wNeg, editDistanceThr, gamma, C) + filePrefix; /* * String fileBase = getModelFileNameBaseEQF( * features.toArray(new Integer[0]), wPos, wNeg); */// < ------------------------- LibSvmUtils.dumpRanges(ftrsMinsMaxs.getMiddle(), ftrsMinsMaxs.getRight(), fileBase + ".range"); svm_model model = TuneModel.trainModel(wPos, wNeg, features, trainProblem, gamma, C); svm.svm_save_model(fileBase + ".model", model); MetricsResultSet metrics = TuneModel.ParameterTester.computeMetrics(model, TuneModel.getScaledTestProblems(features, testGatherer, ftrsMinsMaxs.getMiddle(), ftrsMinsMaxs.getRight())); int tp = metrics.getGlobalTp(); int fp = metrics.getGlobalFp(); int fn = metrics.getGlobalFn(); float microF1 = metrics.getMicroF1(); float macroF1 = metrics.getMacroF1(); float macroRec = metrics.getMacroRecall(); float macroPrec = metrics.getMacroPrecision(); int totVects = testGatherer.getExamplesCount(); mcrs.add(new ModelConfigurationResult(features, wPos, wNeg, editDistanceThr, tp, fp, fn, totVects - tp - fp - fn, microF1, macroF1, macroRec, macroPrec)); System.err.printf("Trained %d/%d models.%n", ++count, weightsToTest.length * featuresSetsToTest.length * paramsToTest.length); } } } } for (ModelConfigurationResult mcr : mcrs) System.out.printf("%.5f%%\t%.5f%%\t%.5f%%%n", mcr.getMacroPrecision() * 100, mcr.getMacroRecall() * 100, mcr.getMacroF1() * 100); for (double[] weightPosNeg : weightsToTest) System.out.printf("%.5f\t%.5f%n", weightPosNeg[0], weightPosNeg[1]); for (ModelConfigurationResult mcr : mcrs) System.out.println(mcr.getReadable()); for (double[] paramGammaC : paramsToTest) System.out.printf("%.5f\t%.5f%n", paramGammaC[0], paramGammaC[1]); WATAnnotator.flush(); }
From source file:com.github.zhanhb.customdatasource.Application.java
public static void main(String[] args) throws IOException { ApplicationContext context = SpringApplication.run(Application.class, args); if (log.isInfoEnabled() && context instanceof EmbeddedWebApplicationContext) { int port = ((EmbeddedWebApplicationContext) context).getEmbeddedServletContainer().getPort(); String contextPath = context.getApplicationName(); String url = String.format(Locale.US, "http://localhost:%d%s", port, contextPath); String dashes = "------------------------------------------------------------------------"; log.info("Access URLs:\n{}\n\tLocal: \t\t{}\n{}", dashes, url, dashes); }/*w w w. java 2s . c o m*/ }
From source file:fr.ericlab.mabed.app.Main.java
public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); Configuration configuration = new Configuration(); Corpus corpus = new Corpus(configuration); System.out.println("MABED: Mention-Anomaly-Based Event Detection"); if (args.length == 0 || args[0].equals("-help")) { System.out.println("For more information on how to run MABED, see the README.txt file"); } else {//w ww.ja v a 2 s.co m if (args[0].equals("-run")) { try { if (configuration.numberOfThreads > 1) { System.out.println("Running the parallelized implementation with " + configuration.numberOfThreads + " threads (this computer has " + Runtime.getRuntime().availableProcessors() + " available threads)"); } else { System.out.println("Running the centralized implementation"); } corpus.loadCorpus(configuration.numberOfThreads > 1); String output = "MABED: Mention-Anomaly-Based Event Detection\n" + corpus.output + "\n"; System.out.println("-------------------------\n" + Util.getDate() + " MABED is running\n-------------------------"); output += "-------------------------\n" + Util.getDate() + " MABED is running\n-------------------------\n"; System.out.println(Util.getDate() + " Reading parameters:\n - k = " + configuration.k + ", p = " + configuration.p + ", theta = " + configuration.theta + ", sigma = " + configuration.sigma); MABED mabed = new MABED(); if (configuration.numberOfThreads > 1) { output += mabed.applyParallelized(corpus, configuration); } else { output += mabed.applyCentralized(corpus, configuration); } System.out.println( "--------------------\n" + Util.getDate() + " MABED ended\n--------------------"); output += "--------------------\n" + Util.getDate() + " MABED ended\n--------------------\n"; File outputDir = new File("output"); if (!outputDir.isDirectory()) { outputDir.mkdir(); } File textFile = new File("output/MABED.tex"); FileUtils.writeStringToFile(textFile, mabed.events.toLatex(corpus), false); textFile = new File("output/MABED.log"); FileUtils.writeStringToFile(textFile, output, false); mabed.events.printLatex(corpus); } catch (InterruptedException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else { System.out.println("Unknown option '" + args[0] + "'\nType 'java -jar MABED.jar -help' for more information on how to run MABED"); } } }
From source file:generators.ExpressionDeprecationValidator.java
public static void main(final String[] args) throws IOException { ClassicEngineBoot.getInstance().start(); final ExpressionRegistry expressionRegistry = ExpressionRegistry.getInstance(); final ExpressionMetaData[] allExpressions = expressionRegistry.getAllExpressionMetaDatas(); for (int i = 0; i < allExpressions.length; i++) { final ExpressionMetaData expression = allExpressions[i]; if (expression == null) { logger.warn("Null Expression encountered"); continue; }//w w w . j av a2s . co m if (isDeprecated(expression)) { if (expression.isDeprecated() == false) { logger.warn( "Expression code is deprecated, but metadata is not:" + expression.getExpressionType()); } if ("Deprecated Function".equals(expression.getGrouping(Locale.US)) == false) { logger.warn("Expression metadata is not in deprecated group:" + expression.getExpressionType()); } } else { if (expression.isDeprecated() == true) { logger.warn( "Expression metadata is deprecated, but code is not:" + expression.getExpressionType()); } } } }
From source file:com.google.play.developerapi.samples.UpdateListing.java
public static void main(String[] args) { try {/* w ww . j a va2 s .c om*/ Preconditions.checkArgument(!Strings.isNullOrEmpty(ApplicationConfig.PACKAGE_NAME), "ApplicationConfig.PACKAGE_NAME cannot be null or empty!"); // Create the API service. AndroidPublisher service = AndroidPublisherHelper.init(ApplicationConfig.APPLICATION_NAME, ApplicationConfig.SERVICE_ACCOUNT_EMAIL); final Edits edits = service.edits(); // Create an edit to update listing for application. Insert editRequest = edits.insert(ApplicationConfig.PACKAGE_NAME, null /** no content */ ); AppEdit edit = editRequest.execute(); final String editId = edit.getId(); log.info(String.format("Created edit with id: %s", editId)); // Update listing for US version of the application. final Listing newUsListing = new Listing(); newUsListing.setTitle(US_LISTING_TITLE).setFullDescription(US_LISTING_FULL_DESCRIPTION) .setShortDescription(US_LISTING_SHORT_DESCRITPION).setVideo(LISTINGS_PROMO_VIDEO); Update updateUSListingsRequest = edits.listings().update(ApplicationConfig.PACKAGE_NAME, editId, Locale.US.toString(), newUsListing); Listing updatedUsListing = updateUSListingsRequest.execute(); log.info(String.format("Created new US app listing with title: %s", updatedUsListing.getTitle())); // Create and update listing for UK version of the application. final Listing newUkListing = new Listing(); newUkListing.setTitle(UK_LISTING_TITLE).setFullDescription(UK_LISTING_FULL_DESCRIPTION) .setShortDescription(UK_LISTING_SHORT_DESCRITPION).setVideo(LISTINGS_PROMO_VIDEO); Update updateUkListingsRequest = edits.listings().update(ApplicationConfig.PACKAGE_NAME, editId, Locale.UK.toString(), newUkListing); Listing updatedUkListing = updateUkListingsRequest.execute(); log.info(String.format("Created new UK app listing with title: %s", updatedUkListing.getTitle())); // Commit changes for edit. Commit commitRequest = edits.commit(ApplicationConfig.PACKAGE_NAME, editId); AppEdit appEdit = commitRequest.execute(); log.info(String.format("App edit with id %s has been comitted", appEdit.getId())); } catch (IOException | GeneralSecurityException ex) { log.error("Exception was thrown while updating listing", ex); } }
From source file:fr.cs.examples.frames.Frames2.java
public static void main(String[] args) { try {//from w ww . j a va 2s . c om // configure Orekit Autoconfiguration.configureOrekit(); // Considering the following Computing/Measurement date in UTC time scale TimeScale utc = TimeScalesFactory.getUTC(); AbsoluteDate date = new AbsoluteDate(2008, 10, 01, 12, 00, 00.000, utc); // The Center of Gravity frame has its origin at the satellite center of gravity (CoG) // and its axes parallel to EME2000. It is derived from EME2000 frame at any moment // by an unknown transform which depends on the current position and the velocity. // Let's initialize this transform by the identity transform. UpdatableFrame cogFrame = new UpdatableFrame(FramesFactory.getEME2000(), Transform.IDENTITY, "LOF", false); // The satellite frame, with origin also at the CoG, depends on attitude. // For the sake of this tutorial, we consider a simple inertial attitude here Transform cogToSat = new Transform(date, new Rotation(0.6, 0.48, 0, 0.64, false)); Frame satFrame = new Frame(cogFrame, cogToSat, "sat", false); // Finally, the GPS antenna frame can be defined from the satellite frame by 2 transforms: // a translation and a rotation Transform translateGPS = new Transform(date, new Vector3D(0, 0, 1)); Transform rotateGPS = new Transform(date, new Rotation(new Vector3D(0, 1, 3), FastMath.toRadians(10))); Frame gpsFrame = new Frame(satFrame, new Transform(date, translateGPS, rotateGPS), "GPS", false); // Let's get the satellite position and velocity in ITRF as measured by GPS antenna at this moment: final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680); final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231); System.out.format(Locale.US, "GPS antenna position in ITRF: %12.3f %12.3f %12.3f%n", position.getX(), position.getY(), position.getZ()); System.out.format(Locale.US, "GPS antenna velocity in ITRF: %12.7f %12.7f %12.7f%n", velocity.getX(), velocity.getY(), velocity.getZ()); // The transform from GPS frame to ITRF frame at this moment is defined by // a translation and a rotation. The translation is directly provided by the // GPS measurement above. The rotation is extracted from the existing tree, where // we know all rotations are already up to date, even if one translation is still // unknown. We combine the extracted rotation and the measured translation by // applying the rotation first because the position/velocity vector are given in // ITRF frame not in GPS antenna frame: Transform measuredTranslation = new Transform(date, position, velocity); Transform formerTransform = gpsFrame .getTransformTo(FramesFactory.getITRF(IERSConventions.IERS_2010, true), date); Transform preservedRotation = new Transform(date, formerTransform.getRotation(), formerTransform.getRotationRate()); Transform gpsToItrf = new Transform(date, preservedRotation, measuredTranslation); // So we can update the transform from EME2000 to CoG frame cogFrame.updateTransform(gpsFrame, FramesFactory.getITRF(IERSConventions.IERS_2010, true), gpsToItrf, date); // And we can get the position and velocity of satellite CoG in EME2000 frame PVCoordinates origin = PVCoordinates.ZERO; Transform cogToItrf = cogFrame.getTransformTo(FramesFactory.getITRF(IERSConventions.IERS_2010, true), date); PVCoordinates satItrf = cogToItrf.transformPVCoordinates(origin); System.out.format(Locale.US, "Satellite position in ITRF: %12.3f %12.3f %12.3f%n", satItrf.getPosition().getX(), satItrf.getPosition().getY(), satItrf.getPosition().getZ()); System.out.format(Locale.US, "Satellite velocity in ITRF: %12.7f %12.7f %12.7f%n", satItrf.getVelocity().getX(), satItrf.getVelocity().getY(), satItrf.getVelocity().getZ()); Transform cogToEme2000 = cogFrame.getTransformTo(FramesFactory.getEME2000(), date); PVCoordinates satEME2000 = cogToEme2000.transformPVCoordinates(origin); System.out.format(Locale.US, "Satellite position in EME2000: %12.3f %12.3f %12.3f%n", satEME2000.getPosition().getX(), satEME2000.getPosition().getY(), satEME2000.getPosition().getZ()); System.out.format(Locale.US, "Satellite velocity in EME2000: %12.7f %12.7f %12.7f%n", satEME2000.getVelocity().getX(), satEME2000.getVelocity().getY(), satEME2000.getVelocity().getZ()); } catch (OrekitException oe) { System.err.println(oe.getMessage()); } }
From source file:msi.gaml.operators.Maths.java
public static void main(final String[] args) throws ParseException { java.lang.System.out.println("Various format tests"); java.lang.System.out.println("NumberFormat.parse1e1 = " + NumberFormat.getInstance(Locale.US).parse("1e1")); java.lang.System.out.println("Double.parse 1e1 = " + Double.parseDouble("1e1")); java.lang.System.out//from w w w. jav a 2 s.c o m .println("NumberFormat.parse 1E1 = " + NumberFormat.getInstance(Locale.US).parse("1E1")); java.lang.System.out.println("Double.parse 1E1 = " + Double.parseDouble("1E1")); java.lang.System.out .println("NumberFormat.parse 1.0e1 = " + NumberFormat.getInstance(Locale.US).parse("1.0e1")); java.lang.System.out.println("Double.parse 1.0e1 = " + Double.parseDouble("1.0e1")); java.lang.System.out.println( "NumberFormat.parse 0.001E+10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E+10")); java.lang.System.out.println("Double.parse 0.001E+10 = " + Double.parseDouble("0.001E+10")); java.lang.System.out.println( "NumberFormat.parse 0.001E-10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E-10")); java.lang.System.out.println("Double.parse 0.001E-10 = " + Double.parseDouble("0.001E-10")); java.lang.System.out .println("NumberFormat.parse 0.001e-10 =" + NumberFormat.getInstance(Locale.US).parse("0.001e-10")); java.lang.System.out.println("Double.parse 0.001e-10 = " + Double.parseDouble("0.001e-10")); java.lang.System.out.println("Various arithmetic tests"); java.lang.System.out.println("cos(PI) = " + Maths.cos_rad(PI)); java.lang.System.out.println("sin_rad(0.0) = " + sin_rad(0.0)); java.lang.System.out.println("tan_rad(0.0) = " + tan_rad(0.0)); java.lang.System.out.println("sin(360) = " + sin(360)); java.lang.System.out.println("sin(-720) = " + sin(-720)); java.lang.System.out.println("sin(360.0) = " + sin(360.0)); java.lang.System.out.println("sin(-720.0) = " + sin(-720.0)); java.lang.System.out.println("sin(90) = " + sin(90)); java.lang.System.out.println("sin(45) = " + sin(45)); java.lang.System.out.println("sin(0) = " + sin(0)); java.lang.System.out.println("sin(135) = " + sin(135)); java.lang.System.out.println("Math.sin(360.0) = " + Math.sin(2 * Math.PI)); // java.lang.System.out.println("3.0 = 3" + (3d == 3)); // java.lang.System.out.println("3.0 != 3" + (3d != 3)); java.lang.System.out.println("floor and ceil 2.7 " + floor(2.7) + " and " + ceil(2.7)); java.lang.System.out.println("floor and ceil -2.7 " + floor(-2.7) + " and " + ceil(-2.7)); java.lang.System.out.println("floor and ceil -2 " + floor(-2) + " and " + ceil(-2)); java.lang.System.out.println("floor and ceil 3 " + floor(3) + " and " + ceil(3)); double atan2diff = 0; double atan2diff2 = 0; Random rand = new Random(); long s1 = 0; long t1 = 0; long t2 = 0; long t3 = 0; // for ( int i = 0; i < 10000000; i++ ) { // double x = rand.nextDouble(); // double y = rand.nextDouble(); // s1 = java.lang.System.currentTimeMillis(); // double a1 = Math.atan2(x, y); // t1 += java.lang.System.currentTimeMillis() - s1; // s1 = java.lang.System.currentTimeMillis(); // double a2 = FastMath.atan2(x, y); // t2 += java.lang.System.currentTimeMillis() - s1; // s1 = java.lang.System.currentTimeMillis(); // double a3 = Maths.atan2Opt2(x, y); // t3 += java.lang.System.currentTimeMillis() - s1; // // atan2diff += Math.abs(a1 - a2); // atan2diff2 += Math.abs(a1 - a3); // } // java.lang.System.out.println("atan2diff : " + atan2diff + " atan2diff2 : " + atan2diff2 + " t1 : " + t1 + // " t2 : " + t2 + " t3 : " + t3); long t4 = 0; long t5 = 0; long t6 = 0; double distDiff1 = 0; double distDiff2 = 0; for (int i = 0; i < 1000000; i++) { double x1 = rand.nextDouble(); double y1 = rand.nextDouble(); double x2 = rand.nextDouble(); double y2 = rand.nextDouble(); Coordinate c1 = new Coordinate(x1, y1); Coordinate c2 = new Coordinate(x2, y2); s1 = java.lang.System.currentTimeMillis(); double a1 = Math.hypot(x2 - x1, y2 - y1); t4 += java.lang.System.currentTimeMillis() - s1; s1 = java.lang.System.currentTimeMillis(); double a2 = FastMath.hypot(x2 - x1, y2 - y1); t5 += java.lang.System.currentTimeMillis() - s1; s1 = java.lang.System.currentTimeMillis(); double a3 = c1.distance(c2); t6 += java.lang.System.currentTimeMillis() - s1; distDiff1 += Math.abs(a1 - a2); distDiff2 += Math.abs(a1 - a3); } java.lang.System.out.println("distDiff1 : " + distDiff1 + " distDiff2 : " + distDiff2 + " t4 : " + t4 + " t5 : " + t5 + " t6 : " + t6); long t7 = 0; long t8 = 0; distDiff1 = 0; for (int i = 0; i < 1000000; i++) { double a1, a2; double x1 = rand.nextDouble(); double x2 = rand.nextDouble(); double y1 = rand.nextDouble(); double y2 = rand.nextDouble(); double z1 = 0.0; double z2 = 0.0; GamaPoint c2 = new GamaPoint(x2, y2, z2); s1 = java.lang.System.currentTimeMillis(); if (z1 == 0d && c2.getZ() == 0d) { a1 = hypot(x1, x2, y1, y2); } else { a1 = hypot(x1, x2, y1, y2, z1, z2); } t7 += java.lang.System.currentTimeMillis() - s1; s1 = java.lang.System.currentTimeMillis(); a2 = hypot(x1, x2, y1, y2, z1, c2.getZ()); t8 += java.lang.System.currentTimeMillis() - s1; distDiff1 += Math.abs(a1 - a2); } java.lang.System.out.println( "with 0.0 check : " + t7 + " with direct 3 parameters call : " + t8 + " distance : " + distDiff1); // java.lang.System.out.println("Infinity to int:" + (int) Double.POSITIVE_INFINITY); // java.lang.System.out.println("NaN to int:" + (int) Double.NaN); // GuiUtils.debug("(int) (1.0/0.0):" + (int) (1.0 / 0.0)); // GuiUtils.debug("(int) (1.0/0):" + (int) (1.0 / 0)); // GuiUtils.debug("(int) (1.0/0d):" + (int) (1 / 0d)); // GuiUtils.debug("(int) (1/0):" + 1 / 0); }
From source file:asl.seedscan.SeedScan.java
public static void main(String args[]) { // Default locations of config and schema files File configFile = new File("config.xml"); File schemaFile = new File("schemas/SeedScanConfig.xsd"); boolean parseConfig = true; ArrayList<File> schemaFiles = new ArrayList<File>(); schemaFiles.add(schemaFile);//from w w w . ja va 2 s . co m // ==== Command Line Parsing ==== Options options = new Options(); Option opConfigFile = new Option("c", "config-file", true, "The config file to use for seedscan. XML format according to SeedScanConfig.xsd."); Option opSchemaFile = new Option("s", "schema-file", true, "The xsd schema file which should be used to verify the config file format. "); OptionGroup ogConfig = new OptionGroup(); ogConfig.addOption(opConfigFile); OptionGroup ogSchema = new OptionGroup(); ogConfig.addOption(opSchemaFile); options.addOptionGroup(ogConfig); options.addOptionGroup(ogSchema); PosixParser optParser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = optParser.parse(options, args, true); } catch (org.apache.commons.cli.ParseException e) { logger.error("Error while parsing command-line arguments."); System.exit(1); } Option opt; Iterator<?> iter = cmdLine.iterator(); while (iter.hasNext()) { opt = (Option) iter.next(); if (opt.getOpt().equals("c")) { configFile = new File(opt.getValue()); } else if (opt.getOpt().equals("s")) { schemaFile = new File(opt.getValue()); } } // ==== Configuration Read and Parse Actions ==== ConfigParser parser = new ConfigParser(schemaFiles); ConfigT config = parser.parseConfig(configFile); // Print out configuration file contents Formatter formatter = new Formatter(new StringBuilder(), Locale.US); // ===== CONFIG: LOCK FILE ===== File lockFile = new File(config.getLockfile()); logger.info("SeedScan lock file is '" + lockFile + "'"); LockFile lock = new LockFile(lockFile); if (!lock.acquire()) { logger.error("Could not acquire lock."); System.exit(1); } // ===== CONFIG: LOGGING ===== // MTH: This is now done in log4j.properties file // ===== CONFIG: DATABASE ===== MetricDatabase readDB = new MetricDatabase(config.getDatabase()); MetricDatabase writeDB = new MetricDatabase(config.getDatabase()); MetricReader reader = new MetricReader(readDB); MetricInjector injector = new MetricInjector(writeDB); // ===== CONFIG: SCANS ===== Hashtable<String, Scan> scans = new Hashtable<String, Scan>(); if (config.getScans().getScan() == null) { logger.error("No scans in configuration."); System.exit(1); } else { for (ScanT scanCfg : config.getScans().getScan()) { String name = scanCfg.getName(); if (scans.containsKey(name)) { logger.error("Duplicate scan name '" + name + "' encountered."); System.exit(1); } // This should really be handled by jaxb by setting it up in schemas/SeedScanConfig.xsd if (scanCfg.getStartDay() == null && scanCfg.getStartDate() == null) { logger.error( "== SeedScan Error: Must set EITHER cfg:start_day -OR- cfg:start_date in config.xml to start Scan!"); System.exit(1); } // Configure this Scan Scan scan = new Scan(scanCfg.getName()); scan.setPathPattern(scanCfg.getPath()); scan.setDatalessDir(scanCfg.getDatalessDir()); scan.setEventsDir(scanCfg.getEventsDir()); scan.setPlotsDir(scanCfg.getPlotsDir()); scan.setDaysToScan(scanCfg.getDaysToScan().intValue()); if (scanCfg.getStartDay() != null) { scan.setStartDay(scanCfg.getStartDay().intValue()); } if (scanCfg.getStartDate() != null) { scan.setStartDate(scanCfg.getStartDate().intValue()); } if (scanCfg.getNetworkSubset() != null) { logger.debug("Filter on Network Subset=[{}]", scanCfg.getNetworkSubset()); Filter filter = new Filter(false); for (String network : scanCfg.getNetworkSubset().split(",")) { logger.debug("Network =[{}]", network); filter.addFilter(network); } scan.setNetworks(filter); } if (scanCfg.getStationSubset() != null) { logger.debug("Filter on Station Subset=[{}]", scanCfg.getStationSubset()); Filter filter = new Filter(false); for (String station : scanCfg.getStationSubset().split(",")) { logger.debug("Station =[{}]", station); filter.addFilter(station); } scan.setStations(filter); } if (scanCfg.getLocationSubset() != null) { logger.debug("Filter on Location Subset=[{}]", scanCfg.getLocationSubset()); Filter filter = new Filter(false); for (String location : scanCfg.getLocationSubset().split(",")) { logger.debug("Location =[{}]", location); filter.addFilter(location); } scan.setLocations(filter); } if (scanCfg.getChannelSubset() != null) { logger.debug("Filter on Channel Subset=[{}]", scanCfg.getChannelSubset()); Filter filter = new Filter(false); for (String channel : scanCfg.getChannelSubset().split(",")) { logger.debug("Channel =[{}]", channel); filter.addFilter(channel); } scan.setChannels(filter); } for (MetricT met : scanCfg.getMetrics().getMetric()) { try { Class<?> metricClass = Class.forName(met.getClassName()); MetricWrapper wrapper = new MetricWrapper(metricClass); for (ArgumentT arg : met.getArgument()) { wrapper.add(arg.getName(), arg.getValue()); } scan.addMetric(wrapper); } catch (ClassNotFoundException ex) { logger.error("No such metric class '" + met.getClassName() + "'"); System.exit(1); } catch (InstantiationException ex) { logger.error("Could not dynamically instantiate class '" + met.getClassName() + "'"); System.exit(1); } catch (IllegalAccessException ex) { logger.error("Illegal access while loading class '" + met.getClassName() + "'"); System.exit(1); } catch (NoSuchFieldException ex) { logger.error("Invalid dynamic argument to Metric subclass '" + met.getClassName() + "'"); System.exit(1); } } scans.put(name, scan); } } // ==== Establish Database Connection ==== // TODO: State Tracking in the Database // - Record scan started in database. // - Track our progress as we go so a new process can pick up where // we left off if our process dies. // - Mark when each date-station-channel-operation is complete //LogDatabaseHandler logDB = new LogDatabaseHandler(configuration.get // For each day ((yesterday - scanDepth) to yesterday) // scan for these channel files, only process them if // they have not yet been scanned, or if changes have // occurred to the file since its last scan. Do this for // each scan type. Do not re-scan data for each type, // launch processes for each scan and use the same data set // for each. If we can pipe the data as it is read, do so. // If we need to push all of it at once, do these in sequence // in order to preserve overall system memory resources. Scan scan = null; // ==== Perform Scans ==== scan = scans.get("daily"); //MTH: This part could/should be moved up higher except that we need to know datalessDir, which, // at this point, is configured on a per scan basis ... so we need to know what scan we're doing MetaServer metaServer = null; if (config.getMetaserver() != null) { if (config.getMetaserver().getUseRemote().equals("yes") || config.getMetaserver().getUseRemote().equals("true")) { String remoteServer = config.getMetaserver().getRemoteUri(); try { metaServer = new MetaServer(new URI(remoteServer)); } catch (Exception e) { logger.error("caught URI exception:" + e.getMessage()); } } else { metaServer = new MetaServer(scan.getDatalessDir()); } } else { // Use local MetaServer metaServer = new MetaServer(scan.getDatalessDir()); } List<Station> stations = null; if (config.getStationList() == null) { // get StationList from MetaServer logger.info("Get StationList from MetaServer"); stations = metaServer.getStationList(); } else { // read StationList from config.xml logger.info("Read StationList from config.xml"); List<String> stationList = config.getStationList().getStation(); if (stationList.size() > 0) { stations = new ArrayList<Station>(); for (String station : stationList) { String[] words = station.split("_"); if (words.length != 2) { logger.warn(String.format("stationList: station=[%s] is NOT a valid station --> Skip", station)); } else { stations.add(new Station(words[0], words[1])); logger.info("config.xml: Read station:" + station); } } } else { logger.error("Error: No valid stations read from config.xml"); } } if (stations == null) { logger.error("Found NO stations to scan --> EXITTING SeedScan"); System.exit(1); } Thread readerThread = new Thread(reader); readerThread.start(); logger.info("Reader thread started."); Thread injectorThread = new Thread(injector); injectorThread.start(); logger.info("Injector thread started."); // Loop over scans and hand each one to a ScanManager logger.info("Hand scan to ScanManager"); for (String key : scans.keySet()) { scan = scans.get(key); logger.info(String.format("Scan=[%s] startDay=%d startDate=%d daysToScan=%d\n", key, scan.getStartDay(), scan.getStartDate(), scan.getDaysToScan())); ScanManager scanManager = new ScanManager(reader, injector, stations, scan, metaServer); } logger.info("ScanManager is [ FINISHED ] --> stop the injector and reader threads"); try { injector.halt(); logger.info("All stations processed. Waiting for injector thread to finish..."); synchronized (injectorThread) { //injectorThread.wait(); injectorThread.interrupt(); } logger.info("Injector thread halted."); } catch (InterruptedException ex) { logger.warn("The injector thread was interrupted while attempting to complete requests."); } try { reader.halt(); logger.info("All stations processed. Waiting for reader thread to finish..."); synchronized (readerThread) { //readerThread.wait(); readerThread.interrupt(); } logger.info("Reader thread halted."); } catch (InterruptedException ex) { logger.warn("The reader thread was interrupted while attempting to complete requests."); } try { lock.release(); } catch (IOException e) { ; } finally { logger.info("Release seedscan lock and quit metaServer"); lock = null; metaServer.quit(); } }