/** Init. */ @PostConstruct public void init() { logger.info("Setting up Ignite Ticket Registry..."); configureSecureTransport(); if (logger.isDebugEnabled()) { logger.debug( "igniteConfiguration.cacheConfiguration={}", this.igniteConfiguration.getCacheConfiguration()); logger.debug( "igniteConfiguration.getDiscoverySpi={}", this.igniteConfiguration.getDiscoverySpi()); logger.debug( "igniteConfiguration.getSslContextFactory={}", this.igniteConfiguration.getSslContextFactory()); } if (Ignition.state() == IgniteState.STOPPED) { this.ignite = Ignition.start(this.igniteConfiguration); } else if (Ignition.state() == IgniteState.STARTED) { this.ignite = Ignition.ignite(); } this.ticketIgniteCache = this.ignite.getOrCreateCache( casProperties.getTicket().getRegistry().getIgnite().getTicketsCache().getCacheName()); }
@Override protected void doStart() throws Exception { super.doStart(); if (lifecycleMode == IgniteLifecycleMode.USER_MANAGED) { return; } // Try to load the configuration from the resource. if (configurationResource != null) { if (configurationResource instanceof URL) { ignite = Ignition.start((URL) configurationResource); } else if (configurationResource instanceof InputStream) { ignite = Ignition.start((InputStream) configurationResource); } else if (configurationResource instanceof String) { ignite = Ignition.start((String) configurationResource); } else { throw new IllegalStateException( "An unsupported configuration resource was provided to the Ignite component. " + "Supported types are: URL, InputStream, String."); } } else if (igniteConfiguration != null) { ignite = Ignition.start(igniteConfiguration); } else { throw new IllegalStateException( "No configuration resource or IgniteConfiguration was provided to the Ignite component."); } }
/** * Executes example. * * @param args Command line arguments, none required. * @throws Exception If example execution failed. */ public static void main(String[] args) throws Exception { Ignite ignite = Ignition.start("examples/config/filesystem/example-igfs.xml"); System.out.println(); System.out.println(">>> IGFS example started."); try { // Get an instance of Ignite File System. IgniteFileSystem fs = ignite.fileSystem("igfs"); // Working directory path. IgfsPath workDir = new IgfsPath("/examples/fs"); // Cleanup working directory. delete(fs, workDir); // Create empty working directory. mkdirs(fs, workDir); // Print information for working directory. printInfo(fs, workDir); // File path. IgfsPath filePath = new IgfsPath(workDir, "file.txt"); // Create file. create(fs, filePath, new byte[] {1, 2, 3}); // Print information for file. printInfo(fs, filePath); // Append more data to previously created file. append(fs, filePath, new byte[] {4, 5}); // Print information for file. printInfo(fs, filePath); // Read data from file. read(fs, filePath); // Delete file. delete(fs, filePath); // Print information for file. printInfo(fs, filePath); // Create several files. for (int i = 0; i < 5; i++) create(fs, new IgfsPath(workDir, "file-" + i + ".txt"), null); list(fs, workDir); } finally { Ignition.stop(false); } }
/** * Executes example. * * @param args Command line arguments, none required. * @throws IgniteException If example execution failed. */ public static void main(String[] args) throws IgniteException { try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(); System.out.println("Compute schedule example started."); // Schedule output message every minute. SchedulerFuture<?> fut = ignite .scheduler() .scheduleLocal( () -> ignite .compute() .broadcast( () -> { System.out.println(); System.out.println("Howdy! :)"); return "Howdy! :)"; }), "{5, 3} * * * * *" // Cron expression. ); while (!fut.isDone()) System.out.println(">>> Invocation result: " + fut.get()); System.out.println(); System.out.println(">>> Schedule future is done and has been unscheduled."); System.out.println(">>> Check all nodes for hello message output."); } }
/** * Listen to events that happen only on local node. * * @throws IgniteException If failed. */ private static void localListen() throws IgniteException { System.out.println(); System.out.println(">>> Local event listener example."); Ignite ignite = Ignition.ignite(); IgnitePredicate<TaskEvent> lsnr = evt -> { System.out.println( "Received task event [evt=" + evt.name() + ", taskName=" + evt.taskName() + ']'); return true; // Return true to continue listening. }; // Register event listener for all local task execution events. ignite.events().localListen(lsnr, EVTS_TASK_EXECUTION); // Generate task events. ignite .compute() .withName("example-event-task") .run(() -> System.out.println("Executing sample job.")); // Unsubscribe local task event listener. ignite.events().stopLocalListen(lsnr); }
/** * Executes example. * * @param args Command line arguments, none required. */ public static void main(String[] args) { try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(); System.out.println(">>> Cache star schema example started."); CacheConfiguration<Integer, FactPurchase> factCacheCfg = new CacheConfiguration<>(PARTITIONED_CACHE_NAME); factCacheCfg.setCacheMode(CacheMode.PARTITIONED); factCacheCfg.setIndexedTypes(Integer.class, FactPurchase.class); CacheConfiguration<Integer, Object> dimCacheCfg = new CacheConfiguration<>(REPLICATED_CACHE_NAME); dimCacheCfg.setCacheMode(CacheMode.REPLICATED); dimCacheCfg.setIndexedTypes( Integer.class, DimStore.class, Integer.class, DimProduct.class); try (IgniteCache<Integer, FactPurchase> factCache = ignite.getOrCreateCache(factCacheCfg); IgniteCache<Integer, Object> dimCache = ignite.getOrCreateCache(dimCacheCfg)) { populateDimensions(dimCache); populateFacts(factCache); queryStorePurchases(); queryProductPurchases(); } } }
/** * Query all purchases made at a specific store for 3 specific products. This query uses * cross-cache joins between {@link DimStore}, {@link DimProduct} objects stored in {@code * 'replicated'} cache and {@link FactPurchase} objects stored in {@code 'partitioned'} cache. * * @throws IgniteException If failed. */ private static void queryProductPurchases() { IgniteCache<Integer, FactPurchase> factCache = Ignition.ignite().cache(PARTITIONED_CACHE_NAME); // All purchases for certain product made at store2. // ================================================= DimProduct p1 = rand(dataProduct.values()); DimProduct p2 = rand(dataProduct.values()); DimProduct p3 = rand(dataProduct.values()); System.out.println( "IDs of products [p1=" + p1.getId() + ", p2=" + p2.getId() + ", p3=" + p3.getId() + ']'); // Create cross cache query to get all purchases made at store2 // for specified products. QueryCursor<Cache.Entry<Integer, FactPurchase>> prodPurchases = factCache.query( new SqlQuery( FactPurchase.class, "from \"" + REPLICATED_CACHE_NAME + "\".DimStore, \"" + REPLICATED_CACHE_NAME + "\".DimProduct, " + "\"" + PARTITIONED_CACHE_NAME + "\".FactPurchase " + "where DimStore.id=FactPurchase.storeId and DimProduct.id=FactPurchase.productId " + "and DimStore.name=? and DimProduct.id in(?, ?, ?)") .setArgs("Store2", p1.getId(), p2.getId(), p3.getId())); printQueryResults( "All purchases made at store2 for 3 specific products:", prodPurchases.getAll()); }
/** {@inheritDoc} */ @Override public void start(BenchmarkConfiguration cfg) throws Exception { IgniteBenchmarkArguments args = new IgniteBenchmarkArguments(); BenchmarkUtils.jcommander(cfg.commandLineArguments(), args, "<ignite-node>"); IgniteConfiguration c = loadConfiguration(args.configuration()); assert c != null; // Server node doesn't contains cache configuration. Driver will create dynamic cache. c.setCacheConfiguration(); TransactionConfiguration tc = c.getTransactionConfiguration(); tc.setDefaultTxConcurrency(args.txConcurrency()); tc.setDefaultTxIsolation(args.txIsolation()); TcpCommunicationSpi commSpi = (TcpCommunicationSpi) c.getCommunicationSpi(); if (commSpi == null) commSpi = new TcpCommunicationSpi(); c.setCommunicationSpi(commSpi); ignite = Ignition.start(c); }
/** * Executes example. * * @param args Command line arguments, none required. */ public static void main(String[] args) { try (Ignite ignite = Ignition.start("examples/config/portable/example-ignite-portable.xml")) { System.out.println(); System.out.println(">>> Portable objects cache put-get example started."); CacheConfiguration<Integer, Organization> cfg = new CacheConfiguration<>(); cfg.setCacheMode(CacheMode.PARTITIONED); cfg.setName(CACHE_NAME); cfg.setAtomicityMode(CacheAtomicityMode.ATOMIC); try (IgniteCache<Integer, Organization> cache = ignite.createCache(cfg)) { if (ignite.cluster().forDataNodes(cache.getName()).nodes().isEmpty()) { System.out.println(); System.out.println(">>> This example requires remote cache node nodes to be started."); System.out.println(">>> Please start at least 1 remote cache node."); System.out.println(">>> Refer to example's javadoc for details on configuration."); System.out.println(); return; } putGet(cache); putGetPortable(cache); putGetAll(cache); putGetAllPortable(cache); System.out.println(); } finally { // Delete cache with its content completely. ignite.destroyCache(CACHE_NAME); } } }
/** @throws Exception If failed. */ public void testIgnitionStartDefault() throws Exception { try (Ignite ignite = Ignition.start()) { log.info("Started1: " + ignite.name()); try { Ignition.start(); fail(); } catch (IgniteException expected) { // No-op. } } try (Ignite ignite = Ignition.start()) { log.info("Started2: " + ignite.name()); } }
/** * Creates cache. * * @param name Cache name. * @param atomicityMode Atomicity mode. * @return Cache configuration. */ private static IgniteCache createCache(String name, CacheAtomicityMode atomicityMode) { CacheConfiguration ccfg = new CacheConfiguration(name); ccfg.setAtomicityMode(atomicityMode); ccfg.setWriteSynchronizationMode(FULL_SYNC); return Ignition.ignite().getOrCreateCache(ccfg); }
/** Tests named grid */ public void testNamedGridGetOrStart() throws Exception { IgniteConfiguration cfg = getConfiguration("test"); try (Ignite ignite = Ignition.getOrStart(cfg)) { try { Ignition.start(cfg); fail("Expected exception after grid started"); } catch (IgniteException ignored) { // No-op. } Ignite ignite2 = Ignition.getOrStart(cfg); assertEquals("Must return same instance", ignite, ignite2); } assertTrue(G.allGrids().isEmpty()); }
/** * Executes example. * * @param args Command line arguments, none required. * @throws Exception If example execution failed. */ public static void main(String[] args) throws Exception { try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(); System.out.println(">>> Events API example started."); // Listen to events happening on local node. localListen(); // Listen to events happening on all cluster nodes. remoteListen(); // Wait for a while while callback is notified about remaining puts. Thread.sleep(1000); } }
/** * @param key Key. * @param cacheName Cache name. * @return Ignite instance which has primary cache for given key. */ protected Ignite primaryNode(Object key, String cacheName) { List<Ignite> allGrids = Ignition.allGrids(); assertFalse("There are no alive nodes.", F.isEmpty(allGrids)); Ignite ignite = allGrids.get(0); Affinity<Object> aff = ignite.affinity(cacheName); ClusterNode node = aff.mapKeyToNode(key); assertNotNull("There are no cache affinity nodes", node); return grid(node); }
/** * @param key Key. * @return Near cache for key. */ protected IgniteCache<Integer, Integer> nearCache(Integer key) { List<Ignite> allGrids = Ignition.allGrids(); assertFalse("There are no alive nodes.", F.isEmpty(allGrids)); Affinity<Integer> aff = allGrids.get(0).affinity(null); Collection<ClusterNode> nodes = aff.mapKeyToPrimaryAndBackups(key); for (Ignite ignite : allGrids) { if (!nodes.contains(ignite.cluster().localNode())) return ignite.cache(null); } fail(); return null; }
/** * Executes example. * * @param args Command line arguments, none required. * @throws IgniteException If example execution failed. */ public static void main(String[] args) throws IgniteException { ExamplesUtils.checkMinMemory(MIN_MEMORY); // To start ignite with desired configuration uncomment the appropriate line. try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(); System.out.println(">>> Cache store example started."); CacheConfiguration<Long, Person> cacheCfg = new CacheConfiguration<>(CACHE_NAME); // Set atomicity as transaction, since we are showing transactions in example. cacheCfg.setAtomicityMode(TRANSACTIONAL); // Configure JDBC store. cacheCfg.setCacheStoreFactory(FactoryBuilder.factoryOf(CacheJdbcPersonStore.class)); // Configure JDBC session listener. cacheCfg.setCacheStoreSessionListenerFactories( new Factory<CacheStoreSessionListener>() { @Override public CacheStoreSessionListener create() { CacheJdbcStoreSessionListener lsnr = new CacheJdbcStoreSessionListener(); lsnr.setDataSource(CacheJdbcPersonStore.DATA_SRC); return lsnr; } }); cacheCfg.setReadThrough(true); cacheCfg.setWriteThrough(true); try (IgniteCache<Long, Person> cache = ignite.getOrCreateCache(cacheCfg)) { // Make initial cache loading from persistent store. This is a // distributed operation and will call CacheStore.loadCache(...) // method on all nodes in topology. loadCache(cache); // Start transaction and execute several cache operations with // read/write-through to persistent store. executeTransaction(cache); } } }
/** * Executes transaction with read/write-through to persistent store. * * @param cache Cache to execute transaction on. */ private static void executeTransaction(IgniteCache<Long, Person> cache) { try (Transaction tx = Ignition.ignite().transactions().txStart()) { Person val = cache.get(id); System.out.println("Read value: " + val); val = cache.getAndPut(id, new Person(id, "Isaac", "Newton")); System.out.println("Overwrote old value: " + val); val = cache.get(id); System.out.println("Read value: " + val); tx.commit(); } System.out.println("Read value after commit: " + cache.get(id)); }
/** * Listen to events coming from all cluster nodes. * * @throws IgniteException If failed. */ private static void remoteListen() throws IgniteException { System.out.println(); System.out.println(">>> Remote event listener example."); // This optional local callback is called for each event notification // that passed remote predicate listener. IgniteBiPredicate<UUID, TaskEvent> locLsnr = (nodeId, evt) -> { // Remote filter only accepts tasks whose name being with "good-task" prefix. assert evt.taskName().startsWith("good-task"); System.out.println( "Received task event [evt=" + evt.name() + ", taskName=" + evt.taskName()); return true; // Return true to continue listening. }; // Remote filter which only accepts tasks whose name begins with "good-task" prefix. IgnitePredicate<TaskEvent> rmtLsnr = evt -> evt.taskName().startsWith("good-task"); Ignite ignite = Ignition.ignite(); // Register event listeners on all nodes to listen for task events. ignite.events().remoteListen(locLsnr, rmtLsnr, EVTS_TASK_EXECUTION); // Generate task events. for (int i = 0; i < 10; i++) { ignite .compute() .withName(i < 5 ? "good-task-" + i : "bad-task-" + i) .run( new IgniteRunnable() { // Auto-inject task session. @TaskSessionResource private ComputeTaskSession ses; @Override public void run() { System.out.println("Executing sample job for task: " + ses.getTaskName()); } }); } }
/** @throws Exception If failed. */ public void testLoadBean() throws Exception { final String path = "modules/spring/src/test/java/org/apache/ignite/internal/cache.xml"; GridTestUtils.assertThrows( log, new Callable<Object>() { @Override public Object call() throws Exception { Ignition.loadSpringBean(path, "wrongName"); return null; } }, IgniteException.class, null); CacheConfiguration cfg = Ignition.loadSpringBean(path, "cache-configuration"); assertEquals("TestDynamicCache", cfg.getName()); }
/** * Query all purchases made at a specific store. This query uses cross-cache joins between {@link * DimStore} objects stored in {@code 'replicated'} cache and {@link FactPurchase} objects stored * in {@code 'partitioned'} cache. * * @throws IgniteException If failed. */ private static void queryStorePurchases() { IgniteCache<Integer, FactPurchase> factCache = Ignition.ignite().cache(PARTITIONED_CACHE_NAME); // All purchases for store1. // ======================== // Create cross cache query to get all purchases made at store1. QueryCursor<Cache.Entry<Integer, FactPurchase>> storePurchases = factCache.query( new SqlQuery( FactPurchase.class, "from \"" + REPLICATED_CACHE_NAME + "\".DimStore, \"" + PARTITIONED_CACHE_NAME + "\".FactPurchase " + "where DimStore.id=FactPurchase.storeId and DimStore.name=?") .setArgs("Store1")); printQueryResults("All purchases made at store1:", storePurchases.getAll()); }
/** * @param key Key. * @param cacheName Cache name. * @return Ignite instance which has primary cache for given key. */ protected Ignite backupNode(Object key, String cacheName) { List<Ignite> allGrids = Ignition.allGrids(); assertFalse("There are no alive nodes.", F.isEmpty(allGrids)); Ignite ignite = allGrids.get(0); Affinity<Object> aff = ignite.affinity(cacheName); Collection<ClusterNode> nodes = aff.mapKeyToPrimaryAndBackups(key); assertTrue( "Expected more than one node for key [key=" + key + ", nodes=" + nodes + ']', nodes.size() > 1); Iterator<ClusterNode> it = nodes.iterator(); it.next(); // Skip primary. return grid(it.next()); }
/** * Executes example. * * @param args Command line arguments, none required. */ public static void main(String[] args) { try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { System.out.println(); System.out.println(">>> Binary objects task execution example started."); if (ignite.cluster().forRemotes().nodes().isEmpty()) { System.out.println(); System.out.println(">>> This example requires remote nodes to be started."); System.out.println(">>> Please start at least 1 remote node."); System.out.println(">>> Refer to example's javadoc for details on configuration."); System.out.println(); return; } // Generate employees to calculate average salary for. Collection<Employee> employees = employees(); System.out.println(); System.out.println(">>> Calculating average salary for employees:"); for (Employee employee : employees) System.out.println(">>> " + employee); // Convert collection of employees to collection of binary objects. // This allows to send objects across nodes without requiring to have // Employee class on classpath of these nodes. Collection<BinaryObject> binaries = ignite.binary().toBinary(employees); // Execute task and get average salary. Long avgSalary = ignite.compute(ignite.cluster().forRemotes()).execute(new ComputeClientTask(), binaries); System.out.println(); System.out.println(">>> Average salary for all employees: " + avgSalary); System.out.println(); } }
/** * Executes example. * * @param args Command line arguments, none required. * @throws IgniteException If example execution failed. */ public static void main(String[] args) throws IgniteException { // Start the node, run the example, and stop the node when finished. try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) { // We use a single session factory, but create a dedicated session // for each transaction or query. This way we ensure that L1 cache // is not used (L1 cache has per-session scope only). System.out.println(); System.out.println(">>> Hibernate L2 cache example started."); try ( // Create all required caches. IgniteCache c1 = createCache("org.hibernate.cache.spi.UpdateTimestampsCache", ATOMIC); IgniteCache c2 = createCache("org.hibernate.cache.internal.StandardQueryCache", ATOMIC); IgniteCache c3 = createCache("org.apache.ignite.examples.datagrid.hibernate.User", TRANSACTIONAL); IgniteCache c4 = createCache( "org.apache.ignite.examples.datagrid.hibernate.User.posts", TRANSACTIONAL); IgniteCache c5 = createCache("org.apache.ignite.examples.datagrid.hibernate.Post", TRANSACTIONAL)) { URL hibernateCfg = ExamplesUtils.url(HIBERNATE_CFG); SessionFactory sesFactory = createHibernateSessionFactory(hibernateCfg); System.out.println(); System.out.println(">>> Creating objects."); final long userId; Session ses = sesFactory.openSession(); try { Transaction tx = ses.beginTransaction(); User user = new User("jedi", "Luke", "Skywalker"); user.getPosts().add(new Post(user, "Let the Force be with you.")); ses.save(user); tx.commit(); // Create a user object, store it in DB, and save the database-generated // object ID. You may try adding more objects in a similar way. userId = user.getId(); } finally { ses.close(); } // Output L2 cache and Ignite cache stats. You may notice that // at this point the object is not yet stored in L2 cache, because // the read was not yet performed. printStats(sesFactory); System.out.println(); System.out.println(">>> Querying object by ID."); // Query user by ID several times. First time we get an L2 cache // miss, and the data is queried from DB, but it is then stored // in cache and successive queries hit the cache and return // immediately, no SQL query is made. for (int i = 0; i < 3; i++) { ses = sesFactory.openSession(); try { Transaction tx = ses.beginTransaction(); User user = (User) ses.get(User.class, userId); System.out.println("User: "******"\tPost: " + post); tx.commit(); } finally { ses.close(); } } // Output the stats. We should see 1 miss and 2 hits for // User and Collection object (stored separately in L2 cache). // The Post is loaded with the collection, so it won't imply // a miss. printStats(sesFactory); } } }
/** * Starts demo node. * * @param args Command line arguments, none required. * @throws IgniteException If example execution failed. */ public static void main(String[] args) throws IgniteException { logger.info(">>> Start demo server node..."); Ignition.start(ConfigProperties.getProperty(ConfigProperties.configFile)); }
/** * Starts demo node. * * @param args Command line arguments, none required. * @throws IgniteException If example execution failed. */ public static void main(String[] args) throws IgniteException { System.out.println(">>> Start demo node..."); Ignition.start("examples/config/example-ignite.xml"); }
/** @throws Exception If failed. */ public void testStartDefault() throws Exception { try (Ignite ignite = Ignition.start("config/default-config.xml")) { log.info("Started: " + ignite.name()); } }
/** @throws Exception If failed. */ public void testConfigInClassPath() throws Exception { try (Ignite ignite = Ignition.start("config/ignite-test-config.xml")) { assert "config-in-classpath".equals(ignite.name()); } }
/** {@inheritDoc} */ @Override public void stop() throws Exception { Ignition.stopAll(true); }
/** Start ignite node with cacheEmployee and populate it with data. */ public static boolean testDrive(AgentConfiguration acfg) { if (initLatch.compareAndSet(false, true)) { log.info("DEMO: Starting embedded nodes for demo..."); System.setProperty(IGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE, "1"); System.setProperty(IGNITE_JETTY_PORT, "60800"); System.setProperty(IGNITE_NO_ASCII, "true"); try { IgniteEx ignite = (IgniteEx) Ignition.start(igniteConfiguration(0, false)); final AtomicInteger cnt = new AtomicInteger(0); final ScheduledExecutorService execSrv = Executors.newSingleThreadScheduledExecutor(); execSrv.scheduleAtFixedRate( new Runnable() { @Override public void run() { int idx = cnt.incrementAndGet(); try { Ignition.start(igniteConfiguration(idx, idx == NODE_CNT)); } catch (Throwable e) { log.error("DEMO: Failed to start embedded node: " + e.getMessage()); } finally { if (idx == NODE_CNT) execSrv.shutdown(); } } }, 10, 10, TimeUnit.SECONDS); if (log.isDebugEnabled()) log.debug("DEMO: Started embedded nodes with indexed enabled caches..."); Collection<String> jettyAddrs = ignite.localNode().attribute(ATTR_REST_JETTY_ADDRS); String host = jettyAddrs == null ? null : jettyAddrs.iterator().next(); Integer port = ignite.localNode().attribute(ATTR_REST_JETTY_PORT); if (F.isEmpty(host) || port == null) { log.error("DEMO: Failed to start embedded node with rest!"); return false; } acfg.demoNodeUri(String.format("http://%s:%d", host, port)); log.info("DEMO: Embedded nodes for sql test-drive successfully started"); startLoad(ignite, 20); } catch (Exception e) { log.error("DEMO: Failed to start embedded node for sql test-drive!", e); return false; } } return true; }
/** {@inheritDoc} */ @Override public void run() { IgniteSet<ScheduledRunnable> set = Ignition.ignite(gridName).set(setName, null); set.add(scheduledRunnable); }