org.apache.ignite.Ignition Java Examples

The following examples show how to use org.apache.ignite.Ignition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SqlQueryEmployees.java    From ignite-book-code-samples with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Example for SQL-based fields queries that return only required fields instead of whole key-value pairs.
 */
private static void sqlFieldsQueryWithJoin() {
    IgniteCache<?, ?> cache = Ignition.ignite().cache(EMPLOYEE_CACHE_NAME);

    // Create query to get names of all employees.
    SqlFieldsQuery qry = new SqlFieldsQuery(
        "select e.ename, d.dname " +
            "from Employee e, \"" + DEPARTMENT_CACHE_NAME + "\".Department d " +
            "where e.deptno = d.deptno");

    // Execute query to get collection of rows. In this particular
    // case each row will have one element with full name of an employees.
    Collection<List<?>> res = cache.query(qry).getAll();

    // Print persons' names and departments' names.
    logDecorated("==Names of all employees and departments they belong to (SQL join)==", res);
}
 
Example #2
Source File: ComputeClosureExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * 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 closure example started.");

        // Execute closure on all cluster nodes.
        Collection<Integer> res = ignite.compute().apply(
            (String word) -> {
                System.out.println();
                System.out.println(">>> Printing '" + word + "' on this node from ignite job.");

                // Return number of letters in the word.
                return word.length();
            },
            // Job parameters. Ignite will create as many jobs as there are parameters.
            Arrays.asList("Count characters using closure".split(" "))
        );

        int sum = res.stream().mapToInt(i -> i).sum();

        System.out.println();
        System.out.println(">>> Total number of characters in the phrase is '" + sum + "'.");
        System.out.println(">>> Check all nodes for output (this node is also part of the cluster).");
    }
}
 
Example #3
Source File: IgniteCfg.java    From SpringBoot-Ignite with MIT License 6 votes vote down vote up
/**
 * 初始化ignite节点信息
 * @return Ignite
 */
@Bean
public Ignite igniteInstance(){
    // 配置一个节点的Configuration
    IgniteConfiguration cfg = new IgniteConfiguration();

    // 设置该节点名称
    cfg.setIgniteInstanceName("springDataNode");

    // 启用Peer类加载器
    cfg.setPeerClassLoadingEnabled(true);

    // 创建一个Cache的配置,名称为PersonCache
    CacheConfiguration ccfg = new CacheConfiguration("PersonCache");

    // 设置这个Cache的键值对模型
    ccfg.setIndexedTypes(Long.class, Person.class);

    // 把这个Cache放入springDataNode这个Node中
    cfg.setCacheConfiguration(ccfg);

    // 启动这个节点
    return Ignition.start(cfg);
}
 
Example #4
Source File: FunctionalTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Tested API:
 * <ul>
 * <li>{@link ClientCache#getAndPut(Object, Object)}</li>
 * <li>{@link ClientCache#getAndRemove(Object)}</li>
 * <li>{@link ClientCache#getAndReplace(Object, Object)}</li>
 * <li>{@link ClientCache#putIfAbsent(Object, Object)}</li>
 * </ul>
 */
@Test
public void testAtomicPutGet() throws Exception {
    try (Ignite ignored = Ignition.start(Config.getServerConfiguration());
         IgniteClient client = Ignition.startClient(getClientConfiguration())
    ) {
        ClientCache<Integer, String> cache = client.createCache("testRemoveReplace");

        assertNull(cache.getAndPut(1, "1"));
        assertEquals("1", cache.getAndPut(1, "1.1"));

        assertEquals("1.1", cache.getAndRemove(1));
        assertNull(cache.getAndRemove(1));

        assertTrue(cache.putIfAbsent(1, "1"));
        assertFalse(cache.putIfAbsent(1, "1.1"));

        assertEquals("1", cache.getAndReplace(1, "1.1"));
        assertEquals("1.1", cache.getAndReplace(1, "1"));
        assertNull(cache.getAndReplace(2, "2"));
    }
}
 
Example #5
Source File: ConfigPropertiesTest.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testGridNameOverrideConfigBuilder() {
	IgniteConfiguration config = createConfig( CUSTOM_GRID_NAME );
	try ( Ignite ignite = Ignition.start( config ) ) {

		StandardServiceRegistry registry = registryBuilder()
				.applySetting( IgniteProperties.CONFIGURATION_CLASS_NAME, MyTinyGridConfigBuilder.class.getName() )
				.applySetting( IgniteProperties.IGNITE_INSTANCE_NAME, CUSTOM_GRID_NAME )
				.build();

		try ( OgmSessionFactory sessionFactory = createFactory( registry ) ) {
			assertThat( Ignition.allGrids() ).hasSize( 1 );
			assertThat( Ignition.allGrids().get( 0 ).name() ).isEqualTo( CUSTOM_GRID_NAME );
		}
	}
}
 
Example #6
Source File: LocalIgniteCluster.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** Private constructor: use {@link #start(int)} to create instances of {@link LocalIgniteCluster}. */
private LocalIgniteCluster(int initSize) {
    if (initSize < 1)
        throw new IllegalArgumentException("Cluster must have at least one node.");

    this.initSize = initSize;

    for (int i = 0; i < initSize; i++) {
        IgniteConfiguration cfg = getConfiguration(
            new NodeConfiguration(TcpDiscoverySpi.DFLT_PORT + i, ClientConnectorConfiguration.DFLT_PORT + i)
        );

        Ignite ignite = Ignition.start(cfg);

        srvs.add(ignite);
    }
}
 
Example #7
Source File: IgniteComputeCustomExecutorConfigurationSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testConfigurations() throws Exception {
    try {
        checkStartWithInvalidConfiguration(getConfiguration("node0")
            .setExecutorConfiguration(new ExecutorConfiguration()));

        checkStartWithInvalidConfiguration(getConfiguration("node0")
            .setExecutorConfiguration(new ExecutorConfiguration("")));

        checkStartWithInvalidConfiguration(getConfiguration("node0")
            .setExecutorConfiguration(new ExecutorConfiguration("exec").setSize(-1)));

        checkStartWithInvalidConfiguration(getConfiguration("node0")
            .setExecutorConfiguration(new ExecutorConfiguration("exec").setSize(0)));
    }
    finally {
        Ignition.stopAll(true);
    }
}
 
Example #8
Source File: IgniteExpiryExample.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {
    // Start Ignite cluster
    Ignite ignite = Ignition.start("default-config.xml");

    // get or create cache
    IgniteCache<Integer, Person> cache =  ignite.getOrCreateCache("testCache");
    Person p1 = new Person(37, "Shamim");
    Person p2 = new Person(2, "Mishel");
    Person p3 = new Person(55, "scott");
    Person p4 = new Person(5, "Tiger");

    cache.put(1, p1);
    cache.put(2, p2);
    cache.put(3, p3);
    cache.put(4, p4);

    System.out.println("Enter crtl-x to quite the application!!!");

}
 
Example #9
Source File: IgniteSetExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * 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(">>> Ignite set example started.");

        // Make set name.
        String setName = UUID.randomUUID().toString();

        set = initializeSet(ignite, setName);

        writeToSet(ignite);

        clearAndRemoveSet();
    }

    System.out.println("Ignite set example finished.");
}
 
Example #10
Source File: SqlQueriesExample.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Example for SQL-based fields queries that return only required
 * fields instead of whole key-value pairs.
 */
private static void sqlFieldsQueryWithJoin() {
    IgniteCache<AffinityKey<Long>, Person> cache = Ignition.ignite().cache(COLLOCATED_PERSON_CACHE);

    // Execute query to get names of all employees.
    String sql =
        "select concat(firstName, ' ', lastName), org.name " +
        "from Person, \"" + ORG_CACHE + "\".Organization as org " +
        "where Person.orgId = org.id";

    QueryCursor<List<?>> cursor = cache.query(new SqlFieldsQuery(sql));

    // In this particular case each row will have one element with full name of an employees.
    List<List<?>> res = cursor.getAll();

    // Print persons' names and organizations' names.
    print("Names of all employees and organizations they belong to: ", res);
}
 
Example #11
Source File: HelloIgniteSpring.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {
    // Start Ignite cluster
    Ignite ignite = Ignition.start("default-config.xml");

    // get or create cache
    IgniteCache<Integer, Person> cache =  ignite.getOrCreateCache("testCache");
    Person p1 = new Person(37, "Shamim");
    Person p2 = new Person(2, "Mishel");
    Person p3 = new Person(55, "scott");
    Person p4 = new Person(5, "Tiger");

    cache.put(1, p1);
    cache.put(2, p2);
    cache.put(3, p3);
    cache.put(4, p4);

    System.out.println("Enter crtl-x to quite the application!!!");

}
 
Example #12
Source File: Evaluator.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate binary classifier by default metrics (see package classification).
 *
 * @param dataCache    The given cache.
 * @param filter       The filter.
 * @param mdl          The model.
 * @param preprocessor The preprocessor.
 * @param <K>          The type of cache entry key.
 * @param <V>          The type of cache entry value.
 * @return Computed metrics.
 */
public static <K, V> EvaluationResult evaluateBinaryClassification(IgniteCache<K, V> dataCache,
    // TODO: IGNITE-12156
    IgniteBiPredicate<K, V> filter,
    IgniteModel<Vector, Double> mdl,
    Preprocessor<K, V> preprocessor) {

    Metric[] metrics = merge(
        MetricName.ACCURACY, MetricName.PRECISION, MetricName.RECALL, MetricName.F_MEASURE,
        MetricName.BALANCED_ACCURACY, MetricName.FALL_OUT, MetricName.FDR, MetricName.MISS_RATE,
        MetricName.NPV, MetricName.SPECIFICITY, MetricName.TRUE_POSITIVE, MetricName.FALSE_POSITIVE,
        MetricName.TRUE_NEGATIVE, MetricName.FALSE_NEGATIVE
    );
    return evaluate(new CacheBasedDatasetBuilder<>(Ignition.ignite(), dataCache, filter), mdl, preprocessor,
        metrics);
}
 
Example #13
Source File: TcpDiscoveryIpFinderCleanerTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the node stops gracefully even if {@link TcpDiscoveryIpFinder} ignores {@link InterruptedException}.
 *
 * @throws Exception If failed.
 */
@Test
public void testNodeStops() throws Exception {
    CustomIpFinder ipFinder = new CustomIpFinder(true);

    Ignite ignite = Ignition.start(getConfiguration(ipFinder));

    try {
        if (!ipFinder.suspend().await(IP_FINDER_CLEAN_FREQ * 5, TimeUnit.MILLISECONDS))
            fail("Failed to suspend IP finder.");

        if (!stopNodeAsync(ignite).await(NODE_STOPPING_TIMEOUT, TimeUnit.MILLISECONDS))
            fail("Node was not stopped.");
    }
    finally {
        ipFinder.interruptCleanerThread();
    }
}
 
Example #14
Source File: CacheJdbcPojoStoreFactorySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Ignore("https://issues.apache.org/jira/browse/IGNITE-10723")
@Test
public void testIncorrectBeanConfiguration() throws Exception {
    GridTestUtils.assertThrowsAnyCause(log, new Callable<Object>() {
        @Override public Object call() throws Exception {
            try (Ignite ignored = Ignition.start("modules/spring/src/test/config/pojo-incorrect-store-cache.xml")) {
                // No-op.
            }
            return null;
        }
    }, IgniteCheckedException.class, "Spring bean with provided name doesn't exist");
}
 
Example #15
Source File: CacheHibernateStoreFactorySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testIncorrectBeanConfiguration() throws Exception {
    GridTestUtils.assertThrows(log, new Callable<Object>() {
        @Override public Object call() throws Exception {
            try (Ignite ignite =
                Ignition.start(MODULE_PATH + "/src/test/config/factory-incorrect-store-cache.xml")) {
                ignite.cache(CACHE_NAME).getConfiguration(CacheConfiguration.class).
                        getCacheStoreFactory().create();
            }
            return null;
        }
    }, IgniteException.class, "Failed to load bean in application context");
}
 
Example #16
Source File: CacheHibernateStoreFactorySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testIncorrectBeanConfiguration() {
    GridTestUtils.assertThrows(log, new Callable<Object>() {
        @Override public Object call() throws Exception {
            String path = MODULE_PATH + "/src/test/config/factory-incorrect-store-cache.xml";
            try (Ignite ignite = Ignition.start(path)) {
                ignite.cache(CACHE_NAME).getConfiguration(CacheConfiguration.class).getCacheStoreFactory().create();
            }
            return null;
        }
    }, IgniteException.class, "Failed to load bean in application context");
}
 
Example #17
Source File: ServiceManagements.java    From ignite-book-code-samples with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException{
    try (Ignite ignite = Ignition.start(CommonConstants.CLIENT_CONFIG)) {

        for(ServiceDescriptor serviceDescriptor : ignite.services().serviceDescriptors()){
            System.out.println("Service Name: " + serviceDescriptor.name());
            System.out.println("MaxPerNode count: " + serviceDescriptor.maxPerNodeCount());
            System.out.println("Total count: " + serviceDescriptor.totalCount());
            System.out.println("Service class Name: " + serviceDescriptor.serviceClass());
            System.out.println("Origin Node ID: " + serviceDescriptor.originNodeId());

        }

    }
}
 
Example #18
Source File: SqlQueryEmployees.java    From ignite-book-code-samples with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Example for SQL queries based on all employees working for a specific department.
 */
private static void sqlQueryWithJoin() {
    IgniteCache<EmployeeKey, Employee> cache = Ignition.ignite().cache(EMPLOYEE_CACHE_NAME);

    // Create query which joins on 2 types to select people for a specific department.
    SqlQuery<EmployeeKey, Employee> qry = new SqlQuery<>(Employee.class,
        "from Employee, \"" + DEPARTMENT_CACHE_NAME + "\".Department " +
            "where Employee.deptno = Department.deptno " +
            "and lower(Department.dname) = lower(?)");

    // Execute queries for find employees for different departments.
    logDecorated("==Following department 'Accounting' have employees (SQL join)==", cache.query(qry.setArgs("Accounting")).getAll());
    logDecorated("==Following department 'Sales' have employees (SQL join)==", cache.query(qry.setArgs("Sales")).getAll());
}
 
Example #19
Source File: PlatformAbstractBootstrap.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void init(long dataPtr) {
    final PlatformInputStream input = new PlatformExternalMemory(null, dataPtr).input();

    Ignition.setClientMode(input.readBoolean());

    processInput(input);
}
 
Example #20
Source File: IgniteTestHelper.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void dropSchemaAndDatabase(SessionFactory sessionFactory) {
	if ( Ignition.allGrids().size() > 1 ) { // some tests doesn't stop DatastareProvider
		String currentGridName = getProvider( sessionFactory ).getGridName();
		for ( Ignite grid : Ignition.allGrids() ) {
			if ( !Objects.equals( currentGridName, grid.name() ) ) {
				grid.close();
			}
		}
	}
}
 
Example #21
Source File: SecurityTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Create user.
 */
private static void createUser(String user, String pwd) throws Exception {
    try (IgniteClient client = Ignition.startClient(new ClientConfiguration()
        .setAddresses(Config.SERVER)
        .setUserName("ignite")
        .setUserPassword("ignite")
    )) {
        client.query(
            new SqlFieldsQuery(String.format("CREATE USER \"%s\" WITH PASSWORD '%s'", user, pwd))
        ).getAll();
    }
}
 
Example #22
Source File: IgnitionEx.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Restarts <b>all</b> started grids. If {@code cancel} flag is set to {@code true} then
 * all jobs currently executing on the local node will be interrupted.
 * If {@code wait} parameter is set to {@code true} then grid will wait for all
 * tasks to be finished.
 * <p>
 * <b>Note:</b> it is usually safer and more appropriate to stop grid instances individually
 * instead of blanket operation. In most cases, the party that started the grid instance
 * should be responsible for stopping it.
 * <p>
 * Note also that restarting functionality only works with the tools that specifically
 * support Ignite's protocol for restarting. Currently only standard <tt>ignite.{sh|bat}</tt>
 * scripts support restarting of JVM Ignite's process.
 *
 * @param cancel If {@code true} then all jobs currently executing on
 *      all grids will be cancelled by calling {@link ComputeJob#cancel()}
 *      method. Note that just like with {@link Thread#interrupt()}, it is
 *      up to the actual job to exit from execution.
 * @see Ignition#RESTART_EXIT_CODE
 */
public static void restart(boolean cancel) {
    String file = System.getProperty(IGNITE_SUCCESS_FILE);

    if (file == null)
        U.warn(null, "Cannot restart node when restart not enabled.");
    else {
        try {
            new File(file).createNewFile();
        }
        catch (IOException e) {
            U.error(null, "Failed to create restart marker file (restart aborted): " + e.getMessage());

            return;
        }

        U.log(null, "Restarting node. Will exit (" + Ignition.RESTART_EXIT_CODE + ").");

        // Set the exit code so that shell process can recognize it and loop
        // the start up sequence again.
        System.setProperty(IGNITE_RESTART_CODE, Integer.toString(Ignition.RESTART_EXIT_CODE));

        stopAll(cancel);

        // This basically leaves loaders hang - we accept it.
        System.exit(Ignition.RESTART_EXIT_CODE);
    }
}
 
Example #23
Source File: ImputingExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Run example.
 */
public static void main(String[] args) throws Exception {
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        System.out.println(">>> Imputing example started.");

        IgniteCache<Integer, Vector> data = null;
        try {
            data = createCache(ignite);

            Vectorizer<Integer, Vector, Integer, Double> vectorizer = new DummyVectorizer<>(1, 2);

            // Defines second preprocessor that imputing features.
            Preprocessor<Integer, Vector> preprocessor = new ImputerTrainer<Integer, Vector>()
                .fit(ignite, data, vectorizer);

            // Creates a cache based simple dataset containing features and providing standard dataset API.
            try (SimpleDataset<?> dataset = DatasetFactory.createSimpleDataset(ignite, data, preprocessor)) {
                new DatasetHelper(dataset).describe();
            }

            System.out.println(">>> Imputing example completed.");
        }
        finally {
            data.destroy();
        }
    }
    finally {
        System.out.flush();
    }
}
 
Example #24
Source File: ComputeCallableExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * 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 callable example started.");

        Collection<IgniteCallable<Integer>> calls = new ArrayList<>();

        // Iterate through all words in the sentence and create callable jobs.
        for (String word : "Count characters using callable".split(" ")) {
            calls.add(() -> {
                System.out.println();
                System.out.println(">>> Printing '" + word + "' on this node from ignite job.");

                return word.length();
            });
        }

        // Execute collection of callables on the ignite.
        Collection<Integer> res = ignite.compute().call(calls);

        int sum = res.stream().mapToInt(i -> i).sum();

        System.out.println();
        System.out.println(">>> Total number of characters in the phrase is '" + sum + "'.");
        System.out.println(">>> Check all nodes for output (this node is also part of the cluster).");
    }
}
 
Example #25
Source File: CacheConfigurationP2PTestServer.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param args Arguments.
 * @throws Exception If failed.
 */
public static void main(String[] args) throws Exception {
    System.out.println("Starting test server node.");

    IgniteConfiguration cfg = CacheConfigurationP2PTest.createConfiguration();

    try (Ignite ignite = Ignition.start(cfg)) {
        System.out.println(CacheConfigurationP2PTest.NODE_START_MSG);

        U.sleep(Long.MAX_VALUE);
    }
}
 
Example #26
Source File: WalModeChangeCommonAbstractSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Waits for the topology version to be not less than one registered on source node.
 *
 * @param src Source node.
 * @throws IgniteCheckedException If failed to wait on affinity ready future.
 */
protected void alignCacheTopologyVersion(Ignite src) throws IgniteCheckedException {
    AffinityTopologyVersion topVer = ((IgniteEx)src).context().cache().context().exchange().readyAffinityVersion();

    info("Will wait for topology version on all nodes: " + topVer);

    for (Ignite ignite : Ignition.allGrids()) {
        IgniteInternalFuture<?> ready = ((IgniteEx)ignite).context().cache().context().exchange()
            .affinityReadyFuture(topVer);

        if (ready != null)
            ready.get();
    }
}
 
Example #27
Source File: AsyncComputation.java    From ignite-book-code-samples with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    String sample1 = TestDataGenerator.getSample1();
    byte[] vaidateSchema = TestDataGenerator.getValidateSchema();
    String validateScript = TestDataGenerator.getValidateScript();

    try (Ignite ignite = Ignition.start(CommonConstants.CLIENT_CONFIG)) {
        IgniteCompute compute = ignite.compute().withAsync();

        compute.call(() -> {
            boolean validateXsdResult = XsdValidator.validate(sample1, vaidateSchema);
            boolean validateByJs = JSEvaluate.evaluateJs(sample1, validateScript);

            System.out.println("validateXsdResult=" + validateXsdResult);
            System.out.println("validateByJs=" + validateByJs);

            return validateXsdResult && validateByJs;
        });

        compute.future().listen((result) -> {
            boolean res = (boolean) result.get();
            System.out.println("result=" + res);
        });


        //System.out.println("Presse ENTER to exit!");
        //System.in.read();
    }
}
 
Example #28
Source File: ComputeAsyncExample.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * 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 asynchronous example started.");

        // Enable asynchronous mode.
        IgniteCompute compute = ignite.compute().withAsync();

        Collection<IgniteFuture<?>> futs = new ArrayList<>();

        // Iterate through all words in the sentence and create runnable jobs.
        for (final String word : "Print words using runnable".split(" ")) {
            // Execute runnable on some node.
            compute.run(() -> {
                System.out.println();
                System.out.println(">>> Printing '" + word + "' on this node from ignite job.");
            });

            futs.add(compute.future());
        }

        // Wait for completion of all futures.
        futs.forEach(IgniteFuture::get);

        System.out.println();
        System.out.println(">>> Finished printing words using runnable execution.");
        System.out.println(">>> Check all nodes for output (this node is also part of the cluster).");
    }
}
 
Example #29
Source File: MessagingRemoteSecurityContextCheckTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
private IgniteBiPredicate<UUID, ?> listener() {
    return (uuid, o) -> {
        VERIFIER.register(OPERATION_CHECK);

        compute(Ignition.localIgnite(), endpointIds()).broadcast(() -> VERIFIER.register(OPERATION_ENDPOINT));

        SYNCHRONIZED_SET.add(o);

        return true;
    };
}
 
Example #30
Source File: VisorNodeStopTask.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override protected Void run(Void arg) {
    new Thread(new Runnable() {
        @Override public void run() {
            Ignition.kill(true);
        }
    }, "grid-stopper").start();

    return null;
}