/** * 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); } }
/** * 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); } }
/** @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); }
/** @throws Exception If failed. */ @SuppressWarnings("NullableProblems") public void testLocalNullGgfsNameIsSupported() throws Exception { g1Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); g1GgfsCfg1.setName(null); assertFalse(G.start(g1Cfg).nodes().isEmpty()); }
/** * 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 { // This method will be executed on a remote grid nodes. int phraseLen = sayIt("Hello World"); X.println(">>>"); X.println(">>> Finished executing Gridify \"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); } }
/** * Starts up grid and checks all provided values for prime. * * @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 { // Starts grid. Grid grid = args.length == 0 ? G.start() : G.start(args[0]); // Values we want to check for prime. long[] checkVals = {32452841, 32452843, 32452847, 32452849, 236887699, 217645199}; X.println(">>>"); X.println( ">>> Starting to check the following numbers for primes: " + Arrays.toString(checkVals)); try { long start = System.currentTimeMillis(); for (long checkVal : checkVals) { // This method will be executed on the Grid as it is // annotated with @Gridify annotation. Long divisor = GridPrimeChecker.checkPrime(checkVal, 2, checkVal); // If divisor is null, then the number is prime. if (divisor == null) { X.println("Value '" + checkVal + "'is a prime number."); } else { X.println("Value '" + checkVal + "' is divisible by '" + divisor + '\''); } } long totalTime = System.currentTimeMillis() - start; X.println(">>> Total time to calculate all primes (milliseconds): " + totalTime); X.println(">>>"); } finally { // Stops grid. G.stop(grid.name(), true); } }
/** @throws Exception If failed. */ public void testRemoteIfAffinityMapperGroupSizeDiffers() throws Exception { GridConfiguration g2Cfg = getConfiguration("g2"); g1Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); g2Cfg.setCacheConfiguration( concat(dataCaches(4021), metaCaches(), GridCacheConfiguration.class)); G.start(g1Cfg); checkGridStartFails( g2Cfg, "Affinity mapper group size should be the same on all nodes in grid for GGFS", false); }
/** * Starts the local node and checks for presence of log file. Also checks that this is really a * log of a started node. * * @param id Test-local node ID. * @throws Exception If error occurred. */ private void checkOneNode(int id) throws Exception { try (Grid grid = G.start(getConfiguration("grid" + id))) { String id8 = U.id8(grid.localNode().id()); String logPath = "work/log/gridgain-" + id8 + ".log"; File logFile = U.resolveGridGainPath(logPath); assertNotNull("Failed to resolve path: " + logPath, logFile); assertTrue("Log file does not exist: " + logFile, logFile.exists()); String logContent = U.readFileToString(logFile.getAbsolutePath(), "UTF-8"); assertTrue( "Log file does not contain it's node ID: " + logFile, logContent.contains(">>> Local node [ID=" + id8.toUpperCase())); } }
/** * Starts new grid node. * * @param gridName name of new node. * @param springCfg file with spring configuration to use for this node. * @return a grid instance local to new node {@link GridGain#start(GridConfiguration)}. * @throws Exception if node run failed. */ protected Grid startNode(String gridName, File springCfg) throws Exception { assert springCfg != null; ListableBeanFactory springCtx = new FileSystemXmlApplicationContext("file:///" + springCfg.getAbsolutePath()); Map cfgMap = springCtx.getBeansOfType(GridConfiguration.class); assert cfgMap != null; assert !cfgMap.isEmpty(); GridConfiguration cfg = (GridConfiguration) cfgMap.values().iterator().next(); cfg.setGridName(gridName + "-" + getNextNodeNum()); return G.start(cfg); }
/** @throws Exception If failed. */ public void testRemoteIfDataBlockSizeDiffers() throws Exception { GridConfiguration g2Cfg = getConfiguration("g2"); g1Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); g2Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); GridGgfsConfiguration g2GgfsCfg1 = new GridGgfsConfiguration(g1GgfsCfg1); g2GgfsCfg1.setBlockSize(g2GgfsCfg1.getBlockSize() + 100); g2Cfg.setGgfsConfiguration(g2GgfsCfg1, g1GgfsCfg2); G.start(g1Cfg); checkGridStartFails( g2Cfg, "Data block size should be same on all nodes in grid for GGFS", false); }
/** * Checks that the given grid configuration will lead to {@link GridException} upon grid startup. * * @param cfg Grid configuration to check. * @param excMsgSnippet Root cause (assertion) exception message snippet. * @param testLoc {@code True} if checking is done for "testLocal" tests. */ private void checkGridStartFails( GridConfiguration cfg, CharSequence excMsgSnippet, boolean testLoc) { assertNotNull(cfg); assertNotNull(excMsgSnippet); try { G.start(cfg); fail("No exception has been thrown."); } catch (GridException e) { if (testLoc) { if ("Failed to start processor: GridProcessorAdapter []".equals(e.getMessage()) && e.getCause().getMessage().contains(excMsgSnippet)) return; // Expected exception. } else if (e.getMessage().contains(excMsgSnippet)) return; // Expected exception. error("Caught unexpected exception.", e); fail(); } }
/** @throws Exception If failed. */ public void testRemoteIfPathModeDiffers() throws Exception { GridConfiguration g2Cfg = getConfiguration("g2"); GridGgfsConfiguration g2GgfsCfg1 = new GridGgfsConfiguration(g1GgfsCfg1); GridGgfsConfiguration g2GgfsCfg2 = new GridGgfsConfiguration(g1GgfsCfg2); g2GgfsCfg1.setPathModes(ImmutableMap.of("/somePath", DUAL_SYNC)); g2GgfsCfg2.setPathModes(ImmutableMap.of("/somePath", DUAL_SYNC)); g1Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); g2Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); g2Cfg.setGgfsConfiguration(g2GgfsCfg1, g2GgfsCfg2); G.start(g1Cfg); checkGridStartFails( g2Cfg, "Path modes should be the same on all nodes in grid for GGFS", false); }
/** * Runs JDBC example. * * @param args Command line arguments. * @throws Exception In case of error. */ public static void main(String[] args) throws Exception { Grid grid = G.start("examples/config/spring-cache.xml"); Connection conn = null; try { // Populate cache with data. populate(grid.cache(CACHE_NAME)); // Register JDBC driver. Class.forName("org.gridgain.jdbc.GridJdbcDriver"); // Open JDBC connection. conn = DriverManager.getConnection("jdbc:gridgain://localhost/" + CACHE_NAME, configuration()); X.println(">>>"); // Query all persons. queryAllPersons(conn); X.println(">>>"); // Query person older than 30 years. queryPersons(conn, 30); X.println(">>>"); // Query persons working in GridGain. queryPersonsInOrganization(conn, "GridGain"); X.println(">>>"); } finally { // Close JDBC connection. if (conn != null) conn.close(); G.stop(true); } }
/** * Starts Grid instance. Note that if grid is already started, then it will be looked up and * returned from this method. * * @return Started grid. */ private Grid startGrid() { Properties props = System.getProperties(); gridName = props.getProperty(GRIDGAIN_NAME.name()); if (!props.containsKey(GRIDGAIN_NAME.name()) || G.state(gridName) != GridFactoryState.STARTED) { selfStarted = true; // Set class loader for the spring. ClassLoader curCl = Thread.currentThread().getContextClassLoader(); // Add no-op logger to remove no-appender warning. Appender app = new NullAppender(); Logger.getRootLogger().addAppender(app); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); Grid grid = G.start(cfgPath); gridName = grid.name(); System.setProperty(GRIDGAIN_NAME.name(), grid.name()); return grid; } catch (GridException e) { throw new GridRuntimeException("Failed to start grid: " + cfgPath, e); } finally { Logger.getRootLogger().removeAppender(app); Thread.currentThread().setContextClassLoader(curCl); } } return G.grid(gridName); }
/** * Executes {@link GridSegmentATask} and {@link GridSegmentBTask} tasks on the grid. * * @param args Command line arguments, none required or used. * @throws GridException If example execution failed. */ public static void main(String[] args) throws GridException { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("org/gridgain/examples/multispi/master.xml"); // Get configuration from Spring. GridConfiguration cfg = ctx.getBean("grid.cfg", GridConfiguration.class); G.start(cfg); try { Grid grid = G.grid(); // Execute task on segment "A". GridTaskFuture<Integer> futA = grid.execute(GridSegmentATask.class, null); // Execute task on segment "B". GridTaskFuture<Integer> futB = grid.execute(GridSegmentBTask.class, null); // Wait for task completion. futA.get(); futB.get(); X.println(">>>"); X.println(">>> Finished executing Grid \"Multiple Topology\" example with custom tasks."); X.println( ">>> You should see print out of 'Executing job on node that is from segment A.'" + "on node that has attribute \"segment=A\""); X.println( ">>> and 'Executing job on node that is from segment B.' on node that has " + "attribute \"segment=B\""); X.println(">>> Check all nodes for output (this node is not a part of the grid)."); X.println(">>>"); } finally { G.stop(true); } }
/** @throws Exception If failed. */ public void testRemoteIfDefaultModeDiffers() throws Exception { GridConfiguration g2Cfg = getConfiguration("g2"); GridGgfsConfiguration g2GgfsCfg1 = new GridGgfsConfiguration(g1GgfsCfg1); GridGgfsConfiguration g2GgfsCfg2 = new GridGgfsConfiguration(g1GgfsCfg2); g1GgfsCfg1.setDefaultMode(DUAL_ASYNC); g1GgfsCfg2.setDefaultMode(DUAL_ASYNC); g2GgfsCfg1.setDefaultMode(DUAL_SYNC); g2GgfsCfg2.setDefaultMode(DUAL_SYNC); g1Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); g2Cfg.setCacheConfiguration( concat(dataCaches(1024), metaCaches(), GridCacheConfiguration.class)); g2Cfg.setGgfsConfiguration(g2GgfsCfg1, g2GgfsCfg2); G.start(g1Cfg); checkGridStartFails( g2Cfg, "Default mode should be the same on all nodes in grid for GGFS", false); }
/** @throws Exception If failed. */ public void testRemoteIfMetaCacheNameDiffers() throws Exception { GridConfiguration g2Cfg = getConfiguration("g2"); GridGgfsConfiguration g2GgfsCfg1 = new GridGgfsConfiguration(g1GgfsCfg1); GridGgfsConfiguration g2GgfsCfg2 = new GridGgfsConfiguration(g1GgfsCfg2); 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, "Meta cache name should be the same on all nodes in grid for GGFS", false); }
/** * Runs basic cache example. * * @param args Command line arguments, none required. * @throws Exception If example execution failed. */ public static void main(String[] args) throws Exception { final Grid g = args.length == 0 ? G.start("examples/config/spring-cache.xml") : G.start(args[0]); try { // Subscribe to events on every node, so we can visualize what's // happening in remote caches. g.run( BROADCAST, new CA() { @Override public void apply() { GridLocalEventListener lsnr = new GridLocalEventListener() { @Override public void onEvent(GridEvent event) { switch (event.type()) { case EVT_CACHE_OBJECT_PUT: case EVT_CACHE_OBJECT_READ: case EVT_CACHE_OBJECT_REMOVED: { GridCacheEvent e = (GridCacheEvent) event; X.println("Cache event [name=" + e.name() + ", key=" + e.key() + ']'); } } } }; GridNodeLocal<String, GridLocalEventListener> loc = g.nodeLocal(); GridLocalEventListener prev = loc.remove("lsnr"); // If there is a listener subscribed from previous runs, unsubscribe it. if (prev != null) g.removeLocalEventListener(prev); // Record new listener, so we can check it on next run. loc.put("lsnr", lsnr); // Subscribe listener. g.addLocalEventListener(lsnr, EVTS_CACHE); } }); final GridCacheProjection<Integer, String> cache = g.cache(CACHE_NAME).projection(Integer.class, String.class); final int keyCnt = 20; // Store keys in cache. for (int i = 0; i < keyCnt; i++) cache.putx(i, Integer.toString(i)); // Peek and get on local node. for (int i = 0; i < keyCnt; i++) { X.println("Peeked [key=" + i + ", val=" + cache.peek(i) + ']'); X.println("Got [key=" + i + ", val=" + cache.get(i) + ']'); } // Projection (view) for remote nodes. GridProjection rmts = g.remoteProjection(); if (!rmts.isEmpty()) { // Peek and get on remote nodes (comment it out if output gets too crowded). g.remoteProjection() .run( BROADCAST, new GridAbsClosureX() { @Override public void applyx() throws GridException { for (int i = 0; i < keyCnt; i++) { X.println("Peeked [key=" + i + ", val=" + cache.peek(i) + ']'); X.println("Got [key=" + i + ", val=" + cache.get(i) + ']'); } } }); } } finally { G.stop(true); } }
/** * @param args Command arguments. * @throws GridException If failed. */ public static void main(String[] args) throws GridException { // Starts grid. Grid grid = args.length == 0 ? G.start() : G.start(args[0]); try { // Create portfolio. GridCredit[] portfolio = new GridCredit[5000]; Random rnd = new Random(); // Generate some test portfolio items. for (int i = 0; i < portfolio.length; i++) { portfolio[i] = new GridCredit( 50000 * rnd.nextDouble(), // Credit amount. rnd.nextInt(1000), // Credit term in days. rnd.nextDouble() / 10, // APR. rnd.nextDouble() / 20 + 0.02 // EDF. ); } // Forecast horizon in days. int horizon = 365; // Number of Monte-Carlo iterations. int iter = 10000; // Percentile. double percentile = 0.95; // Mark the stopwatch. long start = System.currentTimeMillis(); // Calculate credit risk and print it out. // As you can see the grid enabling is completely hidden from the caller // and it is fully transparent to him. In fact, the caller is never directly // aware if method was executed just locally or on the 100s of grid nodes. // Credit risk crdRisk is the minimal amount that creditor has to have // available to cover possible defaults. double crdRisk = grid.reduce( SPREAD, closures(grid.size(), portfolio, horizon, iter, percentile), new R1<Double, Double>() { /** Collected values sum. */ private double sum; /** Collected values count. */ private int count; /** {@inheritDoc} */ @Override public boolean collect(Double e) { sum += e; count++; return true; } /** {@inheritDoc} */ @Override public Double apply() { return sum / count; } }); X.println( "Credit risk [crdRisk=" + crdRisk + ", duration=" + (System.currentTimeMillis() - start) + "ms]"); } // We specifically don't do any error handling here to // simplify the example. Real application may want to // add error handling and application specific recovery. finally { // Stops grid. G.stop(true); } }
/** * 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); } }