List of usage examples for java.util Vector elementAt
public synchronized E elementAt(int index)
From source file:com.intel.cosbench.driver.random.RangeIntGenerator.java
public static void main(String[] args) { final String pattern = "r(50,100)"; final int all = 5; int i = 0;//from ww w . jav a 2 s . c o m Vector<TestThread> threads = new Vector<TestThread>(); RangeIntGenerator gen = RangeIntGenerator.parse(pattern); for (i = 0; i < all; i++) { TestThread thread = new TestThread(gen, i + 1, all); threads.add(thread); thread.start(); } try { for (i = 0; i < all; i++) { threads.elementAt(i).join(); } } catch (InterruptedException ie) { ie.printStackTrace(); } }
From source file:com.intel.cosbench.driver.generator.RangeIntGenerator.java
public static void main(String[] args) { final String pattern = "r(51,1000)"; final int all = 5; int i = 0;/* ww w . j ava2 s. com*/ Vector<TestThread> threads = new Vector<TestThread>(); RangeIntGenerator gen = RangeIntGenerator.parse(pattern); for (i = 0; i < all; i++) { TestThread thread = new TestThread(gen, i + 1, all); threads.add(thread); thread.start(); } try { for (i = 0; i < all; i++) { threads.elementAt(i).join(); } } catch (InterruptedException ie) { ie.printStackTrace(); } }
From source file:CollateApp.java
public static void main(String args[]) { if (args.length != 1) { System.out.println("Usage: java CollateApp file"); System.exit(0);// w w w . j a v a2 s .c o m } Locale defaultLocale = Locale.getDefault(); RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(defaultLocale); Vector keyVector = new Vector(); try { BufferedReader in = new BufferedReader(new FileReader(args[0])); String line; while ((line = in.readLine()) != null) keyVector.addElement(collator.getCollationKey(line)); in.close(); } catch (Exception ex) { System.out.println(ex); System.exit(0); } CollationKey keys[] = new CollationKey[keyVector.size()]; for (int i = 0; i < keys.length; ++i) keys[i] = (CollationKey) keyVector.elementAt(i); }
From source file:CollateApp.java
public static void main(String args[]) { if (args.length != 1) { System.out.println("Usage: java CollateApp file"); System.exit(0);// w w w . j a v a 2s. c o m } Locale defaultLocale = Locale.getDefault(); RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(defaultLocale); Vector<Object> keyVector = new Vector<Object>(); try { BufferedReader in = new BufferedReader(new FileReader(args[0])); String line; while ((line = in.readLine()) != null) keyVector.addElement(collator.getCollationKey(line)); in.close(); } catch (Exception ex) { System.out.println(ex); System.exit(0); } CollationKey keys[] = new CollationKey[keyVector.size()]; for (int i = 0; i < keys.length; ++i) keys[i] = (CollationKey) keyVector.elementAt(i); }
From source file:ShowComponent.java
public static void main(String[] args) { // Process the command line to get the components to display Vector components = getComponentsFromArgs(args); // Create a frame (a window) to display them in JFrame frame = new JFrame("ShowComponent"); // Handle window close requests by exiting the VM frame.addWindowListener(new WindowAdapter() { // Anonymous inner class public void windowClosing(WindowEvent e) { System.exit(0);//from w w w . ja va2 s.c o m } }); // Set up a menu system that allows the user to select the // look-and-feel of the component from a list of installed PLAFs JMenuBar menubar = new JMenuBar(); // Create a menubar frame.setJMenuBar(menubar); // Tell the frame to display it JMenu plafmenu = createPlafMenu(frame); // Create a menu menubar.add(plafmenu); // Add the menu to the menubar // Create a JTabbedPane to display each of the components JTabbedPane pane = new JTabbedPane(); // Now add each component as a tab of the tabbed pane // Use the unqualified component classname as the tab text for (int i = 0; i < components.size(); i++) { Component c = (Component) components.elementAt(i); String classname = c.getClass().getName(); String tabname = classname.substring(classname.lastIndexOf('.') + 1); pane.addTab(tabname, c); } // Add the tabbed pane to the frame. Note the call to getContentPane() // This is required for JFrame, but not for most Swing components frame.getContentPane().add(pane); // Set the frame size and pop it up frame.pack(); // Make frame as big as its kids need frame.setVisible(true); // Make the frame visible on the screen // The main() method exits now but the Java VM keeps running because // all AWT programs automatically start an event-handling thread. }
From source file:Gen.java
public static void main(String[] args) throws Exception { try {/*from w w w .j a va2s . com*/ File[] files = null; if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) { files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toUpperCase().endsWith(".XML"); }; }); } else { String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("") ? System.getProperty("file") : "rjmap.xml"; files = new File[] { new File(fileName) }; } log.info("files : " + Arrays.toString(files)); if (files == null || files.length == 0) { log.info("no files to parse"); System.exit(0); } boolean formatsource = true; if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("") && System.getProperty("formatsource").equalsIgnoreCase("false")) { formatsource = false; } GEN_ROOT = System.getProperty("outputdir"); if (GEN_ROOT == null || GEN_ROOT.equals("")) { GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib"; } GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/'); if (GEN_ROOT.endsWith("/")) GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1); System.out.println("GEN ROOT:" + GEN_ROOT); MAPPING_JAR_NAME = System.getProperty("mappingjar") != null && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar") : "mapping.jar"; if (!MAPPING_JAR_NAME.endsWith(".jar")) MAPPING_JAR_NAME += ".jar"; GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src"; GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + ""; DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); domFactory.setValidating(false); DocumentBuilder documentBuilder = domFactory.newDocumentBuilder(); for (int f = 0; f < files.length; ++f) { log.info("parsing file : " + files[f]); Document document = documentBuilder.parse(files[f]); Vector<Node> initNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript", initNodes); for (int i = 0; i < initNodes.size(); ++i) { NamedNodeMap attrs = initNodes.elementAt(i).getAttributes(); boolean embed = attrs.getNamedItem("embed") != null && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true"); StringBuffer vbuffer = new StringBuffer(); if (attrs.getNamedItem("inline") != null) { vbuffer.append(attrs.getNamedItem("inline").getNodeValue()); vbuffer.append('\n'); } else { String fname = attrs.getNamedItem("name").getNodeValue(); if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') { String path = files[f].getAbsolutePath(); path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR)); fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath(); } vbuffer.append(Utils.getFileAsStringBuffer(fname)); } initScriptBuffer.append(vbuffer); if (embed) embedScriptBuffer.append(vbuffer); } Vector<Node> packageInitNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript", packageInitNodes); for (int i = 0; i < packageInitNodes.size(); ++i) { NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes(); String packageName = attrs.getNamedItem("package").getNodeValue(); if (packageName.equals("")) packageName = "rGlobalEnv"; if (!packageName.endsWith("Function")) packageName += "Function"; if (packageEmbedScriptHashMap.get(packageName) == null) { packageEmbedScriptHashMap.put(packageName, new StringBuffer()); } StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName); // if (!packageName.equals("rGlobalEnvFunction")) { // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n"); // } if (attrs.getNamedItem("inline") != null) { vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n"); initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n"); } else { String fname = attrs.getNamedItem("name").getNodeValue(); if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') { String path = files[f].getAbsolutePath(); path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR)); fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath(); } StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname); vbuffer.append(fileBuffer); initScriptBuffer.append(fileBuffer); } } Vector<Node> functionsNodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function", functionsNodes); for (int i = 0; i < functionsNodes.size(); ++i) { NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes(); String functionName = attrs.getNamedItem("name").getNodeValue(); boolean forWeb = attrs.getNamedItem("forWeb") != null && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true"); String signature = (attrs.getNamedItem("signature") == null ? "" : attrs.getNamedItem("signature").getNodeValue() + ","); String renameTo = (attrs.getNamedItem("renameTo") == null ? null : attrs.getNamedItem("renameTo").getNodeValue()); HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName); if (sigMap == null) { sigMap = new HashMap<String, FAttributes>(); Globals._functionsToPublish.put(functionName, sigMap); if (attrs.getNamedItem("returnType") == null) { _functionsVector.add(new String[] { functionName }); } else { _functionsVector.add( new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() }); } } sigMap.put(signature, new FAttributes(renameTo, forWeb)); if (forWeb) _webPublishingEnabled = true; } if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("") && System.getProperty("targetjdk").compareTo("1.5") < 0) { if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) { log.info("be careful, web publishing disabled beacuse target JDK<1.5"); } _webPublishingEnabled = false; } else { if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("") || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) { _webPublishingEnabled = true; } if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) { log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use"); _webPublishingEnabled = false; } } Vector<Node> s4Nodes = new Vector<Node>(); Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes); if (s4Nodes.size() > 0) { String formalArgs = ""; String signature = ""; for (int i = 0; i < s4Nodes.size(); ++i) { NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes(); String s4Name = attrs.getNamedItem("name").getNodeValue(); formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ","); signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ","); } String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER + "', signature(" + signature + ") , function(" + formalArgs + ") { })"; initScriptBuffer.append(genBeansScriptlet); _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" }); } } if (!new File(GEN_ROOT_LIB).exists()) regenerateDir(GEN_ROOT_LIB); else { clean(GEN_ROOT_LIB, true); } for (int i = 0; i < rwebservicesScripts.length; ++i) DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]); String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() { public void run(Rengine e) { DirectJNI.getInstance().toggleMarker(); DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString()); log.info(" init script status : " + DirectJNI.getInstance().cutStatusSinceMarker()); for (int i = 0; i < _functionsVector.size(); ++i) { String[] functionPair = _functionsVector.elementAt(i); log.info("dealing with : " + functionPair[0]); regenerateDir(GEN_ROOT_SRC); String createMapStr = "createMap("; boolean isGeneric = e.rniGetBoolArrayI( e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1; log.info("is Generic : " + isGeneric); if (isGeneric) { createMapStr += functionPair[0]; } else { createMapStr += "\"" + functionPair[0] + "\""; } createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\""; createMapStr += ", typeMode=\"robject\""; createMapStr += (functionPair.length == 1 || functionPair[1] == null || functionPair[1].trim().equals("") ? "" : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1] + "\")"); createMapStr += ")"; log.info("------------------------------------------"); log.info("-- createMapStr=" + createMapStr); DirectJNI.getInstance().toggleMarker(); e.rniEval(e.rniParse(createMapStr, 1), 0); String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker(); log.info(" createMap status : " + createMapStatus); log.info("------------------------------------------"); deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms"); compile(GEN_ROOT_SRC); jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null); URL url = null; try { url = new URL( "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar") .replace('\\', '/') + "!/"); } catch (Exception ex) { ex.printStackTrace(); } DirectJNI.generateMaps(url, true); } } }); log.info(lastStatus); log.info(DirectJNI._rPackageInterfacesHash); regenerateDir(GEN_ROOT_SRC); for (int i = 0; i < _functionsVector.size(); ++i) { unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC); } regenerateRPackageClass(true); generateS4BeanRef(); if (formatsource) applyJalopy(GEN_ROOT_SRC); compile(GEN_ROOT_SRC); for (String k : DirectJNI._rPackageInterfacesHash.keySet()) { Rmic rmicTask = new Rmic(); rmicTask.setProject(_project); rmicTask.setTaskName("rmic_packages"); rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC)); rmicTask.setBase(new File(GEN_ROOT_SRC)); rmicTask.setClassname(k + "ImplRemote"); rmicTask.init(); rmicTask.execute(); } // DirectJNI._rPackageInterfacesHash=new HashMap<String, // Vector<Class<?>>>(); // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new // Vector<Class<?>>()); if (_webPublishingEnabled) { jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null); URL url = new URL( "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/"); ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader()); for (String className : DirectJNI._rPackageInterfacesHash.keySet()) { if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0) continue; log.info("######## " + className); WsGen wsgenTask = new WsGen(); wsgenTask.setProject(_project); wsgenTask.setTaskName("wsgen"); FileSet rjb_fileSet = new FileSet(); rjb_fileSet.setProject(_project); rjb_fileSet.setDir(new File(".")); rjb_fileSet.setIncludes("RJB.jar"); DirSet src_dirSet = new DirSet(); src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); Path classPath = new Path(_project); classPath.addFileset(rjb_fileSet); classPath.addDirset(src_dirSet); wsgenTask.setClasspath(classPath); wsgenTask.setKeep(true); wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/")); wsgenTask.setSei(className + "Web"); wsgenTask.init(); wsgenTask.execute(); } new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete(); } embedRScripts(); HashMap<String, String> marker = new HashMap<String, String>(); marker.put("RJBMAPPINGJAR", "TRUE"); Properties props = new Properties(); props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames)); props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping)); props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert)); props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping)); props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash)); props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash)); props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories)); new File(GEN_ROOT_SRC + "/" + "maps").mkdirs(); FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml"); props.storeToXML(fos, null); fos.close(); jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker); if (_webPublishingEnabled) genWeb(); DirectJNI._mappingClassLoader = null; } finally { System.exit(0); } }
From source file:edu.umn.cs.spatialHadoop.operations.KNN.java
public static void main(String[] args) throws IOException { final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();// ww w. j a v a 2 s .c o m System.exit(1); } if (paths.length > 1 && !params.checkInputOutput()) { printUsage(); System.exit(1); } final Path inputFile = params.getInputPath(); int count = params.getInt("count", 1); double closeness = params.getFloat("closeness", -1.0f); final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count]; final FileSystem fs = inputFile.getFileSystem(params); final int k = params.getInt("k", 1); int concurrency = params.getInt("concurrency", 100); if (k == 0) { LOG.warn("k = 0"); } if (queryPoints.length == 0) { printUsage(); throw new RuntimeException("Illegal arguments"); } final Path outputPath = paths.length > 1 ? paths[1] : null; if (closeness >= 0) { // Get query points according to its closeness to grid intersections GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile); long seed = params.getLong("seed", System.currentTimeMillis()); Random random = new Random(seed); for (int i = 0; i < count; i++) { int i_block = random.nextInt(gindex.size()); int direction = random.nextInt(4); // Generate a point in the given direction // Get center point (x, y) Iterator<Partition> iterator = gindex.iterator(); while (i_block-- >= 0) iterator.next(); Partition partition = iterator.next(); double cx = (partition.x1 + partition.x2) / 2; double cy = (partition.y1 + partition.y2) / 2; double cw = partition.x2 - partition.x1; double ch = partition.y2 - partition.y1; int signx = ((direction & 1) == 0) ? 1 : -1; int signy = ((direction & 2) == 1) ? 1 : -1; double x = cx + cw * closeness / 2 * signx; double y = cy + ch * closeness / 2 * signy; queryPoints[i] = new Point(x, y); } } final BooleanWritable exceptionHappened = new BooleanWritable(); Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { ex.printStackTrace(); exceptionHappened.set(true); } }; // Run each query in a separate thread final Vector<Thread> threads = new Vector<Thread>(); for (int i = 0; i < queryPoints.length; i++) { Thread thread = new Thread() { @Override public void run() { try { Point query_point = queryPoints[threads.indexOf(this)]; OperationsParams newParams = new OperationsParams(params); OperationsParams.setShape(newParams, "point", query_point); Job job = knn(inputFile, outputPath, params); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }; thread.setUncaughtExceptionHandler(h); threads.add(thread); } long t1 = System.currentTimeMillis(); do { // Ensure that there is at least MaxConcurrentThreads running int i = 0; while (i < concurrency && i < threads.size()) { Thread.State state = threads.elementAt(i).getState(); if (state == Thread.State.TERMINATED) { // Thread already terminated, remove from the queue threads.remove(i); } else if (state == Thread.State.NEW) { // Start the thread and move to next one threads.elementAt(i++).start(); } else { // Thread is still running, skip over it i++; } } if (!threads.isEmpty()) { try { // Sleep for 10 seconds or until the first thread terminates threads.firstElement().join(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } while (!threads.isEmpty()); long t2 = System.currentTimeMillis(); if (exceptionHappened.get()) throw new RuntimeException("Not all jobs finished correctly"); System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Total iterations: " + TotalIterations); }
From source file:edu.umn.cs.sthadoop.trajectory.KNNDTW.java
public static void main(String[] args) throws IOException { args = new String[10]; args[0] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/index_geolife/yyyy-MM/2008-05"; args[1] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/knn-dis-result"; args[2] = "shape:edu.umn.cs.sthadoop.trajectory.GeolifeTrajectory"; args[3] = "interval:2008-05-01,2008-05-30"; args[4] = "time:month"; args[5] = "k:1"; args[6] = "traj:39.9119983,116.606835;39.9119783,116.6065483;39.9119599,116.6062649;39.9119416,116.6059899;39.9119233,116.6057282;39.9118999,116.6054783;39.9118849,116.6052366;39.9118666,116.6050099;39.91185,116.604775;39.9118299,116.604525;39.9118049,116.6042649;39.91177,116.6040166;39.9117516,116.6037583;39.9117349,116.6035066;39.9117199,116.6032666;39.9117083,116.6030232;39.9117,116.6027566;39.91128,116.5969383;39.9112583,116.5966766;39.9112383,116.5964232;39.9112149,116.5961699;39.9111933,116.5959249;39.9111716,116.5956883"; args[7] = "-overwrite"; args[8] = "-local";// "-no-local"; args[9] = "point:39.9119983,116.606835"; final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();// w ww .j av a2 s . c om System.exit(1); } if (paths.length > 1 && !params.checkInputOutput()) { printUsage(); System.exit(1); } final Path inputFile = params.getInputPath(); int count = params.getInt("count", 1); double closeness = params.getFloat("closeness", -1.0f); final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count]; final FileSystem fs = inputFile.getFileSystem(params); final int k = params.getInt("k", 1); int concurrency = params.getInt("concurrency", 100); if (k == 0) { LOG.warn("k = 0"); } if (queryPoints.length == 0) { printUsage(); throw new RuntimeException("Illegal arguments"); } final Path outputPath = paths.length > 1 ? paths[1] : null; if (closeness >= 0) { // Get query points according to its closeness to grid intersections GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile); long seed = params.getLong("seed", System.currentTimeMillis()); Random random = new Random(seed); for (int i = 0; i < count; i++) { int i_block = random.nextInt(gindex.size()); int direction = random.nextInt(4); // Generate a point in the given direction // Get center point (x, y) Iterator<Partition> iterator = gindex.iterator(); while (i_block-- >= 0) iterator.next(); Partition partition = iterator.next(); double cx = (partition.x1 + partition.x2) / 2; double cy = (partition.y1 + partition.y2) / 2; double cw = partition.x2 - partition.x1; double ch = partition.y2 - partition.y1; int signx = ((direction & 1) == 0) ? 1 : -1; int signy = ((direction & 2) == 1) ? 1 : -1; double x = cx + cw * closeness / 2 * signx; double y = cy + ch * closeness / 2 * signy; queryPoints[i] = new Point(x, y); } } final BooleanWritable exceptionHappened = new BooleanWritable(); Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { ex.printStackTrace(); exceptionHappened.set(true); } }; // Run each query in a separate thread final Vector<Thread> threads = new Vector<Thread>(); for (int i = 0; i < queryPoints.length; i++) { Thread thread = new Thread() { @Override public void run() { try { Point query_point = queryPoints[threads.indexOf(this)]; OperationsParams newParams = new OperationsParams(params); OperationsParams.setShape(newParams, "point", query_point); Job job = knn(inputFile, outputPath, params); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }; thread.setUncaughtExceptionHandler(h); threads.add(thread); } long t1 = System.currentTimeMillis(); do { // Ensure that there is at least MaxConcurrentThreads running int i = 0; while (i < concurrency && i < threads.size()) { Thread.State state = threads.elementAt(i).getState(); if (state == Thread.State.TERMINATED) { // Thread already terminated, remove from the queue threads.remove(i); } else if (state == Thread.State.NEW) { // Start the thread and move to next one threads.elementAt(i++).start(); } else { // Thread is still running, skip over it i++; } } if (!threads.isEmpty()) { try { // Sleep for 10 seconds or until the first thread terminates threads.firstElement().join(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } while (!threads.isEmpty()); long t2 = System.currentTimeMillis(); if (exceptionHappened.get()) throw new RuntimeException("Not all jobs finished correctly"); System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Total iterations: " + TotalIterations); }
From source file:com.ricemap.spateDB.operations.RangeQuery.java
public static void main(String[] args) throws IOException { CommandLineArguments cla = new CommandLineArguments(args); final QueryInput query = cla.getQuery(); final Path[] paths = cla.getPaths(); if (paths.length == 0 || (cla.getPrism() == null && cla.getSelectionRatio() < 0.0f)) { printUsage();//from w w w . jav a2 s. c o m throw new RuntimeException("Illegal parameters"); } JobConf conf = new JobConf(FileMBR.class); final Path inputFile = paths[0]; final FileSystem fs = inputFile.getFileSystem(conf); if (!fs.exists(inputFile)) { printUsage(); throw new RuntimeException("Input file does not exist"); } final Path outputPath = paths.length > 1 ? paths[1] : null; final Prism[] queryRanges = cla.getPrisms(); int concurrency = cla.getConcurrency(); final Shape stockShape = cla.getShape(true); final boolean overwrite = cla.isOverwrite(); final long[] results = new long[queryRanges.length]; final Vector<Thread> threads = new Vector<Thread>(); final BooleanWritable exceptionHappened = new BooleanWritable(); Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { ex.printStackTrace(); exceptionHappened.set(true); } }; for (int i = 0; i < queryRanges.length; i++) { Thread t = new Thread() { @Override public void run() { try { int thread_i = threads.indexOf(this); long result_count = rangeQueryMapReduce(fs, inputFile, outputPath, queryRanges[thread_i], stockShape, overwrite, false, query); results[thread_i] = result_count; } catch (IOException e) { throw new RuntimeException(e); } } }; t.setUncaughtExceptionHandler(h); threads.add(t); } long t1 = System.currentTimeMillis(); do { // Ensure that there is at least MaxConcurrentThreads running int i = 0; while (i < concurrency && i < threads.size()) { Thread.State state = threads.elementAt(i).getState(); if (state == Thread.State.TERMINATED) { // Thread already terminated, remove from the queue threads.remove(i); } else if (state == Thread.State.NEW) { // Start the thread and move to next one threads.elementAt(i++).start(); } else { // Thread is still running, skip over it i++; } } if (!threads.isEmpty()) { try { // Sleep for 10 seconds or until the first thread terminates threads.firstElement().join(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } while (!threads.isEmpty()); long t2 = System.currentTimeMillis(); if (exceptionHappened.get()) throw new RuntimeException("Not all jobs finished correctly"); System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis"); System.out.print("Result size: ["); for (long result : results) { System.out.print(result + ", "); } System.out.println("]"); }
From source file:edu.umn.cs.sthadoop.operations.HSPKNNQ.java
public static void main(String[] args) throws IOException { //./hadoop jar /export/scratch/louai/idea-stHadoop/st-hadoop-uber.jar pknn /mntgIndex/yyyy-MM-dd/2017-08-03 /pknn k:2 point:-78.9659,35.7998 shape:edu.umn.cs.sthadoop.mntg.STPointMntg -overwrite // args = new String[8]; // args[0] = "/export/scratch/mntgData/mntgIndex"; // args[1] = "/export/scratch/mntgData/pknn"; // args[2] = "-overwrite"; // args[3] = "k:10"; // args[4] = "point:-78.9659063204100,35.7903907684998"; // args[5] = "shape:edu.umn.cs.sthadoop.trajectory.STPointTrajectory"; // args[6] = "interval:2017-08-03,2017-08-04"; // args[7] = "-overwrite"; final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();//from www . java 2s. c om System.exit(1); } if (paths.length > 1 && !params.checkInputOutput()) { printUsage(); System.exit(1); } if (params.get("interval") == null) { System.err.println("Temporal range missing"); printUsage(); System.exit(1); } TextSerializable inObj = params.getShape("shape"); if (!(inObj instanceof STPoint)) { if (!(inObj instanceof STRectangle)) { LOG.error("Shape is not instance of STPoint or instance of STRectangle"); printUsage(); System.exit(1); } } // path to the spatio-temporal index. List<Path> STPaths = new ArrayList<Path>(); try { STPaths = STRangeQuery.getIndexedSlices(params); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } for (Path input : STPaths) { final Path inputFile = input; int count = params.getInt("count", 1); double closeness = params.getFloat("closeness", -1.0f); final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count]; final FileSystem fs = inputFile.getFileSystem(params); final int k = params.getInt("k", 1); int concurrency = params.getInt("concurrency", 100); if (k == 0) { LOG.warn("k = 0"); } if (queryPoints.length == 0) { printUsage(); throw new RuntimeException("Illegal arguments"); } final Path outputPath = paths.length > 1 ? new Path(paths[1].toUri() + "-" + input.getName()) : null; if (closeness >= 0) { // Get query points according to its closeness to grid intersections GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile); long seed = params.getLong("seed", System.currentTimeMillis()); Random random = new Random(seed); for (int i = 0; i < count; i++) { int i_block = random.nextInt(gindex.size()); int direction = random.nextInt(4); // Generate a point in the given direction // Get center point (x, y) Iterator<Partition> iterator = gindex.iterator(); while (i_block-- >= 0) iterator.next(); Partition partition = iterator.next(); double cx = (partition.x1 + partition.x2) / 2; double cy = (partition.y1 + partition.y2) / 2; double cw = partition.x2 - partition.x1; double ch = partition.y2 - partition.y1; int signx = ((direction & 1) == 0) ? 1 : -1; int signy = ((direction & 2) == 1) ? 1 : -1; double x = cx + cw * closeness / 2 * signx; double y = cy + ch * closeness / 2 * signy; queryPoints[i] = new Point(x, y); } } final BooleanWritable exceptionHappened = new BooleanWritable(); Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { ex.printStackTrace(); exceptionHappened.set(true); } }; // Run each query in a separate thread final Vector<Thread> threads = new Vector<Thread>(); for (int i = 0; i < queryPoints.length; i++) { Thread thread = new Thread() { @Override public void run() { try { Point query_point = queryPoints[threads.indexOf(this)]; OperationsParams newParams = new OperationsParams(params); OperationsParams.setShape(newParams, "point", query_point); Job job = knn(inputFile, outputPath, params); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }; thread.setUncaughtExceptionHandler(h); threads.add(thread); } long t1 = System.currentTimeMillis(); do { // Ensure that there is at least MaxConcurrentThreads running int i = 0; while (i < concurrency && i < threads.size()) { Thread.State state = threads.elementAt(i).getState(); if (state == Thread.State.TERMINATED) { // Thread already terminated, remove from the queue threads.remove(i); } else if (state == Thread.State.NEW) { // Start the thread and move to next one threads.elementAt(i++).start(); } else { // Thread is still running, skip over it i++; } } if (!threads.isEmpty()) { try { // Sleep for 10 seconds or until the first thread terminates threads.firstElement().join(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } while (!threads.isEmpty()); long t2 = System.currentTimeMillis(); if (exceptionHappened.get()) throw new RuntimeException("Not all jobs finished correctly"); System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Total iterations: " + TotalIterations); } }