Query Using GSIterator

You can use the GSIterator which provides the ability to exhaustively read through all of the Objects from a Space that match one or more query templates.
Generally, an iterator should be used because returning all the Objects in one result sent back to the call would consume too many resources in the client or introduce too much latency before the first Object could be processed. The iterator constructs a match set (a collection of Object instances) that incrementally returns the necessary Objects.
For more information about the GSIterator refer to [JavaSpaces Iterator] and IteratorBuilder JavaDoc.

The following code replaces the validator application notify container and its counter bean with a service bean, that uses a GSIterator to iterate on the space and read New and Insecure orderEvent objects using a matching query.
The risky orders counter is increased if an account for the order's user allowing the risk involved with the order is not found (the account riskAllowed attribute is compared to the orderEvent riskInvolved attribute), (Assuming every order belongs to a user that has an account):

IteratorCounter Bean

/*
 * Copyright 2008 GigaSpaces Technologies LTD. All rights reserved.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. GIGASPACES WILL NOT 
 * BE LIABLE FOR ANY DAMAGE OR LOSS IN CONNECTION WITH THE SOFTWARE.
 */

package com.gigaspaces.examples.tutorials.queries.counter;

import java.util.concurrent.atomic.AtomicInteger;

import org.openspaces.core.GigaSpace;
import org.openspaces.core.IteratorBuilder;
import org.openspaces.core.context.GigaSpaceContext;

import org.springframework.beans.factory.InitializingBean;

import com.gigaspaces.examples.tutorials.queries.common.Account;
import com.gigaspaces.examples.tutorials.queries.common.OrderEvent;

import com.j_spaces.core.client.GSIterator;
import com.j_spaces.core.client.SQLQuery;

/**
 * Simple bean used to read and display the "Insecure" orderEvent objects.
 * Shows use of GSIterator.
 */
public class RiskyOrderEventCounter implements InitializingBean{
	
	private AtomicInteger riskyOrderEventCounter = new AtomicInteger(0);
	
	@GigaSpaceContext(name = "gigaSpace")
    private GigaSpace gigaSpace;
	
	public void setGigaSpace(GigaSpace gigaSpace) {
		this.gigaSpace = gigaSpace;
	}
	
	/**
	 * The first method to run upon bean Initialization when implementing InitializingBean.
	 * Runs the init() method 
	 */
	public void afterPropertiesSet() throws Exception {
		init();	
	}

	/**
	 * Starts a new thread running the OrderEventIteratorTask. 
	 */
	public void init(){
		Thread thread = new Thread(new OrderEventIteratorTask());
		thread.start();
	}
	
    /**
     * Iterates through all the orderEvents matching the specified templates.
     * Counts every orderEvent read, that has an associated account (same user name as the orderEvent) 
     * with a satisfying risk allowed.
     */
	public class OrderEventIteratorTask implements Runnable {
	    
		// Create a query for "New" and "Insecure" orderEvent objects.
		SQLQuery<OrderEvent> queryInsecureOrders = new SQLQuery<OrderEvent>(OrderEvent.class,"status='"+OrderEvent.STATUS_NEW+"' and type='"+OrderEvent.TYPE_INSECURE+"'");
		
		// Create and configure an iteratorBuilder to build iterators for the space with the specified templates.
		IteratorBuilder iteratorBuilder = new IteratorBuilder(gigaSpace)
											.addTemplate(queryInsecureOrders)
											.bufferSize(100) // Limit of the number of objects to store for each iteration.
											.withHistory(); // Indicates that this iterator will be first pre-filled with matching objects,
															// otherwise it will start iterating only on newly arriving objects to the space.
	    
	    public void run()
	    {
	    	try
	    	{
	    		System.out.println("Counter creats iterator over the space insecure orders:");
	    		// Build the iterator using the previously configured iteratorBuilder.
	    		GSIterator gsIterator = iteratorBuilder.iterate();
	    		
	    		System.out.println("Counter iterator thread reading messages");
	    		
	    		OrderEvent insecureOrderEvent;
	    		
	    		// Create the query for an account object, each ? place-holder will be replaced inside the following loop using the setParameters method.
	    		SQLQuery<Account> accountQuery = new SQLQuery<Account>(Account.class,"firstName = ? and lastName = ? and riskAllowed > ?");
	    		
	    		while (true)
	    		{
	    			while (gsIterator.hasNext())
	    			{
	    				insecureOrderEvent = (OrderEvent)gsIterator.next();
	    				System.out.println("\nCounter examines order: "+insecureOrderEvent);
	    				// Updating the query parameters, the query will actually equal:
	    				// firstName=(accountQuery.firstName value) and lastName=(accountQuery.lastName value) and amount>(accountQuery.amount value) 
	    		        accountQuery.setParameters(insecureOrderEvent.getFirstName(), /* account user first name*/
	    		        							insecureOrderEvent.getLastName(), /* account user last name*/
	    		        							insecureOrderEvent.getRiskInvolved()); /* account amount*/
	    		        
	    		        // Read an account matching the query
	    		        Account account = (Account)gigaSpace.read((Object)accountQuery);
	    				
	    		        // Set the order status according to the query result
	    		        if (account != null)
	    				{
	    		        	System.out.println("Counter - examined order's risk is higher then allowed.");
	    		        	riskyOrderEventCounter.incrementAndGet();
	    				}
	    		        else
	    		        {
	    		        	System.out.println("Counter - examined order's risk is allowed.");
	    		        }
	    		        	System.out.println("Counter - total of ["+riskyOrderEventCounter+"] insecure risky orders (with risk higher then allowed) counted.");
	    			}
	    		}
    		}
    		catch(Exception e)
    		{
    			e.printStackTrace();
    		}
    	}
	}
}

Wiring the bean inside the pu.xml (Instead of the notify container)

<!-- The insecureRiskyOrderEventIteratorCounter bean -->
    <bean id="insecureRiskyOrderEventIteratorCounter" class="com.gigaspaces.examples.tutorials.queries.validator.InsecureRiskyOrderEventIteratorCounter"/>

Adding the bean to the codebased validator (Instead of the notify container)

InsecureRiskyOrderEventIteratorCounter insecureRiskyOrderEventIteratorCounter = new InsecureRiskyOrderEventIteratorCounter();
insecureRiskyOrderEventIteratorCounter.setGigaSpace(gigaSpace);
insecureRiskyOrderEventIteratorCounter.init();
GigaSpaces.com - Legal Notice - 3rd Party Licenses - Site Map - API Docs - Forum - Downloads - Blog - White Papers - Contact Tech Writing - Gen. by Atlassian Confluence