public void setMainClassFromOptions() { if (mainClass != null) return; if (Options.v().main_class() != null && Options.v().main_class().length() > 0) { setMainClass(getSootClass(Options.v().main_class())); } else { // try to infer a main class from the command line if none is given for (Iterator<String> classIter = Options.v().classes().iterator(); classIter.hasNext(); ) { SootClass c = getSootClass(classIter.next()); if (c.declaresMethod( "main", Collections.<Type>singletonList(ArrayType.v(RefType.v("java.lang.String"), 1)), VoidType.v())) { G.v().out.println("No main class given. Inferred '" + c.getName() + "' as main class."); setMainClass(c); return; } } // try to infer a main class from the usual classpath if none is given for (Iterator<SootClass> classIter = getApplicationClasses().iterator(); classIter.hasNext(); ) { SootClass c = (SootClass) classIter.next(); if (c.declaresMethod( "main", Collections.<Type>singletonList(ArrayType.v(RefType.v("java.lang.String"), 1)), VoidType.v())) { G.v().out.println("No main class given. Inferred '" + c.getName() + "' as main class."); setMainClass(c); return; } } } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); G.context = getBaseContext(); String weather = G.get("weather", " "); if (weather != null && !weather.equals(" ")) Info.updateWeatherInfo(TextFormat.threeHour(weather)); double lat = G.get("latitude", 0.0); if (lat != 0.0) G.lat = lat; double lon = G.get("longitude", 0.0); if (lon != 0.0) G.lon = lon; G.scale = 1.0; ImageManager.setView(this.findViewById(android.R.id.content)); new Handler() .postDelayed( new Runnable() { @Override public void run() { startActivity(new Intent("com.example.clock.DISPLAYACTIVITY")); finish(); } }, SPLASH_TIME_OUT); }
/** * Execute {@code HelloWorld} example on the grid. * * @param args Command line arguments, none required but if provided first one should point to the * Spring XML configuration file. See {@code "examples/config/"} for configuration file * examples. * @throws GridException If example execution failed. */ public static void main(String[] args) throws GridException { if (args.length == 0) { G.start(); } else { G.start(args[0]); } try { // Broadcast this message to all nodes using GridClosure. broadcastWordsClosure("Broadcasting This Message To All Nodes!"); // Print individual words from this phrase on different nodes // using GridClosure spreadWordsClosure("Print Worlds Functional Style!"); // Print this message using anonymous runnable object. unicastWordsRunnable("Printing This Message From Runnable!"); // Split the message into words and pass them as arguments // for remote execution of Callable objects. countLettersCallable("Letter Count With Callable!"); // Split the message into words and pass them as arguments // for remote execution of GridClosure objects. countLettersClosure("Letter Count With Closure!"); // Split the message into words and pass them as arguments // for remote execution of GridClosure objects and // then aggregate results using GridReducer. countLettersReducer("Letter Count With Reducer!"); } finally { G.stop(true); } }
public void defaultCase(Node node) { if (node instanceof TQuotedName || node instanceof TFullIdentifier || node instanceof TIdentifier || node instanceof TStringConstant || node instanceof TIntegerConstant || node instanceof TFloatConstant || node instanceof TAtIdentifier) { if (debug) G.v().out.println("Default case -pushing token:" + ((Token) node).getText()); String tokenString = ((Token) node).getText(); if (node instanceof TStringConstant || node instanceof TQuotedName) { tokenString = tokenString.substring(1, tokenString.length() - 1); } if (node instanceof TIdentifier || node instanceof TFullIdentifier || node instanceof TQuotedName || node instanceof TStringConstant) { try { tokenString = StringTools.getUnEscapedStringOf(tokenString); } catch (RuntimeException e) { G.v().out.println(tokenString); throw e; } } mProductions.addLast(tokenString); } }
/** * Execute {@code HelloWorld} example on the grid. * * @param args Command line arguments, none required but if provided first one should point to the * Spring XML configuration file. See {@code "examples/config/"} for configuration file * examples. * @throws GridException If example execution failed. */ public static void main(String[] args) throws GridException { if (args.length == 0) { G.start(); } else { G.start(args[0]); } try { Grid grid = G.grid(); // Execute Hello World task. GridTaskFuture<Integer> fut = grid.execute(GridHelloWorldTask.class, "Hello World"); // Wait for task completion. int phraseLen = fut.get(); X.println(">>>"); X.println(">>> Finished executing Grid \"Hello World\" example with custom task."); X.println(">>> Total number of characters in the phrase is '" + phraseLen + "'."); X.println(">>> You should see print out of 'Hello' on one node and 'World' on another node."); X.println(">>> Check all nodes for output (this node is also part of the grid)."); X.println(">>>"); } finally { G.stop(true); } }
/** * Execute {@code HelloWorld} example grid-enabled with {@code Gridify} annotation. * * @param args Command line arguments, none required but if provided first one should point to the * Spring XML configuration file. See {@code "examples/config/"} for configuration file * examples. * @throws GridException If example execution failed. */ public static void main(String[] args) throws GridException { if (args.length == 0) { G.start(); } else { G.start(args[0]); } try { // Simple example stateful instance to demonstrate // how object state can be handled with grid-enabled methods. GridifyHelloWorld helloWorld = new GridifyHelloWorld(); // Set simple state. helloWorld.setState("Hello World"); // This method is grid-enabled and // will be executed on remote grid nodes. int phraseLen = helloWorld.sayIt(); X.println(">>>"); X.println(">>> Finished executing Gridify \"Hello World\" stateful example."); X.println(">>> Total number of characters in the phrase is '" + phraseLen + "'."); X.println(">>> You should see print out of 'Hello' on one node and 'World' on another node."); X.println(">>> Check all nodes for output (this node is also part of the grid)."); X.println(">>>"); } finally { G.stop(true); } }
@Override public G next() throws NoSuchElementException { G next = features.next(); String featureId = next.getIdentifier().getID(); Ref ref = typeTree.get(featureId); String versionId = ref == null ? null : ref.getObjectId().toString(); return VersionedFeatureWrapper.wrap(next, versionId); }
/** * @param args Arguments. * @throws Exception If failed. */ public static void main(String[] args) throws Exception { try { G.start("examples/config/example-cache.xml"); JOptionPane.showMessageDialog(null, "Press OK to stop test node."); } finally { G.stopAll(false); } }
public V getEdgeSource(E e) { if (g1.containsEdge(e)) { return g1.getEdgeSource(e); } if (g2.containsEdge(e)) { return g2.getEdgeSource(e); } return null; }
private void analyzeLocal(SootMethod method, Value value) { Local l = (Local) value; boolean objIsThreadLocal = tloa.isObjectThreadLocal(l, method); if (objIsThreadLocal) { G.v().out.println("[lg.tlo] LOCAL " + l.toString() + " is thread-local in method " + method); } else { G.v().out.println("[lg.tlo] LOCAL " + l.toString() + " is thread-shared in method " + method); } }
public V getEdgeTarget(E e) { if (g1.containsEdge(e)) { return g1.getEdgeTarget(e); } if (g2.containsEdge(e)) { return g2.getEdgeTarget(e); } return null; }
public Set<E> edgesOf(V vertex) { Set<E> res = new HashSet<E>(); if (g1.containsVertex(vertex)) { res.addAll(g1.edgesOf(vertex)); } if (g2.containsVertex(vertex)) { res.addAll(g2.edgesOf(vertex)); } return Collections.unmodifiableSet(res); }
public static void main(String args[]) { G<Integer> g = new G<Integer>(10, 5, new Integer(1)); // g.set(new Integer(5)); System.out.println(g.x); System.out.println(g.z); ArrayList<Integer> list = g.addto(new Integer(3)); for (Integer in : list) System.out.println(in); }
private void analyzeField(SootMethod method, Value value) { FieldRef fr = (FieldRef) value; boolean fieldIsThreadLocal = tloa.isObjectThreadLocal(fr, method); if (fieldIsThreadLocal) { G.v().out.println("[lg.tlo] FIELD " + fr.toString() + " is thread-local in method " + method); } else { G.v() .out .println("[lg.tlo] FIELD " + fr.toString() + " is thread-shared in method " + method); } }
private <T extends AbstractEdmEntityImpl, G extends MongoTermList<T>> boolean migratePhaseOne( JacksonDBCollection<G, String> termListColl_source, JacksonDBCollection<MongoTerm, String> termColl_source, JacksonDBCollection<G, String> termListColl_target, JacksonDBCollection<MongoTerm, String> termColl_target, ContextualCategory contextualCategory, String termCollection) throws UnknownHostException { int skip = 0; int counter = 0; while (true) { try { DBCursor<G> curs = termListColl_source .find(new BasicDBObject("entityType", contextualCategory.getEntityClass())) .skip(skip); curs.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT); while (curs.hasNext()) { long nextSequence = nextSequence(contextualCategory); counter++; G termList = curs.next(); String newCodeUri = String.format( "http://data.europeana.eu/%s/base" + "/%d", contextualCategory.getLabel(), nextSequence); String oldCodeUri = termList.getCodeUri(); MongoCodeLookup lookup = new MongoCodeLookup(); lookup.setCodeUri(newCodeUri); lookup.setOriginalCodeUri(oldCodeUri); lookupColl_target.insert(lookup); lookupCodeUri.put(newCodeUri, oldCodeUri); lookupOriginalCodeUri.put(oldCodeUri, newCodeUri); } curs.close(); break; } catch (Exception e) { e.printStackTrace(); initialiseConnections(); skip = counter - 1; continue; } } return true; }
@Test @TestForIssue(jiraKey = "HHH-5472") public void testCascade() { A a = new A(); B b = new B(); C c = new C(); D d = new D(); E e = new E(); F f = new F(); G g = new G(); H h = new H(); a.getBCollection().add(b); b.setA(a); a.getCCollection().add(c); c.setA(a); b.getCCollection().add(c); c.setB(b); a.getDCollection().add(d); d.getACollection().add(a); d.getECollection().add(e); e.setF(f); f.getBCollection().add(b); b.setF(f); c.setG(g); g.getCCollection().add(c); f.setH(h); h.setG(g); Session s; s = openSession(); s.getTransaction().begin(); try { // Fails: says that C.b is null (even though it isn't). Doesn't fail if you persist c, g or h // instead of a s.persist(a); s.flush(); } finally { s.getTransaction().rollback(); s.close(); } }
/** * Prints a phrase on the grid nodes running anonymous closure objects and calculating total * number of letters. * * @param phrase Phrase to print on of the grid nodes. * @throws GridException If failed. */ private static void countLettersClosure(String phrase) throws GridException { X.println(">>> Starting countLettersClosure() example..."); // Explicitly execute the collection of callable objects and receive a result. Collection<Integer> results = G.grid() .call( SPREAD, new GridClosure<String, Integer>() { // Create executable logic. @Override public Integer apply(String word) { // Print out a given word, just so we can // see which node is doing what. X.println(">>> Executing word: " + word); // Return the length of a given word, i.e. number of letters. return word.length(); } }, Arrays.asList(phrase.split(" "))); // Collection of arguments for closures. // Add up all results using convenience 'sum()' method. int letterCnt = F.sum(results); X.println(">>>"); X.println(">>> Finished execution of counting letters with closure based on GridGain 3.0 API."); X.println(">>> You should see the phrase '" + phrase + "' printed out on the nodes."); X.println(">>> Total number of letters in the phrase is '" + letterCnt + "'."); X.println(">>> Check all nodes for output (this node is also part of the grid)."); X.println(">>>"); }
/** * Prints a phrase on the grid nodes running anonymous callable objects and calculating total * number of letters. * * @param phrase Phrase to print on of the grid nodes. * @throws GridException If failed. */ private static void countLettersCallable(String phrase) throws GridException { X.println(">>> Starting countLettersCallable() example..."); Collection<Callable<Integer>> calls = new HashSet<Callable<Integer>>(); for (final String word : phrase.split(" ")) calls.add( new GridCallable<Integer>() { // Create executable logic. @Override public Integer call() throws Exception { // Print out a given word, just so we can // see which node is doing what. X.println(">>> Executing word: " + word); // Return the length of a given word, i.e. number of letters. return word.length(); } }); // Explicitly execute the collection of callable objects and receive a result. Collection<Integer> results = G.grid().call(SPREAD, calls); // Add up all results using convenience 'sum()' method on GridFunc class. int letterCnt = F.sum(results); X.println(">>>"); X.println( ">>> Finished execution of counting letters with callables based on GridGain 3.0 API."); X.println(">>> You should see the phrase '" + phrase + "' printed out on the nodes."); X.println(">>> Total number of letters in the phrase is '" + letterCnt + "'."); X.println(">>> Check all nodes for output (this node is also part of the grid)."); X.println(">>>"); }
/** * Prints a phrase on one of the grid nodes running anonymous runnable. * * @param phrase Phrase to print on one of the grid nodes. * @throws GridException If failed. */ private static void unicastWordsRunnable(final String phrase) throws GridException { X.println(">>> Starting unicastWordsRunnable() example..."); G.grid() .run( UNICAST, new GridRunnable() { @Override public void run() { X.println(">>> Printing phrase: " + phrase); } }); // NOTE: // // Alternatively, you can use existing closure 'F.println()' to // print any text like so: // // G.grid().run(UNICAST, F.println(">>> Printing phrase: " + phrase)); // X.println(">>>"); X.println(">>> Finished execution of runnable object based on GridGain 3.0 API."); X.println(">>> You should see the phrase '" + phrase + "' printed out on one of the nodes."); X.println(">>> Check all nodes for output (this node is also part of the grid)."); X.println(">>>"); }
/** * Prints every word a phrase on different nodes. * * @param phrase Phrase from which to print words on different nodes. * @throws GridException If failed. */ private static void spreadWordsClosure(String phrase) throws GridException { X.println(">>> Starting spreadWordsClosure() example..."); // Splits the passed in phrase into words and prints every word // on a individual grid node. If there are more words than nodes - // some nodes will print more than one word. G.grid() .run( SPREAD, F.yield( phrase.split(" "), new GridInClosure<String>() { @Override public void apply(String word) { X.println(word); } })); // NOTE: // // Alternatively, you can use existing closure 'F.println()' to // print any yield result in 'F.yield()' like so: // // G.grid().run(SPREAD, F.yield(phrase.split(" "), F.println())); // X.println(">>>"); X.println( ">>> Finished printing individual words on different nodes based on GridGain 3.0 API."); X.println(">>> Check all nodes for output (this node is also part of the grid)."); X.println(">>>"); }
/** * Broadcasts a give phrase to all nodes. * * @param phrase Phrase to broadcast. * @throws GridException If failed. */ private static void broadcastWordsClosure(final String phrase) throws GridException { X.println(">>> Starting broadcastWordsClosure() example..."); G.grid() .run( BROADCAST, new GridAbsClosure() { @Override public void apply() { X.println(">>> Printing phrase: " + phrase); } }); // NOTE: // // Alternatively, you can use existing closure 'F.println()' to // print any text like so: // // G.grid().run(BROADCAST, F.println(">>> Printing phrase: " + phrase)); // X.println(">>>"); X.println(">>> Finished broadcasting a phrase to all grid nodes based on GridGain 3.0 API."); X.println(">>> Check all nodes for output (this node is also part of the grid)."); X.println(">>>"); }
/** * Check if flags in correct state. * * @param msg Message. */ private void checkSyncFlags(GridIoMessage msg) { if (!commSpiEnabled) return; Object o = msg.message(); if (!(o instanceof GridDistributedLockRequest)) return; GridKernal g = (GridKernal) G.grid(nodeId); GridCacheTxManager<Object, Object> tm = g.internalCache(REPLICATED_ASYNC_CACHE_NAME).context().tm(); GridCacheVersion v = ((GridCacheVersionable) o).version(); GridCacheTxEx t = tm.tx(v); if (t.hasWriteKey("x1")) { assertFalse(t.syncCommit()); } else if (t.hasWriteKey("x2")) { assertTrue(t.syncCommit()); } else if (t.hasWriteKey("x3")) { assertFalse(t.syncCommit()); } else if (t.hasWriteKey("x4")) { assertTrue(t.syncCommit()); } }
/** * Change topology. * * @param parent Grid to execute tasks on. * @param add New nodes count. * @param rmv Remove nodes count. * @param type Type of nodes to manipulate. */ private static void changeTopology(Ignite parent, int add, int rmv, String type) { Collection<ComputeTaskFuture<?>> tasks = new ArrayList<>(); IgniteCompute comp = parent.compute().withAsync(); // Start nodes in parallel. while (add-- > 0) { comp.execute(ClientStartNodeTask.class, type); tasks.add(comp.future()); } for (ComputeTaskFuture<?> task : tasks) task.get(); // Stop nodes in sequence. while (rmv-- > 0) parent.compute().execute(ClientStopNodeTask.class, type); // Wait for node stops. // U.sleep(1000); Collection<String> gridNames = new ArrayList<>(); for (Ignite g : G.allGrids()) gridNames.add(g.name()); parent.log().info(">>> Available grids: " + gridNames); }
/** @throws Exception If failed. */ @SuppressWarnings("unchecked") public void testCancel() throws Exception { Grid grid = G.grid(getTestGridName()); grid.compute() .localDeployTask(GridCancelTestTask.class, U.detectClassLoader(GridCancelTestTask.class)); GridComputeTaskFuture<?> fut = grid.compute().execute(GridCancelTestTask.class.getName(), null); // Wait until jobs begin execution. boolean await = startSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS); assert await : "Jobs did not start."; info("Test task result: " + fut); assert fut != null; // Only first job should successfully complete. Object res = fut.get(); assert (Integer) res == 1; // Wait for all jobs to finish. await = stopSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS); assert await : "Jobs did not stop."; // One is definitely processed. But there might be some more processed or cancelled or processed // and cancelled. // Thus total number should be at least SPLIT_COUNT and at most (SPLIT_COUNT - 1) *2 +1 assert (cancelCnt + processedCnt) >= SPLIT_COUNT && (cancelCnt + processedCnt) <= (SPLIT_COUNT - 1) * 2 + 1 : "Invalid cancel count value: " + cancelCnt; }
/** @throws Exception If failed. */ public void testInvalidateFlag() throws Exception { GridEx g0 = grid(0); GridCache<String, String> cache = g0.cache(PARTITIONED_CACHE_NAME); String key = null; for (int i = 0; i < 10_000; i++) { if (!cache.affinity().isPrimaryOrBackup(g0.localNode(), String.valueOf(i))) { key = String.valueOf(i); break; } } assertNotNull(key); cache.put(key, key); // Create entry in near cache, it is invalidated if INVALIDATE flag is set. assertNotNull(cache.peek(key)); GridClientData d = client.data(PARTITIONED_CACHE_NAME); d.flagsOn(GridClientCacheFlag.INVALIDATE).put(key, "zzz"); for (Grid g : G.allGrids()) { cache = g.cache(PARTITIONED_CACHE_NAME); if (cache.affinity().isPrimaryOrBackup(g.localNode(), key)) assertEquals("zzz", cache.peek(key)); else assertNull(cache.peek(key)); } }
/** @throws Exception If failed. */ public void testDisabledRest() throws Exception { restEnabled = false; final Grid g = startGrid("disabled-rest"); try { Thread.sleep(2 * TOP_REFRESH_FREQ); // As long as we have round robin load balancer this will cause every node to be queried. for (int i = 0; i < NODES_CNT + 1; i++) assertEquals(NODES_CNT + 1, client.compute().refreshTopology(false, false).size()); final GridClientData data = client.data(PARTITIONED_CACHE_NAME); // Check rest-disabled node is unavailable. try { String affKey; do { affKey = UUID.randomUUID().toString(); } while (!data.affinity(affKey).equals(g.localNode().id())); data.put(affKey, "asdf"); assertEquals("asdf", cache(0, PARTITIONED_CACHE_NAME).get(affKey)); } catch (GridServerUnreachableException e) { // Thrown for direct client-node connections. assertTrue( "Unexpected exception message: " + e.getMessage(), e.getMessage() .startsWith("No available endpoints to connect (is rest enabled for this node?)")); } catch (GridClientException e) { // Thrown for routed client-router-node connections. String msg = e.getMessage(); assertTrue( "Unexpected exception message: " + msg, protocol() == GridClientProtocol.TCP ? msg.contains("No available endpoints to connect (is rest enabled for this node?)") : // TCP router. msg.startsWith( "No available nodes on the router for destination node ID")); // HTTP router. } // Check rest-enabled nodes are available. String affKey; do { affKey = UUID.randomUUID().toString(); } while (data.affinity(affKey).equals(g.localNode().id())); data.put(affKey, "fdsa"); assertEquals("fdsa", cache(0, PARTITIONED_CACHE_NAME).get(affKey)); } finally { restEnabled = true; G.stop(g.name(), true); } }
/** @throws Exception If failed. */ public void testRemoteIfDataCacheNameEquals() throws Exception { GridConfiguration g2Cfg = getConfiguration("g2"); GridGgfsConfiguration g2GgfsCfg1 = new GridGgfsConfiguration(g1GgfsCfg1); GridGgfsConfiguration g2GgfsCfg2 = new GridGgfsConfiguration(g1GgfsCfg2); g2GgfsCfg1.setName("g2GgfsCfg1"); g2GgfsCfg2.setName("g2GgfsCfg2"); g2GgfsCfg1.setMetaCacheName("g2MetaCache1"); g2GgfsCfg2.setMetaCacheName("g2MetaCache2"); g1Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); g2Cfg.setCacheConfiguration( concat( dataCaches(1024), metaCaches("g2MetaCache1", "g2MetaCache2"), GridCacheConfiguration.class)); g2Cfg.setGgfsConfiguration(g2GgfsCfg1, g2GgfsCfg2); G.start(g1Cfg); checkGridStartFails( g2Cfg, "Data cache names should be different for different GGFS instances", false); }
public StronglyConnectedComponentsBV(BitVector typeVariableList, TypeResolverBV resolver) throws TypeException { this.resolver = resolver; variables = typeVariableList; black = new TreeSet(); finished = new LinkedList(); for (BitSetIterator i = variables.iterator(); i.hasNext(); ) { TypeVariableBV var = resolver.typeVariableForId(i.next()); if (!black.contains(var)) { black.add(var); dfsg_visit(var); } } black = new TreeSet(); for (Iterator i = finished.iterator(); i.hasNext(); ) { TypeVariableBV var = (TypeVariableBV) i.next(); if (!black.contains(var)) { current_tree = new LinkedList(); forest.add(current_tree); black.add(var); dfsgt_visit(var); } } for (Iterator i = forest.iterator(); i.hasNext(); ) { LinkedList list = (LinkedList) i.next(); TypeVariableBV previous = null; StringBuffer s = null; if (DEBUG) { s = new StringBuffer("scc:\n"); } for (Iterator j = list.iterator(); j.hasNext(); ) { TypeVariableBV current = (TypeVariableBV) j.next(); if (DEBUG) { s.append(" " + current + "\n"); } if (previous == null) { previous = current; } else { try { previous = previous.union(current); } catch (TypeException e) { if (DEBUG) { G.v().out.println(s); } throw e; } } } } }
public TypeNode(int id, Type type) { this.id = id; this.type = type; if (DEBUG) { G.v().out.println("creating node " + this); } }
@Override public boolean equals(Object obj) { if (this == obj) return true; if (getClass().isInstance(obj)) { WrappedEntity<?, ?> other = (WrappedEntity<?, ?>) obj; return actual().equals(other.actual()) && graphdb.equals(other.graphdb); } return false; }