/*
 * 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();
    		}
    	}
	}
}
GigaSpaces.com - Legal Notice - 3rd Party Licenses - Site Map - API Docs - Forum - Downloads - Blog - White Papers - Contact Tech Writing - Gen. by Atlassian Confluence