/** * Executes example. * * @param args Command line arguments, none required. */ public static void main(String[] args) { // Typedefs: // --------- // G -> GridFactory // CI1 -> GridInClosure // CO -> GridOutClosure // CA -> GridAbsClosure // F -> GridFunc // Data initialisation. Random rand = new Random(); final int size = 20; Collection<Integer> nums = new ArrayList<Integer>(size); // Generate list of random integers. for (int i = 0; i < size; i++) { nums.add(rand.nextInt(size)); } // Print generated list. X.println("Generated list:"); F.forEach(nums, F.<Integer>print("", " ")); // Get new unmodifiable collection with elements which value low than half generated list size. Collection<Integer> view = F.view( nums, new P1<Integer>() { @Override public boolean apply(Integer i) { return i < size / 2; } }); // Print result. X.println("\nResult list:"); F.forEach(view, F.<Integer>print("", " ")); // Check for read only. try { view.add(12); } catch (Exception ignored) { X.println("\nView is read only."); } }
/** {@inheritDoc} */ @Override public void explicitUndeploy(UUID nodeId, String rsrcName) { Collection<SharedDeployment> undeployed = new LinkedList<SharedDeployment>(); synchronized (mux) { for (Iterator<List<SharedDeployment>> i1 = cache.values().iterator(); i1.hasNext(); ) { List<SharedDeployment> deps = i1.next(); for (Iterator<SharedDeployment> i2 = deps.iterator(); i2.hasNext(); ) { SharedDeployment dep = i2.next(); if (dep.hasName(rsrcName)) { if (!dep.isUndeployed()) { dep.undeploy(); dep.onRemoved(); // Undeploy. i2.remove(); undeployed.add(dep); if (log.isInfoEnabled()) log.info("Undeployed per-version class loader: " + dep); } break; } } if (deps.isEmpty()) i1.remove(); } } recordUndeployed(null, undeployed); }
/** * The added suite will be always executed locally, but in parallel with other locally or remotely * running tests. This comes handy for tests that cannot be distributed for some environmental * reasons, but still would benefit from parallel execution. * * <p>Note, that local suites will be executed on local node even if grid topology only allows * remote nodes. * * @param localSuite Test to execute locally in parallel with other local or distributed tests. */ @SuppressWarnings({"TypeMayBeWeakened"}) public void addTest(GridJunit3LocalTestSuite localSuite) { if (!locTests.contains(localSuite.getName())) { locTests.add(localSuite.getName()); } addTest((Test) localSuite); }
/** {@inheritDoc} */ @Override public Collection<UUID> nodeIds() { Collection<UUID> ids = new GridLeanSet<UUID>(); ids.add(cctx.nodeId()); ids.addAll(mappings.keySet()); return ids; }
/** {@inheritDoc} */ @Override public Collection<GridDeployment> getDeployments() { Collection<GridDeployment> deps = new LinkedList<GridDeployment>(); synchronized (mux) { for (List<SharedDeployment> list : cache.values()) for (SharedDeployment d : list) deps.add(d); } return deps; }
/** * Executes example. * * @param args Command line arguments, none required. */ public static void main(String[] args) { // Typedefs: // --------- // G -> GridFactory // CI1 -> GridInClosure // CO -> GridOutClosure // CA -> GridAbsClosure // F -> GridFunc // Data initialisation. Random rand = new Random(); final int size = 20; Collection<Integer> nums = new ArrayList<Integer>(size); // Generate list of random integers. for (int i = 0; i < size; i++) { nums.add(rand.nextInt(size)); } // Print generated list. X.println("Generated list:"); F.forEach(nums, F.<Integer>print("", " ")); // Retain all elements which value low than half generated list size. Collection<Integer> res = F.retain( nums, true, new P1<Integer>() { @Override public boolean apply(Integer i) { return i < size / 2; } }); // Print result. X.println("\nResult list:"); F.forEach(res, F.<Integer>print("", " ")); // Retain first half of result list. F.retain(res, false, res.size() / 2); // Print result. X.println("\nResult list:"); F.forEach(res, F.<Integer>print("", " ")); }
/** {@inheritDoc} */ @Override public Collection<GridDeployment> getDeployments() { Collection<GridDeployment> deps = new ArrayList<GridDeployment>(); synchronized (mux) { for (List<GridDeployment> depList : cache.values()) { for (GridDeployment d : depList) { if (!deps.contains(d)) { deps.add(d); } } } return deps; } }
/** {@inheritDoc} */ @Override public Map<GridRichNode, Collection<K>> mapKeysToNodes(Collection<? extends K> keys) { Map<GridRichNode, Collection<K>> map = new HashMap<GridRichNode, Collection<K>>(); for (K key : keys) { Collection<GridRichNode> nodes = ctx.allNodes(key); for (GridRichNode node : nodes) { Collection<K> keyCol = map.get(node); if (keyCol == null) map.put(node, keyCol = new LinkedList<K>()); keyCol.add(key); } } return map; }
/** {@inheritDoc} */ @Override public void stop() { Collection<SharedDeployment> copy = new HashSet<SharedDeployment>(); synchronized (mux) { for (List<SharedDeployment> deps : cache.values()) for (SharedDeployment dep : deps) { // Mark undeployed. dep.undeploy(); copy.add(dep); } cache.clear(); } for (SharedDeployment dep : copy) dep.recordUndeployed(null); if (log.isDebugEnabled()) log.debug(stopInfo()); }
/** * Adds a test to be executed on the grid. In case of test suite, all tests inside of test suite * will be executed sequentially on some remote node. * * @param test Test to add. */ @Override public void addTest(Test test) { if (copy == null) { copy = new TestSuite(getName()); } // Add test to the list of local ones. if (test instanceof GridJunit3LocalTestSuite) { String testName = ((TestSuite) test).getName(); if (!locTests.contains(testName)) { locTests.add(testName); } } if (test instanceof GridJunit3TestSuite) { copy.addTest(((GridJunit3TestSuite) test).copy); super.addTest(new GridJunit3TestSuiteProxy(((GridJunit3TestSuite) test).copy, factory)); } else if (test instanceof GridJunit3TestSuiteProxy) { copy.addTest(((GridJunit3TestSuiteProxy) test).getOriginal()); super.addTest(test); } else if (test instanceof GridJunit3TestCaseProxy) { copy.addTest(((GridJunit3TestCaseProxy) test).getGridGainJunit3OriginalTestCase()); super.addTest(test); } else if (test instanceof TestSuite) { copy.addTest(test); super.addTest(new GridJunit3TestSuiteProxy((TestSuite) test, factory)); } else { assert test instanceof TestCase : "Test must be either instance of TestSuite or TestCase: " + test; copy.addTest(test); super.addTest(factory.createProxy((TestCase) test)); } }
/** * @param ldr Class loader to undeploy. * @param recEvt Whether or not to record the event. */ private void undeploy(ClassLoader ldr, boolean recEvt) { Collection<GridDeployment> doomed = new HashSet<GridDeployment>(); synchronized (mux) { for (Iterator<LinkedList<GridDeployment>> i1 = cache.values().iterator(); i1.hasNext(); ) { LinkedList<GridDeployment> deps = i1.next(); for (Iterator<GridDeployment> i2 = deps.iterator(); i2.hasNext(); ) { GridDeployment dep = i2.next(); if (dep.classLoader() == ldr) { dep.undeploy(); i2.remove(); doomed.add(dep); if (log.isInfoEnabled()) { log.info("Removed undeployed class: " + dep); } } } if (deps.isEmpty()) { i1.remove(); } } } for (GridDeployment dep : doomed) { if (dep.isObsolete()) { // Resource cleanup. ctx.resource().onUndeployed(dep); } if (recEvt) { recordUndeploy(dep, true); } } }
/** {@inheritDoc} */ @Override public void unlockAll( Collection<? extends K> keys, GridPredicate<? super GridCacheEntry<K, V>>[] filter) { if (keys.isEmpty()) return; try { GridCacheVersion ver = null; Collection<GridRichNode> affNodes = null; int keyCnt = -1; Map<GridRichNode, GridNearUnlockRequest<K, V>> map = null; Collection<K> locKeys = new LinkedList<K>(); GridCacheVersion obsoleteVer = ctx.versions().next(); for (K key : keys) { while (true) { GridDistributedCacheEntry<K, V> entry = peekExx(key); if (entry == null || !ctx.isAll(entry.wrap(false), filter)) break; // While. try { GridCacheMvccCandidate<K> cand = entry.candidate(ctx.nodeId(), Thread.currentThread().getId()); if (cand != null) { ver = cand.version(); if (affNodes == null) { affNodes = CU.allNodes(ctx, cand.topologyVersion()); keyCnt = (int) Math.ceil((double) keys.size() / affNodes.size()); map = new HashMap<GridRichNode, GridNearUnlockRequest<K, V>>(affNodes.size()); } // Send request to remove from remote nodes. GridRichNode primary = CU.primary0(ctx.affinity(key, affNodes)); GridNearUnlockRequest<K, V> req = map.get(primary); if (req == null) { map.put(primary, req = new GridNearUnlockRequest<K, V>(keyCnt)); req.version(ver); } // Remove candidate from local node first. GridCacheMvccCandidate<K> rmv = entry.removeLock(); if (rmv != null) { if (!rmv.reentry()) { if (ver != null && !ver.equals(rmv.version())) throw new GridException( "Failed to unlock (if keys were locked separately, " + "then they need to be unlocked separately): " + keys); if (!primary.isLocal()) { assert req != null; req.addKey(entry.key(), entry.getOrMarshalKeyBytes(), ctx); } else locKeys.add(key); if (log.isDebugEnabled()) log.debug("Removed lock (will distribute): " + rmv); } else if (log.isDebugEnabled()) log.debug( "Current thread still owns lock (or there are no other nodes)" + " [lock=" + rmv + ", curThreadId=" + Thread.currentThread().getId() + ']'); } // Try to evict near entry if it's dht-mapped locally. evictNearEntry(entry, obsoleteVer); } break; } catch (GridCacheEntryRemovedException ignore) { if (log.isDebugEnabled()) log.debug("Attempted to unlock removed entry (will retry): " + entry); } } } if (ver == null) return; for (Map.Entry<GridRichNode, GridNearUnlockRequest<K, V>> mapping : map.entrySet()) { GridRichNode n = mapping.getKey(); GridDistributedUnlockRequest<K, V> req = mapping.getValue(); if (n.isLocal()) dht.removeLocks(ctx.nodeId(), req.version(), locKeys, true); else if (!req.keyBytes().isEmpty()) // We don't wait for reply to this message. ctx.io().send(n, req); } } catch (GridException ex) { U.error(log, "Failed to unlock the lock for keys: " + keys, ex); } }
/** * See <a href="http://e-docs.bea.com/wls/docs100/javadocs/weblogic/common/T3StartupDef.html"> * http://e-docs.bea.com/wls/docs100/javadocs/weblogic/common/T3StartupDef.html</a> for more * information. * * @param str Virtual name by which the class is registered as a {@code startupClass} in the * {@code config.xml} file * @param params A hashtable that is made up of the name-value pairs supplied from the {@code * startupArgs} property * @return Result string (log message). * @throws Exception Thrown if error occurred. */ @SuppressWarnings({"unchecked", "CatchGenericClass"}) @Override public String startup(String str, Hashtable params) throws Exception { GridLogger log = new GridJavaLogger(LoggingHelper.getServerLogger()); cfgFile = (String) params.get(cfgFilePathParam); if (cfgFile == null) { throw new IllegalArgumentException("Failed to read property: " + cfgFilePathParam); } String workMgrName = (String) params.get(workMgrParam); URL cfgUrl = U.resolveGridGainUrl(cfgFile); if (cfgUrl == null) throw new ServerLifecycleException( "Failed to find Spring configuration file (path provided should be " + "either absolute, relative to GRIDGAIN_HOME, or relative to META-INF folder): " + cfgFile); GenericApplicationContext springCtx; try { springCtx = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(springCtx); xmlReader.loadBeanDefinitions(new UrlResource(cfgUrl)); springCtx.refresh(); } catch (BeansException e) { throw new ServerLifecycleException( "Failed to instantiate Spring XML application context: " + e.getMessage(), e); } Map cfgMap; try { // Note: Spring is not generics-friendly. cfgMap = springCtx.getBeansOfType(GridConfiguration.class); } catch (BeansException e) { throw new ServerLifecycleException( "Failed to instantiate bean [type=" + GridConfiguration.class + ", err=" + e.getMessage() + ']', e); } if (cfgMap == null) throw new ServerLifecycleException( "Failed to find a single grid factory configuration in: " + cfgUrl); if (cfgMap.isEmpty()) throw new ServerLifecycleException("Can't find grid factory configuration in: " + cfgUrl); try { ExecutorService execSvc = null; MBeanServer mbeanSrv = null; for (GridConfiguration cfg : (Collection<GridConfiguration>) cfgMap.values()) { assert cfg != null; GridConfigurationAdapter adapter = new GridConfigurationAdapter(cfg); // Set logger. if (cfg.getGridLogger() == null) adapter.setGridLogger(log); if (cfg.getExecutorService() == null) { if (execSvc == null) execSvc = workMgrName != null ? new GridThreadWorkManagerExecutor(workMgrName) : new GridThreadWorkManagerExecutor(J2EEWorkManager.getDefault()); adapter.setExecutorService(execSvc); } if (cfg.getMBeanServer() == null) { if (mbeanSrv == null) { InitialContext ctx = null; try { ctx = new InitialContext(); mbeanSrv = (MBeanServer) ctx.lookup("java:comp/jmx/runtime"); } catch (Exception e) { throw new IllegalArgumentException( "MBean server was not provided and failed to obtain " + "Weblogic MBean server.", e); } finally { if (ctx != null) ctx.close(); } } adapter.setMBeanServer(mbeanSrv); } Grid grid = G.start(adapter, springCtx); // Test if grid is not null - started properly. if (grid != null) gridNames.add(grid.name()); } return getClass().getSimpleName() + " started successfully."; } catch (GridException e) { // Stop started grids only. for (String name : gridNames) G.stop(name, true); throw new ServerLifecycleException("Failed to start GridGain.", e); } }
/** {@inheritDoc} */ @Override public void onKernalStart() throws GridException { discoLsnr = new GridLocalEventListener() { @Override public void onEvent(GridEvent evt) { assert evt instanceof GridDiscoveryEvent; assert evt.type() == EVT_NODE_LEFT || evt.type() == EVT_NODE_FAILED; GridDiscoveryEvent discoEvt = (GridDiscoveryEvent) evt; Collection<SharedDeployment> undeployed = new LinkedList<SharedDeployment>(); if (log.isDebugEnabled()) log.debug("Processing node departure event: " + evt); synchronized (mux) { for (Iterator<List<SharedDeployment>> i1 = cache.values().iterator(); i1.hasNext(); ) { List<SharedDeployment> deps = i1.next(); for (Iterator<SharedDeployment> i2 = deps.iterator(); i2.hasNext(); ) { SharedDeployment dep = i2.next(); dep.removeParticipant(discoEvt.eventNodeId()); if (!dep.hasParticipants()) { if (dep.deployMode() == SHARED) { if (!dep.isUndeployed()) { dep.undeploy(); // Undeploy. i2.remove(); assert !dep.isRemoved(); dep.onRemoved(); undeployed.add(dep); if (log.isDebugEnabled()) log.debug( "Undeployed class loader as there are no participating " + "nodes: " + dep); } } else if (log.isDebugEnabled()) log.debug("Preserving deployment without node participants: " + dep); } else if (log.isDebugEnabled()) log.debug("Keeping deployment as it still has participants: " + dep); } if (deps.isEmpty()) i1.remove(); } } recordUndeployed(discoEvt.eventNodeId(), undeployed); } }; ctx.event().addLocalEventListener(discoLsnr, EVT_NODE_FAILED, EVT_NODE_LEFT); Collection<SharedDeployment> undeployed = new LinkedList<SharedDeployment>(); synchronized (mux) { for (Iterator<List<SharedDeployment>> i1 = cache.values().iterator(); i1.hasNext(); ) { List<SharedDeployment> deps = i1.next(); for (Iterator<SharedDeployment> i2 = deps.iterator(); i2.hasNext(); ) { SharedDeployment dep = i2.next(); for (UUID nodeId : dep.getParticipantNodeIds()) if (ctx.discovery().node(nodeId) == null) dep.removeParticipant(nodeId); if (!dep.hasParticipants()) { if (dep.deployMode() == SHARED) { if (!dep.isUndeployed()) { dep.undeploy(); // Undeploy. i2.remove(); dep.onRemoved(); undeployed.add(dep); if (log.isDebugEnabled()) log.debug("Undeployed class loader as there are no participating nodes: " + dep); } } else if (log.isDebugEnabled()) log.debug("Preserving deployment without node participants: " + dep); } else if (log.isDebugEnabled()) log.debug("Keeping deployment as it still has participants: " + dep); } if (deps.isEmpty()) i1.remove(); } } recordUndeployed(null, undeployed); if (log.isDebugEnabled()) log.debug("Registered deployment discovery listener: " + discoLsnr); }