List of usage examples for java.util List size
int size();
From source file:io.fluo.webindex.data.Copy.java
public static void main(String[] args) throws Exception { if (args.length != 3) { log.error("Usage: Copy <pathsFile> <range> <dest>"); System.exit(1);//from w w w .ja v a 2 s . c o m } final String hadoopConfDir = IndexEnv.getHadoopConfDir(); final List<String> copyList = IndexEnv.getPathsRange(args[0], args[1]); if (copyList.isEmpty()) { log.error("No files to copy given {} {}", args[0], args[1]); System.exit(1); } DataConfig dataConfig = DataConfig.load(); SparkConf sparkConf = new SparkConf().setAppName("webindex-copy"); try (JavaSparkContext ctx = new JavaSparkContext(sparkConf)) { FileSystem hdfs = FileSystem.get(ctx.hadoopConfiguration()); Path destPath = new Path(args[2]); if (!hdfs.exists(destPath)) { hdfs.mkdirs(destPath); } log.info("Copying {} files (Range {} of paths file {}) from AWS to HDFS {}", copyList.size(), args[1], args[0], destPath.toString()); JavaRDD<String> copyRDD = ctx.parallelize(copyList, dataConfig.getNumExecutorInstances()); final String prefix = DataConfig.CC_URL_PREFIX; final String destDir = destPath.toString(); copyRDD.foreachPartition(iter -> { FileSystem fs = IndexEnv.getHDFS(hadoopConfDir); iter.forEachRemaining(ccPath -> { try { Path dfsPath = new Path(destDir + "/" + getFilename(ccPath)); if (fs.exists(dfsPath)) { log.error("File {} exists in HDFS and should have been previously filtered", dfsPath.getName()); } else { String urlToCopy = prefix + ccPath; log.info("Starting copy of {} to {}", urlToCopy, destDir); try (OutputStream out = fs.create(dfsPath); BufferedInputStream in = new BufferedInputStream( new URL(urlToCopy).openStream())) { IOUtils.copy(in, out); } log.info("Created {}", dfsPath.getName()); } } catch (IOException e) { log.error("Exception while copying {}", ccPath, e); } }); }); } }
From source file:com.yobidrive.diskmap.DiskMapStore.java
public static void main(String[] args) { try {//w ww . j a va 2 s . c om BasicConfigurator.configure(); // (String storeName, String logPath, String keyPath, long ckeckPointPeriod, long logSize, int keySize, // long mapSize, int packInterval, int readThreads, long needleCachedEntries, long bucketCachedBytes, short nodeId) /* String path = "/Users/david/Documents/NEEDLES"; if ( args.length > 0) { path = args[0]; } System.out.println("Using directory:" + path); */ DiskMapStore dms = new DiskMapStore("teststore", "/drive_hd1;/drive_hd2", "/drive_ssd/storage_indexes", 1000L, // Synching period 60000 * 5L, // Checkpointing period 2000000000L, // Log file size 100, // Key max size 2048, // Nb of buffers 32768, // Nb of entries (buckets) per buffer 60, // Compact interval 8, // Read threads TEST_COUNT / 3 * 2 * 140, // NeedleHeaderCachedEntries (1/20 in cache, 1/2 of typical data set) TEST_COUNT / 3 * 2 * 140, // NeedleCachedBytes (3% of Map, weights 120 bytes/entry) true, // Use needle average age instead of needle yougest age (short) 0, 1, 1, 1); // dmm.getBtm().getCheckPoint().copyFrom(new NeedlePointer()) ; // Removes checkpoint dms.initialize(); // System.out.println("Start read for "+TEST_COUNT+" pointers") ; Date startDate = new Date(); Date lapDate = new Date(); System.out.println("Start read test for " + TEST_COUNT + " pointers"); long counter = 0; long lapCounter = 0; startDate = new Date(); lapDate = new Date(); long failCount = 0; counter = 0; while (counter < TEST_COUNT) { String key = "MYVERYNICELEY" + counter; // System.out.println("key="+key+"...") ; List<Versioned<byte[]>> values = dms.get(new ByteArray(key.getBytes("UTF-8")), null); if (values.size() <= 0) { failCount++; } else { // Gets previous version byte[] value = values.get(0).getValue(); if (value == null) failCount++; else if (value[0] != (byte) ((short) counter % 128)) failCount++; } counter++; Date lapDate2 = new Date(); long spent = lapDate2.getTime() - lapDate.getTime(); if (spent >= 1000 || (counter - lapCounter > TARGET_TPSR)) { // Check each second or target tps if (spent < 1000) { // pause when tps reached Thread.sleep(1000 - spent); // System.out.print(".") ; } else // System.out.print("*") ; lapDate = lapDate2; // Reset lap time lapCounter = counter; // Reset tps copunter } } long timeSpent = new Date().getTime() - startDate.getTime(); System.out.println("\n\nProcessed reading of " + TEST_COUNT + " pointers \n" + "\tTotal time: " + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT * 1000 / timeSpent) + " tps\n" + "\tBad results: " + failCount); startDate = new Date(); lapDate = new Date(); System.out.println("Start write test for " + TEST_COUNT + " pointers"); counter = 0; lapCounter = 0; while (counter < TEST_COUNT) { String key = "MYVERYNICELEY" + counter; // System.out.println("key="+key+"...") ; byte[] value = new byte[128000]; value[0] = (byte) ((short) counter % 128); long chaseDurer = new Date().getTime(); List<Versioned<byte[]>> previousValues = dms.get(new ByteArray(key.getBytes("UTF-8")), null); long chaseDurer2 = new Date().getTime(); // System.out.println("Get in "+(chaseDurer2 -chaseDurer)+"ms") ; chaseDurer = chaseDurer2; Version newVersion = null; if (previousValues.size() <= 0) { newVersion = new VectorClock(); } else { // Gets previous version newVersion = previousValues.get(0).cloneVersioned().getVersion(); } // Increment version before writing ((VectorClock) newVersion).incrementVersion(0, new Date().getTime()); Versioned<byte[]> versionned = new Versioned<byte[]>( previousValues.size() <= 0 ? value : previousValues.get(0).cloneVersioned().getValue(), newVersion); dms.put(new ByteArray(key.getBytes("UTF-8")), versionned, null); chaseDurer2 = new Date().getTime(); // System.out.println("Put in "+(chaseDurer2 -chaseDurer)+"ms") ; // dmm.putValue(key.getBytes("UTF-8"), value) ; counter++; Date lapDate2 = new Date(); long spent = lapDate2.getTime() - lapDate.getTime(); if (spent >= 1000 || (counter - lapCounter > TARGET_TPS)) { // Check each second or target tps if (spent < 1000) { // pause when tps reached Thread.sleep(1000 - spent); // System.out.print("("+counter+")") ; } else // System.out.print("["+counter+"]") ; lapDate = lapDate2; // Reset lap time lapCounter = counter; // Reset tps copunter } } timeSpent = new Date().getTime() - startDate.getTime(); System.out.println("\n\nWriting before cache commit of " + TEST_COUNT + " pointers \n" + "\tTotal time: " + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT * 1000 / timeSpent) + " tps"); System.out.println("Start read for " + TEST_COUNT + " pointers"); startDate = new Date(); lapDate = new Date(); failCount = 0; counter = 0; while (counter < TEST_COUNT) { String key = "MYVERYNICELEY" + counter; // System.out.println("key="+key+"...") ; List<Versioned<byte[]>> values = dms.get(new ByteArray(key.getBytes("UTF-8")), null); if (values.size() <= 0) { failCount++; } else { // Gets previous version byte[] value = values.get(0).getValue(); if (value == null) failCount++; else if (value[0] != (byte) ((short) counter % 128)) failCount++; } counter++; Date lapDate2 = new Date(); long spent = lapDate2.getTime() - lapDate.getTime(); if (spent >= 1000 || (counter - lapCounter > TARGET_TPSR)) { // Check each second or target tps if (spent < 1000) { // pause when tps reached Thread.sleep(1000 - spent); // System.out.print(".") ; } else // System.out.print("*") ; lapDate = lapDate2; // Reset lap time lapCounter = counter; // Reset tps copunter } } timeSpent = new Date().getTime() - startDate.getTime(); System.out.println("\n\nProcessed reading of " + TEST_COUNT + " pointers \n" + "\tTotal time: " + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT * 1000 / timeSpent) + " tps\n" + "\tBad results: " + failCount); dms.close(); // System.out.println("Max cycle time = "+ (dms.getBtm().getMaxCycleTimePass1()+dmm.getBtm().getMaxCycleTimePass2())) ; } catch (Throwable th) { th.printStackTrace(); } }
From source file:bear.core.BearMain.java
/** * -VbearMain.appConfigDir=src/main/groovy/examples -VbearMain.buildDir=.bear/classes -VbearMain.script=dumpSampleGrid -VbearMain.projectClass=SecureSocialDemoProject -VbearMain.propertiesFile=.bear/test.properties *///from ww w .ja v a2s . c o m public static void main(String[] args) throws Exception { int i = ArrayUtils.indexOf(args, "--log-level"); if (i != -1) { LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.toLevel(args[i + 1])); } i = ArrayUtils.indexOf(args, "-q"); if (i != -1) { LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN); } GlobalContext global = GlobalContext.getInstance(); BearMain bearMain = null; try { bearMain = new BearMain(global, getCompilerManager(), args); } catch (Exception e) { if (e.getClass().getSimpleName().equals("MissingRequiredOptionException")) { System.out.println(e.getMessage()); } else { Throwables.getRootCause(e).printStackTrace(); } System.exit(-1); } if (bearMain.checkHelpAndVersion()) { return; } AppOptions2 options2 = bearMain.options; if (options2.has(AppOptions2.UNPACK_DEMOS)) { String filesAsText = ProjectGenerator.readResource("/demoFiles.txt"); int count = 0; for (String resource : filesAsText.split("::")) { File dest = new File(BEAR_DIR + resource); System.out.printf("copying %s to %s...%n", resource, dest); writeStringToFile(dest, ProjectGenerator.readResource(resource)); count++; } System.out.printf("extracted %d files%n", count); return; } if (options2.has(AppOptions2.CREATE_NEW)) { String dashedTitle = options2.get(AppOptions2.CREATE_NEW); String user = options2.get(AppOptions2.USER); String pass = options2.get(AppOptions2.PASSWORD); List<String> hosts = options2.getList(AppOptions2.HOSTS); List<String> template; if (options2.has(AppOptions2.TEMPLATE)) { template = options2.getList(AppOptions2.TEMPLATE); } else { template = emptyList(); } ProjectGenerator g = new ProjectGenerator(dashedTitle, user, pass, hosts, template); if (options2.has(AppOptions2.ORACLE_USER)) { g.oracleUser = options2.get(AppOptions2.ORACLE_USER); } if (options2.has(AppOptions2.ORACLE_PASSWORD)) { g.oraclePassword = options2.get(AppOptions2.ORACLE_PASSWORD); } File projectFile = new File(BEAR_DIR, g.getProjectTitle() + ".groovy"); File pomFile = new File(BEAR_DIR, "pom.xml"); writeStringToFile(projectFile, g.processTemplate("TemplateProject.template")); writeStringToFile(new File(BEAR_DIR, dashedTitle + ".properties"), g.processTemplate("project-properties.template")); writeStringToFile(new File(BEAR_DIR, "demos.properties"), g.processTemplate("project-properties.template")); writeStringToFile(new File(BEAR_DIR, "bear-fx.properties"), g.processTemplate("bear-fx.properties.template")); writeStringToFile(pomFile, g.generatePom(dashedTitle)); System.out.printf("Created project file: %s%n", projectFile.getPath()); System.out.printf("Created maven pom: %s%n", pomFile.getPath()); System.out.println("\nProject files have been created. You may now: " + "\n a) Run `bear " + g.getShortName() + ".ls` to quick-test your minimal setup" + "\n b) Import the project to IDE or run smoke tests, find more details at the project wiki: https://github.com/chaschev/bear/wiki/."); return; } Bear bear = global.bear; if (options2.has(AppOptions2.QUIET)) { global.put(bear.quiet, true); LoggingBooter.changeLogLevel(LogManager.ROOT_LOGGER_NAME, Level.WARN); } if (options2.has(AppOptions2.USE_UI)) { global.put(bear.useUI, true); } if (options2.has(AppOptions2.NO_UI)) { global.put(bear.useUI, false); } List<?> list = options2.getOptionSet().nonOptionArguments(); if (list.size() > 1) { throw new IllegalArgumentException("too many arguments: " + list + ", " + "please specify an invoke line, project.method(arg1, arg2)"); } if (list.isEmpty()) { throw new UnsupportedOperationException("todo implement running a single project"); } String invokeLine = (String) list.get(0); String projectName; String method; if (invokeLine.contains(".")) { projectName = StringUtils.substringBefore(invokeLine, "."); method = StringUtils.substringAfter(invokeLine, "."); } else { projectName = invokeLine; method = null; } if (method == null || method.isEmpty()) method = "deploy()"; if (!method.contains("(")) method += "()"; Optional<CompiledEntry<? extends BearProject>> optional = bearMain.compileManager.findProject(projectName); if (!optional.isPresent()) { throw new IllegalArgumentException("project was not found: " + projectName + ", loaded classes: \n" + Joiner.on("\n").join(bearMain.compileManager.findProjects()) + ", searched in: " + bearMain.compileManager.getSourceDirs() + ", "); } BearProject project = OpenBean.newInstance(optional.get().aClass).injectMain(bearMain); GroovyShell shell = new GroovyShell(); shell.setVariable("project", project); shell.evaluate("project." + method); }
From source file:com.mirth.connect.server.launcher.MirthLauncher.java
public static void main(String[] args) { try {// w ww . j av a 2s. c om try { uninstallPendingExtensions(); installPendingExtensions(); } catch (Exception e) { logger.error("Error uninstalling or installing pending extensions.", e); } Properties mirthProperties = new Properties(); String includeCustomLib = null; try { mirthProperties.load(new FileInputStream(new File(MIRTH_PROPERTIES_FILE))); includeCustomLib = mirthProperties.getProperty(PROPERTY_INCLUDE_CUSTOM_LIB); createAppdataDir(mirthProperties); } catch (Exception e) { logger.error("Error creating the appdata directory.", e); } ManifestFile mirthServerJar = new ManifestFile("server-lib/mirth-server.jar"); ManifestFile mirthClientCoreJar = new ManifestFile("server-lib/mirth-client-core.jar"); ManifestDirectory serverLibDir = new ManifestDirectory("server-lib"); serverLibDir.setExcludes(new String[] { "mirth-client-core.jar" }); List<ManifestEntry> manifestList = new ArrayList<ManifestEntry>(); manifestList.add(mirthServerJar); manifestList.add(mirthClientCoreJar); manifestList.add(serverLibDir); // We want to include custom-lib if the property isn't found, or if it equals "true" if (includeCustomLib == null || Boolean.valueOf(includeCustomLib)) { manifestList.add(new ManifestDirectory("custom-lib")); } ManifestEntry[] manifest = manifestList.toArray(new ManifestEntry[manifestList.size()]); // Get the current server version JarFile mirthClientCoreJarFile = new JarFile(mirthClientCoreJar.getName()); Properties versionProperties = new Properties(); versionProperties.load(mirthClientCoreJarFile .getInputStream(mirthClientCoreJarFile.getJarEntry("version.properties"))); String currentVersion = versionProperties.getProperty("mirth.version"); List<URL> classpathUrls = new ArrayList<URL>(); addManifestToClasspath(manifest, classpathUrls); addExtensionsToClasspath(classpathUrls, currentVersion); URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()])); Class<?> mirthClass = classLoader.loadClass("com.mirth.connect.server.Mirth"); Thread mirthThread = (Thread) mirthClass.newInstance(); mirthThread.setContextClassLoader(classLoader); mirthThread.start(); } catch (Exception e) { e.printStackTrace(); } }
From source file:ca.on.oicr.pde.deciders.GenomicAlignmentNovoalignDecider.java
public static void main(String args[]) { List<String> params = new ArrayList<String>(); params.add("--plugin"); params.add(GenomicAlignmentNovoalignDecider.class.getCanonicalName()); params.add("--"); params.addAll(Arrays.asList(args)); System.out.println("Parameters: " + Arrays.deepToString(params.toArray())); net.sourceforge.seqware.pipeline.runner.PluginRunner.main(params.toArray(new String[params.size()])); }
From source file:com.hp.test.framework.Reporting.Utlis.java
public static void main(String ar[]) throws IOException { ArrayList<String> runs_list = new ArrayList<String>(); String basepath = replacelogs(); String path = basepath + "ATU Reports\\Results"; File directory = new File(path); File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); String htmlReport = basepath + "HTML_Design_Files\\CSS\\HtmlReport.html"; for (File dir : subdirs) { runs_list.add(dir.getName());/*from ww w . j a v a2s .com*/ } String Reports_path = basepath + "ATU Reports\\"; int LatestRun = Utlis.getLastRun(Reports_path); String Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\"; HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html")); HtmlParse.replaceCountsinJSFile(new File("HTML_Design_Files/JS/3dChart.js"), Last_run_path); UpdateTestCaseDesciption.basepath = Last_run_path; UpdateTestCaseDesciption.getTestCaseHtmlPath(Last_run_path + "/CurrentRun.html"); UpdateTestCaseDesciption.replaceDetailsTable(Last_run_path + "/CurrentRun.html"); // GenerateFailReport.genarateFailureReport(new File(htmlReport), Reports_path + "Results\\Run_" + String.valueOf(LatestRun)); genarateFailureReport(new File(htmlReport), Reports_path + "Results\\"); Map<String, List<String>> runCounts = GetCountsrunsWise(runs_list, path); int success = replaceCounts(runCounts, path); if (success == 0) { File SourceFile = new File(path + "\\lineChart_temp.js"); File RenameFile = new File(path + "\\lineChart.js"); renameOriginalFile(SourceFile, RenameFile); File SourceFile1 = new File(path + "\\barChart_temp.js"); File RenameFile1 = new File(path + "\\barChart.js"); renameOriginalFile(SourceFile1, RenameFile1); Utlis.getpaths(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun)); try { Utlis.replaceMainTable(false, new File(Reports_path + "index.html")); Utlis.replaceMainTable(true, new File(Reports_path + "results\\" + "ConsolidatedPage.html")); Utlis.replaceMainTable(true, new File(Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); fileList.add( new File(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); for (File f : fileList) { Utlis.replaceMainTable(true, f); } } catch (Exception ex) { log.info("Error in updating Report format" + ex.getMessage()); } Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\"; // HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html")); // HtmlParse.replaceCountsinJSFile(new File("../HTML_Design_Files/JS/3dChart.js"), Last_run_path); ArrayList<String> to_list = new ArrayList<String>(); ReportingProperties reportingproperties = new ReportingProperties(); String temp_eml = reportingproperties.getProperty("TOLIST"); String JenkinsURL = reportingproperties.getProperty("JENKINSURL"); String ScreenShotsDir = reportingproperties.getProperty("ScreenShotsDirectory"); Boolean cleanScreenshotsDir = Boolean.valueOf(reportingproperties.getProperty("CleanPreScreenShots")); Boolean generatescreenshots = Boolean.valueOf(reportingproperties.getProperty("GenerateScreenShots")); String HtmlreportFilePrefix = reportingproperties.getProperty("HtmlreportFilePrefix"); if (cleanScreenshotsDir) { if (!CleanFilesinDir(ScreenShotsDir)) { log.error("Not able to Clean the Previous Run Details in the paht" + ScreenShotsDir); } else { log.info("Cleaning Previous Run Details in the paht" + ScreenShotsDir + "Sucess"); } } List<String> scr_fileList; List<String> html_fileList; if (generatescreenshots) { scr_fileList = GetFileListinDir(ScreenShotsDir, "png"); int len = scr_fileList.size(); len = len + 1; screenshot.generatescreenshot(Last_run_path + "CurrentRun.html", ScreenShotsDir + "screenshot_" + len + ".png"); File source = new File(Reports_path + "Results\\HtmlReport.html"); File dest = new File(ScreenShotsDir + HtmlreportFilePrefix + "_HtmlReport.html"); // Files.copy(f.toPath(), (new File((ScreenShotsDir+HtmlreportFilePrefix+"_HtmlReport.html").toPath(),StandardCopyOption.REPLACE_EXISTING); FileUtils.copyFile(source, dest); scr_fileList.clear(); } scr_fileList = GetFileListinDir(ScreenShotsDir, "png"); html_fileList = GetFileListinDir(ScreenShotsDir, "html"); if (temp_eml.length() > 1) { String[] to_list_temp = temp_eml.split(","); if (to_list_temp.length > 0) { for (String to_list_temp1 : to_list_temp) { to_list.add(to_list_temp1); } } if (to_list.size() > 0) { screenshot.generatescreenshot(Last_run_path + "CurrentRun.html", Last_run_path + "screenshot.png"); // cleanTempDir.cleanandCreate(Reports_path, LatestRun); // ZipUtils.ZipFolder(Reports_path + "temp", Reports_path + "ISTF_Reports.zip"); if (generatescreenshots) { SendingEmail.sendmail(to_list, JenkinsURL, scr_fileList, html_fileList); } else { SendingEmail.sendmail(to_list, JenkinsURL, Reports_path + "/Results/HtmlReport.html", Last_run_path + "screenshot.png"); } // FileUtils.deleteQuietly(new File(Reports_path + "ISTF_Reports.zip")); // FileUtils.deleteDirectory(new File(Reports_path + "temp")); } } } }
From source file:PopClean.java
public static void main(String args[]) { try {//from w ww. j a v a 2s .co m String hostname = null, username = null, password = null; int port = 110; int sizelimit = -1; String subjectPattern = null; Pattern pattern = null; Matcher matcher = null; boolean delete = false; boolean confirm = true; // Handle command-line arguments for (int i = 0; i < args.length; i++) { if (args[i].equals("-user")) username = args[++i]; else if (args[i].equals("-pass")) password = args[++i]; else if (args[i].equals("-host")) hostname = args[++i]; else if (args[i].equals("-port")) port = Integer.parseInt(args[++i]); else if (args[i].equals("-size")) sizelimit = Integer.parseInt(args[++i]); else if (args[i].equals("-subject")) subjectPattern = args[++i]; else if (args[i].equals("-debug")) debug = true; else if (args[i].equals("-delete")) delete = true; else if (args[i].equals("-force")) // don't confirm confirm = false; } // Verify them if (hostname == null || username == null || password == null || sizelimit == -1) usage(); // Make sure the pattern is a valid regexp if (subjectPattern != null) { pattern = Pattern.compile(subjectPattern); matcher = pattern.matcher(""); } // Say what we are going to do System.out .println("Connecting to " + hostname + " on port " + port + " with username " + username + "."); if (delete) { System.out.println("Will delete all messages longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } else { System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes"); if (subjectPattern != null) System.out.println("that have a subject matching: [" + subjectPattern + "]"); } // If asked to delete, ask for confirmation unless -force is given if (delete && confirm) { System.out.println(); System.out.print("Do you want to proceed (y/n) [n]: "); System.out.flush(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); String response = console.readLine(); if (!response.equals("y")) { System.out.println("No messages deleted."); System.exit(0); } } // Connect to the server, and set up streams s = new Socket(hostname, port); in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); // Read the welcome message from the server, confirming it is OK. System.out.println("Connected: " + checkResponse()); // Now log in send("USER " + username); // Send username, wait for response send("PASS " + password); // Send password, wait for response System.out.println("Logged in"); // Check how many messages are waiting, and report it String stat = send("STAT"); StringTokenizer t = new StringTokenizer(stat); System.out.println(t.nextToken() + " messages in mailbox."); System.out.println("Total size: " + t.nextToken()); // Get a list of message numbers and sizes send("LIST"); // Send LIST command, wait for OK response. // Now read lines from the server until we get . by itself List msgs = new ArrayList(); String line; for (;;) { line = in.readLine(); if (line == null) throw new IOException("Unexpected EOF"); if (line.equals(".")) break; msgs.add(line); } // Now loop through the lines we read one at a time. // Each line should specify the message number and its size. int nummsgs = msgs.size(); for (int i = 0; i < nummsgs; i++) { String m = (String) msgs.get(i); StringTokenizer st = new StringTokenizer(m); int msgnum = Integer.parseInt(st.nextToken()); int msgsize = Integer.parseInt(st.nextToken()); // If the message is too small, ignore it. if (msgsize <= sizelimit) continue; // If we're listing messages, or matching subject lines // find the subject line for this message String subject = null; if (!delete || pattern != null) { subject = getSubject(msgnum); // get the subject line // If we couldn't find a subject, skip the message if (subject == null) continue; // If this subject does not match the pattern, then // skip the message if (pattern != null) { matcher.reset(subject); if (!matcher.matches()) continue; } // If we are listing, list this message if (!delete) { System.out.println("Subject " + msgnum + ": " + subject); continue; // so we never delete it } } // If we were asked to delete, then delete the message if (delete) { send("DELE " + msgnum); if (pattern == null) System.out.println("Deleted message " + msgnum); else System.out.println("Deleted message " + msgnum + ": " + subject); } } // When we're done, log out and shutdown the connection shutdown(); } catch (Exception e) { // If anything goes wrong print exception and show usage System.err.println(e); usage(); // Always try to shutdown nicely so the server doesn't hang on us shutdown(); } }
From source file:IrqaQuery.java
/** Simple command-line based search demo. */ public static void main(String[] args) throws Exception { String basedir = "/Users/bong/works/research/irqa"; // String basedir = "/home/bgshin/works/irqa"; List<String> exps = new ArrayList<>(); exps.add("_c_2048"); // exps.add("_c_1024"); // exps.add("_c_512"); // exps.add("_c_256"); // exps.add("_c_128"); // exps.add("_c_64"); // exps.add("_c_32"); // exps.add("_c_16"); // exps.add("_c_8"); // exps.add("_c_4"); // exps.add("_c_2"); // exps.add("_c_0"); for (int i = 0; i < exps.size(); i++) { String indexpath = exps.get(i); batch_query(basedir, indexpath); }/*from w w w . j a v a 2s. c om*/ // pipeline ////////////////////////////////////////////////////////////// // JSONParser parser = new JSONParser(); // String lookup_sentfn = basedir+"/data/wikilookup_clean_sentence.json"; // Object obj1 = parser.parse(new FileReader(lookup_sentfn)); // JSONObject lookup_sent = (JSONObject) obj1; // // for (int i=0; i<exps.size(); i++) { // String indexpath = exps.get(i); // pipeline(basedir, indexpath, "dev", lookup_sent); // pipeline(basedir, indexpath, "test", lookup_sent); // pipeline(basedir, indexpath, "train", lookup_sent); // } // pipeline ////////////////////////////////////////////////////////////// }
From source file:esiptestbed.mudrod.ontology.process.LocalOntology.java
public static void main(String[] args) throws Exception { // boolean options Option helpOpt = new Option("h", "help", false, "show this help message"); // argument options Option ontDirOpt = Option.builder(ONT_DIR).required(true).numberOfArgs(1).hasArg(true) .desc("A directory containing .owl files.").argName(ONT_DIR).build(); // create the options Options options = new Options(); options.addOption(helpOpt);/*from w ww .j a v a2 s. co m*/ options.addOption(ontDirOpt); String ontDir; CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption(ONT_DIR)) { ontDir = line.getOptionValue(ONT_DIR).replace("\\", "/"); } else { ontDir = LocalOntology.class.getClassLoader().getResource("ontology").getFile(); } if (!ontDir.endsWith("/")) { ontDir += "/"; } } catch (Exception e) { LOG.error("Error whilst processing main method of LocalOntology.", e); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("LocalOntology: 'ontDir' argument is mandatory. ", options, true); return; } File fileDir = new File(ontDir); //Fail if the input is not a directory. if (fileDir.isDirectory()) { List<String> owlFiles = new ArrayList<>(); for (File owlFile : fileDir.listFiles()) { owlFiles.add(owlFile.toString()); } MudrodEngine mEngine = new MudrodEngine(); Properties props = mEngine.loadConfig(); Ontology ontology = new OntologyFactory(props).getOntology(); //convert to correct iput for ontology loading. String[] owlArray = new String[owlFiles.size()]; owlArray = owlFiles.toArray(owlArray); ontology.load(owlArray); String[] terms = new String[] { "Glacier ice" }; //Demonstrate that we can do basic ontology heirarchy navigation and log output. for (Iterator<OntClass> i = getParser().rootClasses(getModel()); i.hasNext();) { //print Ontology Class Hierarchy OntClass c = i.next(); renderHierarchy(System.out, c, new LinkedList<>(), 0); for (Iterator<OntClass> subClass = c.listSubClasses(true); subClass.hasNext();) { OntClass sub = subClass.next(); //This means that the search term is present as an OntClass if (terms[0].equalsIgnoreCase(sub.getLabel(null))) { //Add the search term(s) above to the term cache. for (int j = 0; j < terms.length; j++) { addSearchTerm(terms[j], sub); } //Query the ontology and return subclasses of the search term(s) for (int k = 0; k < terms.length; k++) { Iterator<String> iter = ontology.subclasses(terms[k]); while (iter.hasNext()) { LOG.info("Subclasses >> " + iter.next()); } } //print any synonymic relationships to demonstrate that we can //undertake synonym-based query expansion for (int l = 0; l < terms.length; l++) { Iterator<String> iter = ontology.synonyms(terms[l]); while (iter.hasNext()) { LOG.info("Synonym >> " + iter.next()); } } } } } mEngine.end(); } }
From source file:org.openimaj.demos.sandbox.PlotFlickrGeo.java
public static void main(String[] args) throws IOException { File inputcsv = new File("/Users/jsh2/Desktop/world-geo.csv"); List<float[]> data = new ArrayList<float[]>(10000000); //read in images BufferedReader br = new BufferedReader(new FileReader(inputcsv)); String line;/*from ww w . j av a 2s . c o m*/ int i = 0; while ((line = br.readLine()) != null) { String[] parts = line.split(","); float longitude = Float.parseFloat(parts[0]); float latitude = Float.parseFloat(parts[1]); data.add(new float[] { longitude, latitude }); if (i++ % 10000 == 0) System.out.println(i); } System.out.println("Done reading"); float[][] dataArr = new float[2][data.size()]; for (i = 0; i < data.size(); i++) { dataArr[0][i] = data.get(i)[0]; dataArr[1][i] = data.get(i)[1]; } NumberAxis domainAxis = new NumberAxis("X"); domainAxis.setRange(-180, 180); NumberAxis rangeAxis = new NumberAxis("Y"); rangeAxis.setRange(-90, 90); FastScatterPlot plot = new FastScatterPlot(dataArr, domainAxis, rangeAxis); JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot); chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); final ApplicationFrame frame = new ApplicationFrame("Title"); frame.setContentPane(chartPanel); frame.pack(); frame.setVisible(true); }