List of usage examples for java.lang String split
public String[] split(String regex)
From source file:edu.ku.brc.specify.tools.schemalocale.SchemaLocalizerFrame.java
/** * @param args/*from ww w .j av a2 s . c o m*/ */ public static void main(String[] args) { log.debug("********* Current [" + (new File(".").getAbsolutePath()) + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // This is for Windows and Exe4J, turn the args into System Properties for (String s : args) { String[] pairs = s.split("="); //$NON-NLS-1$ if (pairs.length == 2) { log.debug("[" + pairs[0] + "][" + pairs[1] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (pairs[0].startsWith("-D")) //$NON-NLS-1$ { System.setProperty(pairs[0].substring(2, pairs[0].length()), pairs[1]); } } } // Now check the System Properties String appDir = System.getProperty("appdir"); //$NON-NLS-1$ if (StringUtils.isNotEmpty(appDir)) { UIRegistry.setDefaultWorkingPath(appDir); } String appdatadir = System.getProperty("appdatadir"); //$NON-NLS-1$ if (StringUtils.isNotEmpty(appdatadir)) { UIRegistry.setBaseAppDataDir(appdatadir); } SwingUtilities.invokeLater(new Runnable() { public void run() { // Set App Name, MUST be done very first thing! UIRegistry.setAppName("Specify"); //$NON-NLS-1$ // Then set this IconManager.setApplicationClass(Specify.class); IconManager.loadIcons(XMLHelper.getConfigDir("icons_datamodel.xml")); //$NON-NLS-1$ IconManager.loadIcons(XMLHelper.getConfigDir("icons_plugins.xml")); //$NON-NLS-1$ IconManager.loadIcons(XMLHelper.getConfigDir("icons_disciplines.xml")); //$NON-NLS-1$ try { UIHelper.OSTYPE osType = UIHelper.getOSType(); if (osType == UIHelper.OSTYPE.Windows) { //UIManager.setLookAndFeel(new WindowsLookAndFeel()); UIManager.setLookAndFeel(new PlasticLookAndFeel()); PlasticLookAndFeel.setPlasticTheme(new ExperienceBlue()); } else if (osType == UIHelper.OSTYPE.Linux) { //UIManager.setLookAndFeel(new GTKLookAndFeel()); PlasticLookAndFeel.setPlasticTheme(new SkyKrupp()); //PlasticLookAndFeel.setPlasticTheme(new DesertBlue()); //PlasticLookAndFeel.setPlasticTheme(new ExperienceBlue()); //PlasticLookAndFeel.setPlasticTheme(new ExperienceRoyale()); UIManager.setLookAndFeel(new PlasticLookAndFeel()); } } catch (Exception e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SchemaLocalizerFrame.class, e); e.printStackTrace(); } AppPreferences localPrefs = AppPreferences.getLocalPrefs(); localPrefs.setDirPath(UIRegistry.getAppDataDir()); //Specify.adjustLocaleFromPrefs(); System.setProperty(AppContextMgr.factoryName, "edu.ku.brc.specify.config.SpecifyAppContextMgr"); // Needed by AppContextMgr //$NON-NLS-1$ System.setProperty(SchemaI18NService.factoryName, "edu.ku.brc.specify.config.SpecifySchemaI18NService"); // Needed for Localization and Schema //$NON-NLS-1$ System.setProperty(UIFieldFormatterMgr.factoryName, "edu.ku.brc.specify.ui.SpecifyUIFieldFormatterMgr"); // Needed for CatalogNumbering //$NON-NLS-1$ System.setProperty(WebLinkMgr.factoryName, "edu.ku.brc.specify.config.SpecifyWebLinkMgr"); // Needed for WebLnkButton //$NON-NLS-1$ System.setProperty(DataObjFieldFormatMgr.factoryName, "edu.ku.brc.specify.config.SpecifyDataObjFieldFormatMgr"); // Needed for WebLnkButton //$NON-NLS-1$ SpecifyDataObjFieldFormatMgr.setDoingLocal(true); SpecifyUIFieldFormatterMgr.setDoingLocal(true); SpecifyWebLinkMgr.setDoingLocal(true); Object[] options = { getResourceString("SchemaLocalizerFrame.FULL_SCHEMA"), //$NON-NLS-1$ getResourceString("SchemaLocalizerFrame.WB_SCHEMA") }; //$NON-NLS-1$ int retVal = JOptionPane.showOptionDialog(null, getResourceString("SchemaLocalizerFrame.WHICH_SCHEMA"), //$NON-NLS-1$ getResourceString("SchemaLocalizerFrame.CHOOSE_SCHEMA"), JOptionPane.YES_NO_CANCEL_OPTION, //$NON-NLS-1$ JOptionPane.QUESTION_MESSAGE, null, options, options[0]); SchemaLocalizerFrame sla; if (retVal == JOptionPane.NO_OPTION) { DBTableIdMgr schema = new DBTableIdMgr(false); schema.initialize(new File(XMLHelper.getConfigDirPath("specify_workbench_datamodel.xml"))); //$NON-NLS-1$ sla = new SchemaLocalizerFrame(SpLocaleContainer.WORKBENCH_SCHEMA, schema); } else { sla = new SchemaLocalizerFrame(SpLocaleContainer.CORE_SCHEMA, DBTableIdMgr.getInstance()); } AppContextMgr.getInstance().setHasContext(true); sla.createDisplay(); sla.pack(); Dimension size = sla.getSize(); size.width += 250; sla.setSize(size); UIHelper.centerAndShow(sla); final SchemaLocalizerFrame slaf = sla; slaf.setDefaultCloseOperation(EXIT_ON_CLOSE); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { slaf.chooseCurrentLocale(); } }); } }); }
From source file:com.oltpbenchmark.multitenancy.MuTeBench.java
/** * @param args//from w ww. j a v a 2s. co m * @throws Exception */ public static void main(String[] args) throws Exception { String duration = null; String scenarioFile = null; // ------------------------------------------------------------------- // INITIALIZE LOGGING // ------------------------------------------------------------------- String log4jPath = System.getProperty("log4j.configuration"); if (log4jPath != null) { org.apache.log4j.PropertyConfigurator.configure(log4jPath); } else { throw new RuntimeException("Missing log4j.properties file"); } // ------------------------------------------------------------------- // PARSE COMMAND LINE PARAMETERS // ------------------------------------------------------------------- CommandLineParser parser = new PosixParser(); XMLConfiguration pluginConfig = null; try { pluginConfig = new XMLConfiguration("config/plugin.xml"); } catch (ConfigurationException e1) { LOG.info("Plugin configuration file config/plugin.xml is missing"); e1.printStackTrace(); } pluginConfig.setExpressionEngine(new XPathExpressionEngine()); Options options = new Options(); options.addOption("s", "scenario", true, "[required] Workload scenario file"); options.addOption("a", "analysis-buckets", true, "sampling buckets for result aggregation"); options.addOption("r", "runtime", true, "maximum runtime (no events will be started after finishing runtime)"); options.addOption("v", "verbose", false, "Display Messages"); options.addOption("g", "gui", false, "Show controlling GUI"); options.addOption("h", "help", false, "Print this help"); options.addOption("o", "output", true, "Output file (default System.out)"); options.addOption("b", "baseline", true, "Output files of previous baseline run"); options.addOption(null, "histograms", false, "Print txn histograms"); options.addOption("d", "dialects-export", true, "Export benchmark SQL to a dialects file"); // parse the command line arguments CommandLine argsLine = parser.parse(options, args); if (argsLine.hasOption("h")) { printUsage(options); return; } else if (!argsLine.hasOption("scenario")) { INIT_LOG.fatal("Missing scenario description file"); System.exit(-1); } else scenarioFile = argsLine.getOptionValue("scenario"); if (argsLine.hasOption("r")) duration = argsLine.getOptionValue("r"); if (argsLine.hasOption("runtime")) duration = argsLine.getOptionValue("runtime"); // ------------------------------------------------------------------- // CREATE TENANT SCHEDULE // ------------------------------------------------------------------- INIT_LOG.info("Create schedule"); Schedule schedule = new Schedule(duration, scenarioFile); HashMap<Integer, ScheduleEvents> tenantEvents = schedule.getTenantEvents(); ArrayList<Integer> tenantList = schedule.getTenantList(); List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>(); for (int tenInd = 0; tenInd < tenantList.size(); tenInd++) { int tenantID = tenantList.get(tenInd); for (int tenEvent = 0; tenEvent < tenantEvents.get(tenantID).size(); tenEvent++) { BenchmarkSettings benchmarkSettings = (BenchmarkSettings) tenantEvents.get(tenantID) .getBenchmarkSettings(tenEvent); // update benchmark Settings benchmarkSettings.setTenantID(tenantID); // ------------------------------------------------------------------- // GET PLUGIN LIST // ------------------------------------------------------------------- String plugins = benchmarkSettings.getBenchmark(); String[] pluginList = plugins.split(","); String configFile = benchmarkSettings.getConfigFile(); XMLConfiguration xmlConfig = new XMLConfiguration(configFile); xmlConfig.setExpressionEngine(new XPathExpressionEngine()); int lastTxnId = 0; for (String plugin : pluginList) { // ---------------------------------------------------------------- // WORKLOAD CONFIGURATION // ---------------------------------------------------------------- String pluginTest = ""; pluginTest = "[@bench='" + plugin + "']"; WorkloadConfiguration wrkld = new WorkloadConfiguration(); wrkld.setTenantId(tenantID); wrkld.setBenchmarkName(setTenantIDinString(plugin, tenantID)); wrkld.setXmlConfig(xmlConfig); wrkld.setDBType(DatabaseType.get(setTenantIDinString(xmlConfig.getString("dbtype"), tenantID))); wrkld.setDBDriver(setTenantIDinString(xmlConfig.getString("driver"), tenantID)); wrkld.setDBConnection(setTenantIDinString(xmlConfig.getString("DBUrl"), tenantID)); wrkld.setDBName(setTenantIDinString(xmlConfig.getString("DBName"), tenantID)); wrkld.setDBUsername(setTenantIDinString(xmlConfig.getString("username"), tenantID)); wrkld.setDBPassword(setTenantIDinString(xmlConfig.getString("password"), tenantID)); String terminalString = setTenantIDinString(xmlConfig.getString("terminals[not(@bench)]", "0"), tenantID); int terminals = Integer.parseInt(xmlConfig.getString("terminals" + pluginTest, terminalString)); wrkld.setTerminals(terminals); int taSize = Integer.parseInt(xmlConfig.getString("taSize", "1")); if (taSize < 0) INIT_LOG.fatal("taSize must not be negative!"); wrkld.setTaSize(taSize); wrkld.setProprietaryTaSyntax(xmlConfig.getBoolean("proprietaryTaSyntax", false)); wrkld.setIsolationMode(setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"), tenantID)); wrkld.setScaleFactor(Double .parseDouble(setTenantIDinString(xmlConfig.getString("scalefactor", "1.0"), tenantID))); wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false)); int size = xmlConfig.configurationsAt("/works/work").size(); for (int i = 1; i < size + 1; i++) { SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]"); List<String> weight_strings; // use a workaround if there multiple workloads or // single // attributed workload if (pluginList.length > 1 || work.containsKey("weights[@bench]")) { weight_strings = get_weights(plugin, work); } else { weight_strings = work.getList("weights[not(@bench)]"); } int rate = 1; boolean rateLimited = true; boolean disabled = false; // can be "disabled", "unlimited" or a number String rate_string; rate_string = setTenantIDinString(work.getString("rate[not(@bench)]", ""), tenantID); rate_string = setTenantIDinString(work.getString("rate" + pluginTest, rate_string), tenantID); if (rate_string.equals(RATE_DISABLED)) { disabled = true; } else if (rate_string.equals(RATE_UNLIMITED)) { rateLimited = false; } else if (rate_string.isEmpty()) { LOG.fatal(String.format( "Tenant " + tenantID + ": Please specify the rate for phase %d and workload %s", i, plugin)); System.exit(-1); } else { try { rate = Integer.parseInt(rate_string); if (rate < 1) { LOG.fatal("Tenant " + tenantID + ": Rate limit must be at least 1. Use unlimited or disabled values instead."); System.exit(-1); } } catch (NumberFormatException e) { LOG.fatal(String.format( "Tenant " + tenantID + ": Rate string must be '%s', '%s' or a number", RATE_DISABLED, RATE_UNLIMITED)); System.exit(-1); } } Phase.Arrival arrival = Phase.Arrival.REGULAR; String arrive = setTenantIDinString(work.getString("@arrival", "regular"), tenantID); if (arrive.toUpperCase().equals("POISSON")) arrival = Phase.Arrival.POISSON; int activeTerminals; activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals[not(@bench)]", String.valueOf(terminals)), tenantID)); activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals" + pluginTest, String.valueOf(activeTerminals)), tenantID)); if (activeTerminals > terminals) { LOG.fatal("Tenant " + tenantID + ": Configuration error in work " + i + ": number of active terminals" + "" + "is bigger than the total number of terminals"); System.exit(-1); } wrkld.addWork(Integer.parseInt(setTenantIDinString(work.getString("/time"), tenantID)), rate, weight_strings, rateLimited, disabled, activeTerminals, arrival); } // FOR int numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); if (numTxnTypes == 0 && pluginList.length == 1) { // if it is a single workload run, <transactiontypes /> // w/o attribute is used pluginTest = "[not(@bench)]"; numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); } wrkld.setNumTxnTypes(numTxnTypes); // CHECKING INPUT PHASES int j = 0; for (Phase p : wrkld.getAllPhases()) { j++; if (p.getWeightCount() != wrkld.getNumTxnTypes()) { LOG.fatal(String.format("Tenant " + tenantID + ": Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types", j, p.getWeightCount(), wrkld.getNumTxnTypes())); System.exit(-1); } } // FOR // Generate the dialect map wrkld.init(); assert (wrkld.getNumTxnTypes() >= 0); assert (xmlConfig != null); // ---------------------------------------------------------------- // BENCHMARK MODULE // ---------------------------------------------------------------- String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']"); if (classname == null) { throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml"); } BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld }, new Class<?>[] { WorkloadConfiguration.class }); assert (benchList.get(0) != null); Map<String, Object> initDebug = new ListOrderedMap<String, Object>(); initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname)); initDebug.put("Configuration", configFile); initDebug.put("Type", wrkld.getDBType()); initDebug.put("Driver", wrkld.getDBDriver()); initDebug.put("URL", wrkld.getDBConnection()); initDebug.put("Isolation", setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"), tenantID)); initDebug.put("Scale Factor", wrkld.getScaleFactor()); INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug)); INIT_LOG.info(SINGLE_LINE); // Load TransactionTypes List<TransactionType> ttypes = new ArrayList<TransactionType>(); // Always add an INVALID type for Carlo ttypes.add(TransactionType.INVALID); int txnIdOffset = lastTxnId; for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) { String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]"; String txnName = setTenantIDinString(xmlConfig.getString(key + "/name"), tenantID); int txnId = i + 1; if (xmlConfig.containsKey(key + "/id")) { txnId = Integer .parseInt(setTenantIDinString(xmlConfig.getString(key + "/id"), tenantID)); } ttypes.add(bench.initTransactionType(txnName, txnId + txnIdOffset)); lastTxnId = i; } // FOR TransactionTypes tt = new TransactionTypes(ttypes); wrkld.setTransTypes(tt); if (benchmarkSettings.getBenchmarkSlaFile() != null) wrkld.setSlaFromFile(benchmarkSettings.getBenchmarkSlaFile()); LOG.debug("Tenant " + tenantID + ": Using the following transaction types: " + tt); bench.setTenantOffset(tenantEvents.get(tenantID).getTime(tenEvent)); bench.setTenantID(tenantID); bench.setBenchmarkSettings(benchmarkSettings); benchList.add(bench); } } } // create result collector ResultCollector rCollector = new ResultCollector(tenantList); // execute benchmarks in parallel ArrayList<Thread> benchThreads = new ArrayList<Thread>(); for (BenchmarkModule benchmark : benchList) { BenchmarkExecutor benchThread = new BenchmarkExecutor(benchmark, argsLine); Thread t = new Thread(benchThread); t.start(); benchThreads.add(t); benchmark.getWorkloadConfiguration().setrCollector(rCollector); } // waiting for completion of all benchmarks for (Thread t : benchThreads) { t.join(); } // print statistics int analysisBuckets = -1; if (argsLine.hasOption("analysis-buckets")) analysisBuckets = Integer.parseInt(argsLine.getOptionValue("analysis-buckets")); String output = null; if (argsLine.hasOption("o")) output = argsLine.getOptionValue("o"); String baseline = null; if (argsLine.hasOption("b")) baseline = argsLine.getOptionValue("b"); rCollector.printStatistics(output, analysisBuckets, argsLine.hasOption("histograms"), baseline); // create GUI if (argsLine.hasOption("g") && (!rCollector.getAllResults().isEmpty())) { try { Gui gui = new Gui(Integer.parseInt(argsLine.getOptionValue("analysis-buckets", "10")), rCollector, output); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.hpe.nv.samples.basic.BasicComparisonWithoutNV.java
public static void main(String[] args) throws Exception { try {// w ww . jav a 2 s.co m // program arguments Options options = new Options(); options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP"); options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port"); options.addOption("u", "username", true, "[mandatory] NV username"); options.addOption("w", "password", true, "[mandatory] NV password"); options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false"); options.addOption("y", "proxy", true, "[optional] Proxy server host:port"); options.addOption("a", "active-adapter-ip", true, "[optional] Active adapter IP. Default: --server-ip argument"); options.addOption("t", "site-url", true, "[optional] Site under test URL. Default: HPE Network Virtualization site URL. If you change this value, make sure to change the --xpath argument too"); options.addOption("x", "xpath", true, "[optional] Parameter for ExpectedConditions.visibilityOfElementLocated(By.xpath(...)) method. Use an xpath expression of some element in the site. Default: //div[@id='content']"); options.addOption("k", "analysis-ports", true, "[optional] A comma-separated list of ports for test analysis"); options.addOption("b", "browser", true, "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome, Firefox. Default: Firefox"); options.addOption("d", "debug", true, "[optional] Pass true to view console debug messages during execution. Default: false"); options.addOption("h", "help", false, "[optional] Generates and prints help information"); // parse and validate the command line arguments CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { // print help if help argument is passed HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("BasicComparisonWithoutNV.java", options); return; } if (line.hasOption("server-ip")) { serverIp = line.getOptionValue("server-ip"); if (serverIp.equals("0.0.0.0")) { throw new Exception( "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP"); } } else { throw new Exception("Missing argument -i/--server-ip <serverIp>"); } if (line.hasOption("server-port")) { serverPort = Integer.parseInt(line.getOptionValue("server-port")); } else { throw new Exception("Missing argument -o/--server-port <serverPort>"); } if (line.hasOption("username")) { username = line.getOptionValue("username"); } else { throw new Exception("Missing argument -u/--username <username>"); } if (line.hasOption("password")) { password = line.getOptionValue("password"); } else { throw new Exception("Missing argument -w/--password <password>"); } if (line.hasOption("ssl")) { ssl = Boolean.parseBoolean(line.getOptionValue("ssl")); } if (line.hasOption("site-url")) { siteUrl = line.getOptionValue("site-url"); } else { siteUrl = "http://www8.hp.com/us/en/software-solutions/network-virtualization/index.html"; } if (line.hasOption("xpath")) { xpath = line.getOptionValue("xpath"); } else { xpath = "//div[@id='content']"; } if (line.hasOption("proxy")) { proxySetting = line.getOptionValue("proxy"); } if (line.hasOption("active-adapter-ip")) { activeAdapterIp = line.getOptionValue("active-adapter-ip"); } else { activeAdapterIp = serverIp; } if (line.hasOption("analysis-ports")) { String analysisPortsStr = line.getOptionValue("analysis-ports"); analysisPorts = analysisPortsStr.split(","); } else { analysisPorts = new String[] { "80", "8080" }; } if (line.hasOption("browser")) { browser = line.getOptionValue("browser"); } else { browser = "Firefox"; } if (line.hasOption("debug")) { debug = Boolean.parseBoolean(line.getOptionValue("debug")); } String newLine = System.getProperty("line.separator"); String testDescription = "*** This sample demonstrates how NV helps you test your application under various network conditions. ***" + newLine + "*** This test starts by navigating to the home page in the HPE Network Virtualization website using the Selenium WebDriver. ***" + newLine + "*** This initial step runs without NV emulation and provides a basis for comparison. ***" + newLine + "*** ***" + newLine + "*** Next, the sample starts an NV test configured with a \"3G Busy\" network scenario. ***" + newLine + "*** The same step runs as before - navigating to the home page in the HPE Network Virtualization website - but this time, ***" + newLine + "*** it does so over an emulated \"3G Busy\" network as part of an NV transaction. ***" + newLine + "*** ***" + newLine + "*** When the sample finishes running, it prints a summary to the console. This summary displays a comparison of the time ***" + newLine + "*** it took to navigate to the site both with and without NV's network emulation. The results show that the slow \"3G Busy\" ***" + newLine + "*** network increases the time it takes to navigate to the site, as you would expect. ***" + newLine + "*** ***" + newLine + "*** You can view the actual steps of this sample in the BasicComparisonWithoutNV.java file. ***" + newLine; // print the sample's description System.out.println(testDescription); // start console spinner if (!debug) { spinner = new Thread(new Spinner()); spinner.start(); } // sample execution steps /***** Part 1 - Navigate to the site without using NV emulation *****/ printPartDescription("\b------ Part 1 - Navigate to the site without using NV emulation"); buildSeleniumWebDriver(); startNoNV = System.currentTimeMillis(); seleniumNavigateToPage(); stopNoNV = System.currentTimeMillis(); driverCloseAndQuit(); printPartSeparator(); /***** Part 2 - Navigate to the site using NV "3G Busy" network scenario emulation *****/ printPartDescription( "------ Part 2 - Navigate to the site using NV \"3G Busy\" network scenario emulation"); initTestManager(); setActiveAdapter(); startBusyTest(); testRunning = true; connectToTransactionManager(); startTransaction(); transactionInProgress = true; buildSeleniumWebDriver(); seleniumNavigateToPage(); stopTransaction(); transactionInProgress = false; driverCloseAndQuit(); stopTest(); testRunning = false; printPartSeparator(); /***** Part 3 - Analyze the NV test and print the results to the console *****/ printPartDescription("------ Part 3 - Analyze the NV test and print the results to the console"); analyzeTestJson(); printPartSeparator(); doneCallback(); } catch (Exception e) { try { handleError(e.getMessage()); } catch (Exception e2) { System.out.println("Error occurred: " + e2.getMessage()); } } }
From source file:Satellite.java
/** Program entry point. * @param args program arguments (unused here) *//*from w w w .j a va2 s . c o m*/ public static void main(String[] args) { try { // configure Orekit AutoconfigurationCustom.configureOrekit(); // Initial state definition : date, orbit AbsoluteDate targetDate = new AbsoluteDate(2015, 12, 15, 2, 54, 27.000, TimeScalesFactory.getUTC()); //*******/ double mu = 3.986004415e+14; // gravitation coefficient //*******/ Frame inertialFrame = FramesFactory.getEME2000(); // inertial frame for orbit definition //*******/ Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680); //*******/ Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231); //*******/ PVCoordinates pvCoordinates = new PVCoordinates(position, velocity); //*******/ Orbit initialOrbit = new KeplerianOrbit(pvCoordinates, inertialFrame, initialDate, mu); String Line1 = "1 25544U 98067A 15348.82280235 .00015563 00000-0 23610-3 0 9996"; String Line2 = "2 25544 51.6445 262.5935 0007865 276.8969 187.2494 15.54770155976144"; TLE TLEdata = new TLE(Line1, Line2); // Propagator : consider a simple keplerian motion (could be more elaborate) Propagator TLEProp = TLEPropagator.selectExtrapolator(TLEdata); // // Earth and frame // Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true); // BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, // Constants.WGS84_EARTH_FLATTENING, // earthFrame); // // // Station // final double longitude = FastMath.toRadians(89.); // final double latitude = FastMath.toRadians(-8); // final double altitude = 0.; // final GeodeticPoint station1 = new GeodeticPoint(latitude, longitude, altitude); // final TopocentricFrame sta1Frame = new TopocentricFrame(earth, station1, "station1"); // // // Event definition // final double maxcheck = 60.0; // final double threshold = 0.001; // final double elevation = FastMath.toRadians(5.0); // final EventDetector sta1Visi = // new ElevationDetector(maxcheck, threshold, sta1Frame). // withConstantElevation(elevation). // withHandler(new VisibilityHandler()); // Add event to be detected //kepler.addEventDetector(sta1Visi); //Propagate from the initial date to the first raising or for the fixed duration //SpacecraftState finalState = kepler.propagate(initialDate.shiftedBy(1500.)); //System.out.println(" Final state : " + finalState.getDate().durationFrom(initialDate)); String stateVector = TLEProp.propagate(targetDate) .getPVCoordinates(FramesFactory.getITRF(IERSConventions.IERS_2010, true)).toString(); stateVector = stateVector.replace("{", "").replace("}", ""); //Removes brackets {} stateVector = stateVector.replace("(", "").replace(")", ""); //Removes parentheses () stateVector = stateVector.replace("P", "").replace("V", "").replace("A", ""); //Removes P, V, A stateVector = stateVector.replace(" ", ""); //Removes spaces String[] lineData = stateVector.split(","); String timeStamp = new String(lineData[0]); double[] position = new double[] { Double.parseDouble(lineData[1]), Double.parseDouble(lineData[2]), Double.parseDouble(lineData[3]) }; double[] velocity = new double[] { Double.parseDouble(lineData[4]), Double.parseDouble(lineData[5]), Double.parseDouble(lineData[6]) }; double[] acceleration = new double[] { Double.parseDouble(lineData[7]), Double.parseDouble(lineData[8]), Double.parseDouble(lineData[9]) }; position = Convert_To_Lat_Long(position); System.out.format("Latitude %.8f N%n", position[0]); System.out.format("Longitude %.8f E%n", position[1]); System.out.format("Altitude %.0f m %n", position[2]); } catch (OrekitException oe) { System.err.println(oe.getMessage()); } }
From source file:com.twentyn.patentSearch.DocumentSearch.java
public static void main(String[] args) throws Exception { System.out.println("Starting up..."); System.out.flush();/*ww w. j a v a2 s. co m*/ Options opts = new Options(); opts.addOption(Option.builder("x").longOpt("index").hasArg().required().desc("Path to index file to read") .build()); opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build()); opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build()); opts.addOption(Option.builder("f").longOpt("field").hasArg().desc("The indexed field to search").build()); opts.addOption( Option.builder("q").longOpt("query").hasArg().desc("The query to use when searching").build()); opts.addOption(Option.builder("l").longOpt("list-file").hasArg() .desc("A file containing a list of queries to run in sequence").build()); opts.addOption( Option.builder("e").longOpt("enumerate").desc("Enumerate the documents in the index").build()); opts.addOption(Option.builder("d").longOpt("dump").hasArg() .desc("Dump terms in the document index for a specified field").build()); opts.addOption( Option.builder("o").longOpt("output").hasArg().desc("Write results JSON to this file.").build()); opts.addOption(Option.builder("n").longOpt("inchi-field").hasArg() .desc("The index of the InChI field if an input TSV is specified.").build()); opts.addOption(Option.builder("s").longOpt("synonym-field").hasArg() .desc("The index of the chemical synonym field if an input TSV is specified.").build()); HelpFormatter helpFormatter = new HelpFormatter(); CommandLineParser cmdLineParser = new DefaultParser(); CommandLine cmdLine = null; try { cmdLine = cmdLineParser.parse(opts, args); } catch (ParseException e) { System.out.println("Caught exception when parsing command line: " + e.getMessage()); helpFormatter.printHelp("DocumentIndexer", opts); System.exit(1); } if (cmdLine.hasOption("help")) { helpFormatter.printHelp("DocumentIndexer", opts); System.exit(0); } if (!(cmdLine.hasOption("enumerate") || cmdLine.hasOption("dump") || (cmdLine.hasOption("field") && (cmdLine.hasOption("query") || cmdLine.hasOption("list-file"))))) { System.out.println("Must specify one of 'enumerate', 'dump', or 'field' + {'query', 'list-file'}"); helpFormatter.printHelp("DocumentIndexer", opts); System.exit(1); } if (cmdLine.hasOption("verbose")) { // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2 LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration ctxConfig = ctx.getConfiguration(); LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); logConfig.setLevel(Level.DEBUG); ctx.updateLoggers(); LOGGER.debug("Verbose logging enabled"); } ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); LOGGER.info("Opening index at " + cmdLine.getOptionValue("index")); try (Directory indexDir = FSDirectory.open(new File(cmdLine.getOptionValue("index")).toPath()); IndexReader indexReader = DirectoryReader.open(indexDir);) { if (cmdLine.hasOption("enumerate")) { /* Enumerate all documents in the index. * With help from * http://stackoverflow.com/questions/2311845/is-it-possible-to-iterate-through-documents-stored-in-lucene-index */ for (int i = 0; i < indexReader.maxDoc(); i++) { Document doc = indexReader.document(i); LOGGER.info("Doc " + i + ":"); LOGGER.info(doc); } } else if (cmdLine.hasOption("dump")) { /* Dump indexed terms for a specific field. * With help from http://stackoverflow.com/questions/11148036/find-list-of-terms-indexed-by-lucene */ Terms terms = SlowCompositeReaderWrapper.wrap(indexReader).terms(cmdLine.getOptionValue("dump")); LOGGER.info("Has positions: " + terms.hasPositions()); LOGGER.info("Has offsets: " + terms.hasOffsets()); LOGGER.info("Has freqs: " + terms.hasFreqs()); LOGGER.info("Stats: " + terms.getStats()); LOGGER.info(terms); TermsEnum termsEnum = terms.iterator(); BytesRef br = null; while ((br = termsEnum.next()) != null) { LOGGER.info(" " + br.utf8ToString()); } } else { IndexSearcher searcher = new IndexSearcher(indexReader); String field = cmdLine.getOptionValue("field"); List<Pair<String, String>> queries = null; if (cmdLine.hasOption("query")) { queries = Collections.singletonList(Pair.of("", cmdLine.getOptionValue("query"))); } else if (cmdLine.hasOption("list-file")) { if (!(cmdLine.hasOption("inchi-field") && cmdLine.hasOption("synonym-field"))) { LOGGER.error("Must specify both inchi-field and synonym-field when using list-file."); System.exit(1); } Integer inchiField = Integer.parseInt(cmdLine.getOptionValue("inchi-field")); Integer synonymField = Integer.parseInt(cmdLine.getOptionValue("synonym-field")); queries = new LinkedList<>(); BufferedReader r = new BufferedReader(new FileReader(cmdLine.getOptionValue("list-file"))); String line; while ((line = r.readLine()) != null) { line = line.trim(); if (!line.isEmpty()) { // TODO: use a proper TSV reader; this is intentionally terrible as is. String[] fields = line.split("\t"); queries.add(Pair.of(fields[inchiField].replace("\"", ""), fields[synonymField])); } } r.close(); } if (queries == null || queries.size() == 0) { LOGGER.error("Found no queries to run."); return; } List<SearchResult> searchResults = new ArrayList<>(queries.size()); for (Pair<String, String> queryPair : queries) { String inchi = queryPair.getLeft(); String rawQueryString = queryPair.getRight(); /* The Lucene query parser interprets the kind of structural annotations we see in chemical entities * as query directives, which is not what we want at all. Phrase queries seem to work adequately * with the analyzer we're currently using. */ String queryString = rawQueryString.trim().toLowerCase(); String[] parts = queryString.split("\\s+"); PhraseQuery query = new PhraseQuery(); for (String p : parts) { query.add(new Term(field, p)); } LOGGER.info("Running query: " + query.toString()); BooleanQuery bq = new BooleanQuery(); bq.add(query, BooleanClause.Occur.MUST); bq.add(new TermQuery(new Term(field, "yeast")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "ferment")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "fermentation")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "fermentive")), BooleanClause.Occur.SHOULD); bq.add(new TermQuery(new Term(field, "saccharomyces")), BooleanClause.Occur.SHOULD); LOGGER.info(" Full query: " + bq.toString()); TopDocs topDocs = searcher.search(bq, 100); ScoreDoc[] scoreDocs = topDocs.scoreDocs; if (scoreDocs.length == 0) { LOGGER.info("Search returned no results."); } List<ResultDocument> results = new ArrayList<>(scoreDocs.length); for (int i = 0; i < scoreDocs.length; i++) { ScoreDoc scoreDoc = scoreDocs[i]; Document doc = indexReader.document(scoreDoc.doc); LOGGER.info("Doc " + i + ": " + scoreDoc.doc + ", score " + scoreDoc.score + ": " + doc.get("id") + ", " + doc.get("title")); results.add(new ResultDocument(scoreDoc.doc, scoreDoc.score, doc.get("title"), doc.get("id"), null)); } LOGGER.info("----- Done with query " + query.toString()); // TODO: reduce memory usage when not writing results to an output file. searchResults.add(new SearchResult(inchi, rawQueryString, bq, results)); } if (cmdLine.hasOption("output")) { try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"));) { writer.write(objectMapper.writeValueAsString(searchResults)); } } } } }
From source file:at.ac.tuwien.inso.subcat.postprocessor.PostProcessor.java
public static void main(String[] args) { Map<String, PostProcessorTask> steps = new HashMap<String, PostProcessorTask>(); PostProcessorTask _step = new ClassificationTask(); steps.put(_step.getName(), _step);//w w w. j av a 2 s . c o m CommentAnalyserTask commentAnalysisStep = new CommentAnalyserTask(); steps.put(commentAnalysisStep.getName(), commentAnalysisStep); AccountInterlinkingTask interlinkingTask = new AccountInterlinkingTask(); steps.put(interlinkingTask.getName(), interlinkingTask); _step = new CommitBugInterlinkingTask(); steps.put(_step.getName(), _step); Options options = new Options(); options.addOption("h", "help", false, "Show this options"); options.addOption("d", "db", true, "The database to process (required)"); options.addOption("v", "verbose", false, "Show details"); options.addOption("p", "project", true, "The project ID to process"); options.addOption("P", "list-projects", false, "List all registered projects"); options.addOption("S", "list-processor-steps", false, "List all registered processor steps"); options.addOption("s", "processor-step", true, "A processor step name"); options.addOption("c", "commit-dictionary", true, "Path to a classification dictionary for commit message classification"); options.addOption("b", "bug-dictionary", true, "Path to a classification dictionary for bug classification"); options.addOption("m", "smart-matching", true, "Smart user matching configuration. Syntax: <method>:<distance>"); options.addOption("M", "list-matching-methods", false, "List smart matching methods"); final Reporter reporter = new Reporter(true); reporter.startTimer(); Settings settings = new Settings(); ModelPool pool = null; boolean printTraces = false; CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); printTraces = cmd.hasOption("verbose"); if (cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("postprocessor", options); return; } if (cmd.hasOption("list-processor-steps")) { for (String proj : steps.keySet()) { System.out.println(" " + proj); } return; } if (cmd.hasOption("list-matching-methods")) { for (String method : HashFunc.getHashFuncNames()) { System.out.println(" " + method); } return; } if (cmd.hasOption("db") == false) { reporter.error("post-processor", "Option --db is required"); reporter.printSummary(); return; } File dbf = new File(cmd.getOptionValue("db")); if (dbf.exists() == false || dbf.isFile() == false) { reporter.error("post-processor", "Invalid database file path"); reporter.printSummary(); return; } pool = new ModelPool(cmd.getOptionValue("db"), 2); if (cmd.hasOption("list-projects")) { Model model = pool.getModel(); for (Project proj : model.getProjects()) { System.out.println(" " + proj.getId() + ": " + proj.getDate()); } model.close(); return; } Integer projId = null; if (cmd.hasOption("project") == false) { reporter.error("post-processor", "Option --project is required"); reporter.printSummary(); return; } else { try { projId = Integer.parseInt(cmd.getOptionValue("project")); } catch (NumberFormatException e) { reporter.error("post-processor", "Invalid project ID"); reporter.printSummary(); return; } } Model model = pool.getModel(); Project project = model.getProject(projId); model.close(); if (project == null) { reporter.error("post-processor", "Invalid project ID"); reporter.printSummary(); return; } if (cmd.hasOption("bug-dictionary")) { DictionaryParser dp = new DictionaryParser(); for (String path : cmd.getOptionValues("bug-dictionary")) { try { Dictionary dict = dp.parseFile(path); settings.bugDictionaries.add(dict); } catch (FileNotFoundException e) { reporter.error("post-processor", "File not found: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } catch (XmlReaderException e) { reporter.error("post-processor", "XML Error: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } } } if (cmd.hasOption("commit-dictionary")) { DictionaryParser dp = new DictionaryParser(); for (String path : cmd.getOptionValues("commit-dictionary")) { try { Dictionary dict = dp.parseFile(path); settings.srcDictionaries.add(dict); } catch (FileNotFoundException e) { reporter.error("post-processor", "File not found: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } catch (XmlReaderException e) { reporter.error("post-processor", "XML Error: " + path + ": " + e.getMessage()); reporter.printSummary(); return; } } } if (cmd.hasOption("smart-matching")) { String str = cmd.getOptionValue("smart-matching"); String[] parts = str.split(":"); if (parts.length != 2) { reporter.error("post-processor", "Unexpected smart-matching format"); reporter.printSummary(); return; } HashFunc func = HashFunc.getHashFunc(parts[0]); if (func == null) { reporter.error("post-processor", "Unknown smart matching hash function"); reporter.printSummary(); return; } int dist = -1; try { dist = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { dist = -1; } if (dist < 0) { reporter.error("post-processor", "Invalid smart matching edist distance"); reporter.printSummary(); return; } interlinkingTask.setDistance(dist); interlinkingTask.setHashFunc(func); } PostProcessor processor = new PostProcessor(project, pool, settings); if (cmd.hasOption("processor-step")) { for (String stepName : cmd.getOptionValues("processor-step")) { PostProcessorTask step = steps.get(stepName); if (step == null) { reporter.error("post-processor", "Unknown processor step: '" + stepName + "'"); reporter.printSummary(); return; } processor.register(step); } } else { processor.register(steps.values()); } if (printTraces == true) { model = pool.getModel(); final Stats stats = model.getStats(project); model.close(); processor.addListener(new PostProcessorListener() { private int commitCount = 0; private int bugCount = 0; @Override public void commit(PostProcessor proc) { commitCount++; reporter.note("post-processor", "status: Commit " + commitCount + "/" + stats.commitCount); } @Override public void bug(PostProcessor proc) { bugCount++; reporter.note("post-processor", "status: Bug " + bugCount + "/" + stats.bugCount); } }); } processor.process(); } catch (ParseException e) { reporter.error("post-processor", "Parsing failed: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (ClassNotFoundException e) { reporter.error("post-processor", "Failed to create a database connection: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (SQLException e) { reporter.error("post-processor", "Failed to create a database connection: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } catch (PostProcessorException e) { reporter.error("post-processor", "Post-Processor Error: " + e.getMessage()); if (printTraces == true) { e.printStackTrace(); } } finally { if (pool != null) { pool.close(); } } reporter.printSummary(true); }
From source file:com.xiangzhurui.util.ftp.ServerToServerFTP.java
public static void main(String[] args) { String server1, username1, password1, file1; String server2, username2, password2, file2; String[] parts;/*from w w w .j av a2s.c om*/ int port1 = 0, port2 = 0; FTPClient ftp1, ftp2; ProtocolCommandListener listener; if (args.length < 8) { System.err.println( "Usage: com.xzr.practice.util.ftp <host1> <user1> <pass1> <file1> <host2> <user2> <pass2> <file2>"); System.exit(1); } server1 = args[0]; parts = server1.split(":"); if (parts.length == 2) { server1 = parts[0]; port1 = Integer.parseInt(parts[1]); } username1 = args[1]; password1 = args[2]; file1 = args[3]; server2 = args[4]; parts = server2.split(":"); if (parts.length == 2) { server2 = parts[0]; port2 = Integer.parseInt(parts[1]); } username2 = args[5]; password2 = args[6]; file2 = args[7]; listener = new PrintCommandListener(new PrintWriter(System.out), true); ftp1 = new FTPClient(); ftp1.addProtocolCommandListener(listener); ftp2 = new FTPClient(); ftp2.addProtocolCommandListener(listener); try { int reply; if (port1 > 0) { ftp1.connect(server1, port1); } else { ftp1.connect(server1); } System.out.println("Connected to " + server1 + "."); reply = ftp1.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp1.disconnect(); System.err.println("FTP server1 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp1.isConnected()) { try { ftp1.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server1."); e.printStackTrace(); System.exit(1); } try { int reply; if (port2 > 0) { ftp2.connect(server2, port2); } else { ftp2.connect(server2); } System.out.println("Connected to " + server2 + "."); reply = ftp2.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp2.disconnect(); System.err.println("FTP server2 refused connection."); System.exit(1); } } catch (IOException e) { if (ftp2.isConnected()) { try { ftp2.disconnect(); } catch (IOException f) { // do nothing } } System.err.println("Could not connect to server2."); e.printStackTrace(); System.exit(1); } __main: try { if (!ftp1.login(username1, password1)) { System.err.println("Could not login to " + server1); break __main; } if (!ftp2.login(username2, password2)) { System.err.println("Could not login to " + server2); break __main; } // Let's just assume success for now. ftp2.enterRemotePassiveMode(); ftp1.enterRemoteActiveMode(InetAddress.getByName(ftp2.getPassiveHost()), ftp2.getPassivePort()); // Although you would think the store command should be sent to // server2 // first, in reality, com.xzr.practice.util.ftp servers like wu-ftpd start accepting data // connections right after entering passive mode. Additionally, they // don't even send the positive preliminary reply until after the // transfer is completed (in the case of passive mode transfers). // Therefore, calling store first would hang waiting for a // preliminary // reply. if (ftp1.remoteRetrieve(file1) && ftp2.remoteStoreUnique(file2)) { // if(ftp1.remoteRetrieve(file1) && ftp2.remoteStore(file2)) { // We have to fetch the positive completion reply. ftp1.completePendingCommand(); ftp2.completePendingCommand(); } else { System.err.println("Couldn't initiate transfer. Check that filenames are valid."); break __main; } } catch (IOException e) { e.printStackTrace(); System.exit(1); } finally { try { if (ftp1.isConnected()) { ftp1.logout(); ftp1.disconnect(); } } catch (IOException e) { // do nothing } try { if (ftp2.isConnected()) { ftp2.logout(); ftp2.disconnect(); } } catch (IOException e) { // do nothing } } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step4MTurkOutputCollector.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDirWithArgumentPairs = args[0]; File[] resultFiles;/*from w w w. j a v a 2s .c om*/ if (args[1].contains("*")) { File path = new File(args[1]); File directory = path.getParentFile(); String regex = path.getName().replaceAll("\\*", ""); List<File> files = new ArrayList<>(FileUtils.listFiles(directory, new String[] { regex }, false)); resultFiles = new File[files.size()]; for (int i = 0; i < files.size(); i++) { resultFiles[i] = files.get(i); } } else { // result file is a comma-separated list of CSV files from MTurk String[] split = args[1].split(","); resultFiles = new File[split.length]; for (int i = 0; i < split.length; i++) { resultFiles[i] = new File(split[i]); } } File outputDir = new File(args[2]); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { throw new IOException("Cannot create directory " + outputDir); } } // error if output folder not empty to prevent any confusion by mixing files if (!FileUtils.listFiles(outputDir, null, false).isEmpty()) { throw new IllegalArgumentException("Output dir " + outputDir + " is not empty"); } // collected assignments with empty reason for rejections Set<String> assignmentsWithEmptyReason = new HashSet<>(); // parse with first line as header MTurkOutputReader mTurkOutputReader = new MTurkOutputReader(resultFiles); Collection<File> files = FileUtils.listFiles(new File(inputDirWithArgumentPairs), new String[] { "xml" }, false); if (files.isEmpty()) { throw new IOException("No xml files found in " + inputDirWithArgumentPairs); } // statistics: how many hits with how many assignments ; hit ID / assignments Map<String, Map<String, Integer>> assignmentsPerHits = new HashMap<>(); // collect accept/reject statistics for (Map<String, String> record : mTurkOutputReader) { boolean wasRejected = "Rejected".equals(record.get("assignmentstatus")); String hitID = record.get("hitid"); String hitTypeId = record.get("hittypeid"); if (!wasRejected) { // update statistics if (!assignmentsPerHits.containsKey(hitTypeId)) { assignmentsPerHits.put(hitTypeId, new HashMap<String, Integer>()); } if (!assignmentsPerHits.get(hitTypeId).containsKey(hitID)) { assignmentsPerHits.get(hitTypeId).put(hitID, 0); } assignmentsPerHits.get(hitTypeId).put(hitID, assignmentsPerHits.get(hitTypeId).get(hitID) + 1); } } // statistics: how many hits with how many assignments ; hit ID / assignments Map<String, Integer> approvedAssignmentsPerHit = new HashMap<>(); Map<String, Integer> rejectedAssignmentsPerHit = new HashMap<>(); // collect accept/reject statistics for (Map<String, String> record : mTurkOutputReader) { boolean approved = "Approved".equals(record.get("assignmentstatus")); boolean rejected = "Rejected".equals(record.get("assignmentstatus")); String hitID = record.get("hitid"); if (approved) { // update statistics if (!approvedAssignmentsPerHit.containsKey(hitID)) { approvedAssignmentsPerHit.put(hitID, 0); } approvedAssignmentsPerHit.put(hitID, approvedAssignmentsPerHit.get(hitID) + 1); } else if (rejected) { // update statistics if (!rejectedAssignmentsPerHit.containsKey(hitID)) { rejectedAssignmentsPerHit.put(hitID, 0); } rejectedAssignmentsPerHit.put(hitID, rejectedAssignmentsPerHit.get(hitID) + 1); } else { throw new IllegalStateException( "Unknown state: " + record.get("assignmentstatus") + " HITID: " + hitID); } } // System.out.println("Approved: " + approvedAssignmentsPerHit); // System.out.println("Rejected: " + rejectedAssignmentsPerHit); System.out.println("Approved (values): " + new HashSet<>(approvedAssignmentsPerHit.values())); System.out.println("Rejected (values): " + new HashSet<>(rejectedAssignmentsPerHit.values())); // rejection statistics int totalRejected = 0; for (Map.Entry<String, Integer> rejectionEntry : rejectedAssignmentsPerHit.entrySet()) { totalRejected += rejectionEntry.getValue(); } System.out.println("Total rejections: " + totalRejected); /* // generate .success files for adding more annotations for (File resultFile : resultFiles) { String hitTypeID = mTurkOutputReader.getHitTypeIdForFile().get(resultFile); // assignments for that hittypeid (= file) Map<String, Integer> assignments = assignmentsPerHits.get(hitTypeID); prepareUpdateHITsFiles(assignments, hitTypeID, resultFile); } */ int totalSavedPairs = 0; // load all previously prepared argument pairs for (File file : files) { List<ArgumentPair> argumentPairs = (List<ArgumentPair>) XStreamTools.getXStream().fromXML(file); List<AnnotatedArgumentPair> annotatedArgumentPairs = new ArrayList<>(); for (ArgumentPair argumentPair : argumentPairs) { AnnotatedArgumentPair annotatedArgumentPair = new AnnotatedArgumentPair(argumentPair); // is there such an answer? String key = "Answer." + argumentPair.getId(); // iterate only if there is such column to save time if (mTurkOutputReader.getColumnNames().contains(key)) { // now find the results for (Map<String, String> record : mTurkOutputReader) { if (record.containsKey(key)) { // extract the values AnnotatedArgumentPair.MTurkAssignment assignment = new AnnotatedArgumentPair.MTurkAssignment(); boolean wasRejected = "Rejected".equals(record.get("assignmentstatus")); // only non-rejected (if required) if (!wasRejected) { String hitID = record.get("hitid"); String workerID = record.get("workerid"); String assignmentId = record.get("assignmentid"); try { assignment.setAssignmentAcceptTime( DATE_FORMAT.parse(record.get("assignmentaccepttime"))); assignment.setAssignmentSubmitTime( DATE_FORMAT.parse(record.get("assignmentsubmittime"))); assignment.setHitComment(record.get("Answer.feedback")); assignment.setHitID(hitID); assignment.setTurkID(workerID); assignment.setAssignmentId(assignmentId); // and answer specific fields String valueRaw = record.get(key); // so far the label has had format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal // strip now only true label String label = valueRaw.split("_")[2]; assignment.setValue(label); String reason = record.get(key + "_reason"); // missing reason if (reason == null) { assignmentsWithEmptyReason.add(assignmentId); } else { assignment.setReason(reason); // get worker's stance String stanceRaw = record.get(key + "_stance"); if (stanceRaw != null) { // parse stance String stance = stanceRaw.split("_stance_")[1]; assignment.setWorkerStance(stance); } // we take maximal 5 assignments Collections.sort(annotatedArgumentPair.mTurkAssignments, new Comparator<AnnotatedArgumentPair.MTurkAssignment>() { @Override public int compare(AnnotatedArgumentPair.MTurkAssignment o1, AnnotatedArgumentPair.MTurkAssignment o2) { return o1.getAssignmentAcceptTime() .compareTo(o2.getAssignmentAcceptTime()); } }); if (annotatedArgumentPair.mTurkAssignments .size() < MAXIMUM_ASSIGNMENTS_PER_HIT) { annotatedArgumentPair.mTurkAssignments.add(assignment); } } } catch (IllegalArgumentException | NullPointerException ex) { System.err.println("Malformed annotations for HIT " + hitID + ", worker " + workerID + ", assignment " + assignmentId + "; " + ex.getMessage() + ", full record: " + record); } } } } } // and if there are some annotations, add it to the result set if (!annotatedArgumentPair.mTurkAssignments.isEmpty()) { annotatedArgumentPairs.add(annotatedArgumentPair); } } if (!annotatedArgumentPairs.isEmpty()) { File outputFile = new File(outputDir, file.getName()); XStreamTools.toXML(annotatedArgumentPairs, outputFile); System.out.println("Saved " + annotatedArgumentPairs.size() + " annotated pairs to " + outputFile); totalSavedPairs += annotatedArgumentPairs.size(); } } System.out.println("Total saved " + totalSavedPairs + " pairs"); // print assignments with empty reasons if (!assignmentsWithEmptyReason.isEmpty()) { System.out.println( "== Assignments with empty reason:\nassignmentIdToReject\tassignmentIdToRejectComment"); for (String assignmentId : assignmentsWithEmptyReason) { System.out.println( assignmentId + "\t\"Dear worker, you did not fill the required field with a reason.\""); } } }
From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java
public static void main(String[] args) { String target = "Content-Disposition: attachment; filename=dubbo-dubbo-2.4.11.zip"; String[] splits = target.split(";"); if (splits.length >= 2) { String name = splits[1].trim().split("=")[1].trim(); System.out.println(name); }/* ww w . ja va2s . co m*/ }
From source file:cn.util.RSAUtils.java
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub // HashMap<String, Object> map = RSAUtils.getKeys(); // //??/*from w w w. jav a2 s . c o m*/ // RSAPublicKey publicKey = (RSAPublicKey) map.get("public"); // RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private"); // String ming = "wow"; //?? RSAPublicKey pubKey = RSAUtils.getPublicKey(); RSAPrivateKey priKey = RSAUtils.getPrivateKey(); System.err.println(":" + Base64Util.encryptBASE64(pubKey.getEncoded())); System.err.println("?:" + Base64Util.encryptBASE64(priKey.getEncoded())); //? String mi = RSAUtils.encryptByPublicKey(ming); System.err.println("?:" + mi); //? //mi="aYlJTFE+cQjwsVkhmQrFnlwSPSidfPFbSaez8qw47xEfqwhPHX9na+7KoFwere3F2Incr0OoBhNt\nK8cqKwHtzuvJMW3/rz0X8n9Jld22lrsh9TOcEiq3Xwk3jTfNhGNnOEQIsOYVZs3Qqumdm0tAu7y6\nBHSE8kbfhRIPsqOys+0="; String[] mis = mi.split("#"); String ming1 = ""; for (String string : mis) { ming1 += RSAUtils.decryptByPrivateKey(string); } System.err.println("?:" + ming); System.err.println("?:" + ming1); // String a = "cVqjXrpazESBCFmZy5HxIy+C5o0PbYk9iCtBHBCGi8TMRPp2LpsVblrZIGrCw4s/fPEJp5pL7pBfZw4HDx412OfQpMCxezTltNNRWQBbFYCz/FHj6GeX7KAnkZhTC4hTZSHp1EyIa5EMsF6xdFtHuki98KS+75L3Z1Iln1efk2Y="; // System.out.println(RSAUtils.decryptByPrivateKey(a)); // System.out.println(RSAUtils.decryptByPrivateKey(null)); // RSAPrivateKey privateKey = getPrivateKey(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); // //int key_len = privateKey.getModulus().bitLength() / 8; String srcstring = "NKUsmMdJpSeAVFSk3hMwBoWsA7t/wOMc8hfzo2dwPIULOo1y0AUwPTDxVLw7AK1888rdyp/3U38y5eQUjuNQH68XN4jm7MHdRm+bnO6XUHuZLiXNFkLpVCAM5hVh6TTcOz3QIE9rhP+Up1WRxnq/PDuM/cXIeNWjBLbW4Iic9/w=#fRdhSf+a3xVktmJ6J0AJTW30wqpwQslN0Bxdyzpyr6u6VEj/Vo/5MpzZsVeIyBU/CzVvvkrvs5LKTagaA3M4thH3mz4gfMTrw746n4NhujZEUEehvNQIFdUBjKWPAI0XUtdcQQTtdUJbIWmuhTYxKParm0G8cNz5DSTRUTIw2fQ=#a9CaDtGkhVQNwgxHl0oJ8I/383pE3kE8yF76OyDtfeQsT50izuk44xQ34ersgzKkKSA8IB0W3SSw2bedsaj8A9dxrSf+S8S8w/Sg3G3/IA8pKaQqJD4idTCUFxjczf32aQbv+eUbs7fenAPKb3rpn+R+Q/c5y6jTEG5h+H27MsY=#N/dn52TTgJ+EoxTSp3weagZ+ggrIPl4rtKfzo0f/j2lMtXMfCQN7xgGiwDpv4Rele/58NV2X0ezDXjB3wtVugIA3nhKSNnsjEs/os1Zl2XO1EKuTnLGSJFSPS6yyr4o0wxHEeA52qA1UXaYS9clpjraXCDWuRrTpyQfONVDXGZ4=#P48NIZj+L8stk0CCNwAQmKZPH0/7GfOhhc9s/MONVPHBPRYo9N47Kb71PJszhrLsoEM2/VZD1Ech4HH8UmWhW6XPnVAWy/lS1nZDD/GEoTZvoN4Rw7oiWUGj2i+2SMyjcET9mnVPBUrgTmP8He5OFV6oIa1mAN95V4UkbXwYApw=#h79I/zTTAc2TA7j4k2wq5hrotElhskZudnuTViRvR2Ot9rAlFzdl1WasY0e+9pi7dCi40F5+2U7eVNuWLA9qvFKwgUSxA+z6FI++p0fAGsboJna9qwcplByYWh6DFPiPVFlRD2CTOZU+U/rfFn8wRT/qgLGyNI23/2el0fC1Bb0="; String stringarray[] = srcstring.split("#"); List<byte[]> srcArrays = new ArrayList<byte[]>(); for (String stemp : stringarray) { byte[] byte_temp = Base64Util.decryptBASE64(stemp); byte_temp = cipher.doFinal(byte_temp); srcArrays.add(byte_temp); } byte[] byte_sta = sysCopy(srcArrays); System.err.println(new String(byte_sta)); }