All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nhindirect.policy.impl.machine.StackMachine Maven / Gradle / Ivy

/* 
Copyright (c) 2010, NHIN Direct Project
All rights reserved.

Authors:
   Greg Meyer      [email protected]
 
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer 
in the documentation and/or other materials provided with the distribution.  Neither the name of the The NHIN Direct Project (nhindirect.org). 
nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS 
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
THE POSSIBILITY OF SUCH DAMAGE.
*/

package org.nhindirect.policy.impl.machine;

import java.lang.reflect.Constructor;
import java.util.Stack;
import java.util.Vector;

import org.nhindirect.policy.ExecutionEngine;
import org.nhindirect.policy.Opcode;
import org.nhindirect.policy.PolicyOperator;
import org.nhindirect.policy.PolicyOperatorExecutor;
import org.nhindirect.policy.PolicyProcessException;
import org.nhindirect.policy.PolicyValue;

/**
 * Implementation of the {@link ExecutionEngine} interface that is implemented using a simple stack machine.  This engine
 * takes {@link org.nhindirect.policy.Opcode Opcodes} generated by the {@link StackMachineCompiler}.
 * @author Greg Meyer
 * @since 1.0
 */
public class StackMachine implements ExecutionEngine
{	
	/**
	 * Default constructor.
	 */
	public StackMachine()
	{

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Boolean evaluate(Vector opcodes) throws PolicyProcessException
	{
		final Stack> machineStack = new Stack>();
		
		Boolean retVal;
		
		for (Opcode opcode : opcodes)
		{
			// the vector for this machine type should only use StackMachineEntry codes
			final StackMachineEntry entry = StackMachineEntry.class.cast(opcode);
			
			switch(entry.getEntryType())
			{
			    case VALUE:
				{
					machineStack.push(entry.getValue());
					break;
				}
			    case OPERATOR:
				{
					PolicyOperatorExecutor executor = null;
					switch(entry.getOperator().getParamsType())
					{
						case BINARY:	
						{	
							if (machineStack.size() < 2)
								throw new IllegalStateException("Stack machine must have at least two pushed operands for " + entry.getOperator().getOperatorText()
										+ " operator");
							
							executor = 
									createOperatorExecutor(entry.getOperator(), machineStack.pop(), machineStack.pop());
								
							break;
						}					
						case UNARY:
						{
							if (machineStack.size() < 1)
								throw new IllegalStateException("Stack machine must have at least one pushed operand for " + entry.getOperator().getOperatorText()
										+ " operator");
							
							executor = 
									createOperatorExecutor(entry.getOperator(), machineStack.pop());
							
							break;
						}
					}
					
					machineStack.push(executor.execute());
					
					break;
				}
				
			}
		}
		
		if (machineStack.isEmpty() || machineStack.size() > 1)
			throw new IllegalStateException("Stack machine is either empty or has remaining parameters to be processed." +
					"\r\n\tFinal stack size: " + machineStack.size());
		
		final PolicyValue finalValue = machineStack.pop();
		try
		{
			retVal = Boolean.class.cast(finalValue.getPolicyValue());
		}
		catch (ClassCastException e)
		{
			throw new IllegalStateException("Final machine value must be a boolean litteral" +
					"\r\n\tFinal value type: " + finalValue.getPolicyValue().getClass() 
					+ "\r\n\tFinal value value:" + finalValue.getPolicyValue().toString(), e);			
		}
		
		return retVal;
	}
	
	/**
	 * Creates an executor instance for an operator and a set of operands.
	 * @param operator The operation that will be executed.
	 * @param values The operands used by the executor.
	 * @return An instance of a {@link PolicyOperatorExecutor} that will evaluate the operation.
	 * @throws PolicyProcessException
	 */
	protected PolicyOperatorExecutor createOperatorExecutor(PolicyOperator operator, PolicyValue... values) throws PolicyProcessException
	{
		PolicyOperatorExecutor executor = null;
		Constructor constructor = null;
		
		switch(operator.getParamsType())
		{
			case BINARY:
			{
				try
				{
					constructor =
							operator.getExecutorClass().getConstructor(PolicyValue.class, PolicyValue.class, PolicyOperator.class);
					
				}
				///CLOVER:OFF
				catch (Exception e)
				{
					throw new PolicyProcessException("Failed to get constructor for operator executor.", e);
				}
				///CLOVER:ON
				break;
			}					
			case UNARY:
			{
				try
				{
					constructor =
							operator.getExecutorClass().getConstructor(PolicyValue.class, PolicyOperator.class);
				}
				///CLOVER:OFF
				catch (Exception e)
				{
					throw new PolicyProcessException("Failed to get constructor for operator executor.", e);
				}
				///CLOVER:ON
				break;
			}	
		}
		
		try
		{
			if (values.length == 1)
				executor =  PolicyOperatorExecutor.class.cast(constructor.newInstance(values[0], operator));
			else
				executor =  PolicyOperatorExecutor.class.cast(constructor.newInstance(values[0], values[1], operator));
		}
		///CLOVER:OFF
		catch (Exception e)
		{
			throw new PolicyProcessException("Failed to create operator executor.", e);
		}
		///CLOVER:ON
		
		return executor;
	}
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy