Package org.apache.imperius.spl.parser.expression.primary

Source Code of org.apache.imperius.spl.parser.expression.primary.CollectOperation

/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License. 
*/
//

/**
* @author Prashant Baliga <prabalig@in.ibm.com>
*
*/



package org.apache.imperius.spl.parser.expression.primary;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.imperius.spl.core.DataCollector;
import org.apache.imperius.spl.core.Expression;
import org.apache.imperius.spl.core.TypeConstants;
import org.apache.imperius.spl.core.TypeInfo;
import org.apache.imperius.spl.parser.compiler.symboltable.SPLSymbolTable;
import org.apache.imperius.spl.parser.compiler.symboltable.Symbol;
import org.apache.imperius.spl.parser.exceptions.IllegalExpressionTypeException;
import org.apache.imperius.spl.parser.exceptions.MissingParameterException;
import org.apache.imperius.spl.parser.exceptions.NonExistentSymbolException;
import org.apache.imperius.spl.parser.exceptions.SPLException;
import org.apache.imperius.spl.parser.expressions.ReferenceExpression;
import org.apache.imperius.spl.parser.util.DataCollectorFactory;
import org.apache.imperius.spl.parser.util.TypeInfoImpl;
import org.apache.imperius.util.Messages;
import org.apache.imperius.util.SPLLogger;

public class CollectOperation implements ReferenceExpression {

  private static final int COLLECT_FLAVOUR1 = 0;
  private static final int COLLECT_FLAVOUR2 = 1;
  private static final int INVALID_TYPE = 2;
  private static Logger logger = SPLLogger.getSPLLogger().getLogger();
  private static final String sourceClass="CollectOperation";


  private int collectType;
  private ArrayList paramList;
  private SPLSymbolTable symTab;
  private String returnClassName;
  private PostCollectExpression postCollectOperation;
  private TypeInfo _dataType=new TypeInfoImpl();
//  private boolean isArray;
  private boolean noPostCollectOperation;
  private Expression referenceExpression;
  private String associationName;
  private String sourceRole;
  private String targetRole;
  private String targetClassName;
  private String targetClassPropertyName;
  private Expression expressionForTarget;



  //  #(c:COLLECT_OP #(COLLECT_CALL paramList = exprList[collectSymbolTable]) (postExpr = methodPropArrForCollect[symTab,collectSymbolTable])?  ) 
  public CollectOperation(ArrayList pList, Expression postCollect, SPLSymbolTable sTab) throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "CollectOperation");

    this.paramList = pList;
   
    // if no of params is 6 then flavour1 collect(refExp, associationname, srcRole, targetRole, targetClass, targetExp)
    if(pList.size()  == 6)
    { 
      collectType = COLLECT_FLAVOUR1;
   
    else if(pList.size()  == 7)
    {
      // if no of params is 7 then flavour2 collect(refExp, associationname, srcRole, targetRole, targetClass, <target class param>, targetExp)
      collectType = COLLECT_FLAVOUR2;
   
    else
    {
      logger.severe(Thread.currentThread().getName()+" "+"No of parameters for collect has to be 6 or 7");
      throw new InvalidParameterException(Messages
          .getString("SPL_EXPRESSION_VALIDATION_FAIL_MSG")
          + sourceClass);
    }

    if(postCollect != null) //  expression following collect e.g. collect(....)[1].param
   
      postCollectOperation = (PostCollectExpression)postCollect;
      noPostCollectOperation = false;
    }
    else // no expression following collect e.g. collect(...) implies return is an array of targetclass instances (flavour 1) or param values (flavour 2)
    {
      _dataType.setIsArray(true);
      noPostCollectOperation = true;
    }

    this.symTab = sTab;

    // validate the expression
    if (!validate())
    {
      logger.severe(Thread.currentThread().getName()+" "+"validation error:");
      throw new SPLException("validation error:");
    }

    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "CollectOperation");
  }

  public boolean validate() throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "validate");

    boolean result = false;
    if(collectType != INVALID_TYPE)
    {
      if(collectType == COLLECT_FLAVOUR1)
      {
        result = validateCollectFlavour1();
      }
      else
      {
        result = validateCollectFlavour2();
      }
    }
    else
    {
      logger.severe(Thread.currentThread().getName()+" "+"Missing parameters");
      throw new MissingParameterException(Messages
          .getString("SPL_MISSING_PARAMETERS_EXCEPTION_MSG"));
    }
    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "validate");
    return result;


  }

  // The first 4 parameters are common to both Collect flavours
  private boolean validateCommonParameters() throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "validateCommonParameters");
    //System.out.println("validateCommonParameters ");

    String sourceClassValidate = null;
    if(symTab.getParentSymbolTable() != null) // the symbol table which is the parent of the collect symbol table
      sourceClassValidate = (String)symTab.getParentSymbolTable().getAnchorData().getAnchorClassList().get(0);

    //System.out.println("sourceClassValidate "+sourceClassValidate);
    Expression refExp = (Expression)paramList.get(0);
    if(refExp.getType().getType() != TypeConstants.referenceType) // param 0 is the source class
    {
      logger.severe(Thread.currentThread().getName()+" "+"First param to collect needs to be a reference expression");
      throw new IllegalExpressionTypeException(
          "first "
              + Messages
                  .getString("SPL_COLLECT_OPERATION_EXP_EXCEPTION1_MSG")
              + sourceClass);
    }
    if(refExp instanceof ReferenceExpression)
    {
      sourceClassValidate = ((ReferenceExpression)refExp).getReferenceTypeName();
      referenceExpression = refExp;
      ReferenceExpression ref=(ReferenceExpression)refExp;
      //System.out.println(" class of refExp is "+ref.getReferenceTypeName());

      //refExp.
    }
    else{
      referenceExpression = refExp;
    }

    Expression assocExp = (Expression)paramList.get(1); // param 1 is the assoc Name
    if(assocExp.getType().getType() != TypeConstants.stringType)
    {
      logger.severe(Thread.currentThread().getName()+" "+"2nd param to collect needs to be a string expression");

      throw new IllegalExpressionTypeException(
          "second "
              + Messages
                  .getString("SPL_COLLECT_OPERATION_EXP_EXCEPTION2_MSG"));
    }
    associationName = (String)assocExp.evaluate();

    Expression roleExp = (Expression)paramList.get(2); // param 2 is role 1
    if(roleExp.getType().getType() != TypeConstants.stringType)
    {
      logger.severe(Thread.currentThread().getName()+" "+"3rd param to collect needs to be a string expression");

      throw new IllegalExpressionTypeException(
          "third "
              + Messages
                  .getString("SPL_COLLECT_OPERATION_EXP_EXCEPTION2_MSG"));
    }

    sourceRole = (String)roleExp.evaluate();

    roleExp = (Expression)paramList.get(3); // param 3 is role 2
    if(roleExp.getType().getType() != TypeConstants.stringType)
    {

      logger.severe(Thread.currentThread().getName()+" "+"4th param to collect needs to be a string expression");

      throw new IllegalExpressionTypeException(
          "fourth "
              + Messages
                  .getString("SPL_COLLECT_OPERATION_EXP_EXCEPTION2_MSG"));
    }
    targetRole = (String)roleExp.evaluate();

    Expression targetClassExp = (Expression)paramList.get(4); // param 4 is the target class name
    if(targetClassExp.getType().getType() != TypeConstants.stringType)
    {

      logger.severe(Thread.currentThread().getName()+" "+"5th param to collect needs to be a string expression");

      throw new IllegalExpressionTypeException(
          "fifth "
              + Messages
                  .getString("SPL_COLLECT_OPERATION_EXP_EXCEPTION2_MSG"));
    }
    targetClassName = (String)targetClassExp.evaluate();

    List instanceInfoList=new ArrayList();
    String qual=symTab.getDefaultQualifier();

    symTab.addAnchor(this.targetClassName, qual, instanceInfoList);

    if(refExp instanceof ReferenceExpression)
    {
      validateAssociation(sourceClassValidate,associationName,sourceRole,targetRole,targetClassName);

    }
    // validate that such an association actually exists

    // set the anchor for the collect symbol table to the targetclass name. This will populate static symbol info. for the targetclass
    //symTab.addCollectAnchor(targetClassName, qual, new ArrayList(), true);
    // NRJ

//    if(symTab.getAnchorClassList().size() !=1)
//    {
//    //System.out.println("symTab.getAnchorClassList().size() "+symTab.getAnchorClassList().size());
//    throw new SPLException(" symTab.getAnchorClassList().size() !=1 ");
//    }
//    else
//    {
//    symTab.addAnchor(this.targetClassName, qual, instanceInfoList);

//    }
    // no exceptions were thrown validation success

    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "validateCommonParameters");
    //System.out.println("validateCommonParameters done "+true);

    return true;
  }

  //collect(refExp, associationname, srcRole, targetRole, targetClass, <target class property>, targetExp)
  private boolean validateCollectFlavour2() throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "validateCollectFlavour2");
    //System.out.println("validateCollectFlavour2()");

    // validate the common params
    validateCommonParameters();

    Expression propNameExp = (Expression)paramList.get(5); // the 5th parameter is a property of the targetclass
    if(propNameExp.getType().getType() != TypeConstants.stringType)
    {

      logger.severe(Thread.currentThread().getName()+" "+"5th param to collect needs to be a string expression")

      throw new IllegalExpressionTypeException(
          "fifth "
              + Messages
                  .getString("SPL_COLLECT_OPERATION_EXP_EXCEPTION2_MSG"));
 
    }
    targetClassPropertyName = (String)propNameExp.evaluate();

    boolean recurse = false;
    if(!symTab.symbolExists(targetClassName + "." + targetClassPropertyName,recurse )) // make sure this is a valid property
    {

      logger.severe(targetClassName + "." + targetClassPropertyName + " does not exist");
     
      throw new NonExistentSymbolException(targetClassName + "." + targetClassPropertyName + " does not exist");
    }
    else
    {
      // xiping's modification to support Java overloading, 06/21/09
      Symbol propSymbol = (Symbol)symTab.getSymbol(targetClassName + "." + targetClassPropertyName);
//      Collection c = symTab.getSymbol(targetClassName + "." + targetClassPropertyName);
//      Iterator it = c.iterator();
//      Symbol propSymbol = (Symbol) it.next();
     
      this._dataType=new TypeInfoImpl(propSymbol.getType());
      this._dataType.setIsArray(true);
      expressionForTarget = (Expression)paramList.get(6); // 6th param is an expression involving properties of the targetclass
      if(expressionForTarget.validate())
      {
        if(expressionForTarget.getType().getType() != TypeConstants.booleanType) // this expression is used to filter instances hence needs to be boolean
       

          logger.severe(Thread.currentThread().getName()+" "+"6th param to collect needs to be a boolean expression");

          throw new IllegalExpressionTypeException(
              "sixth "
                  + Messages
                      .getString("SPL_COLLECT_OPERATION_EXP_EXCEPTION3_MSG"));

        }
        if(!noPostCollectOperation) // if an expression exists that follows collect
       

          // REMOVED BY NRJ
          //System.out.println("Post collect expression exists");   
          postCollectOperation.validate(this.targetClassName); // validate the expression
          if(postCollectOperation.Array2Exists() || postCollectOperation.isMethodOrParamExists())  {
            this._dataType=new TypeInfoImpl(postCollectOperation.getType());
          }
          else{
            this._dataType.setIsArray(false);
          }
        } 


      }
    }
    //System.out.println(" all went well, validation success validateCollectFlavour2");

    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "validateCollectFlavour2");
    //System.out.println("validateCollectFlavour2 done "+true);
    //System.out.println(" Type info "+this._dataType.getType()+" "+this._dataType.getIsArray());

    return true;

  }
  private boolean validateCollectFlavour1() throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "validateCollectFlavour1");

    //System.out.println("validateCollectFlavour1");

    //collect(<refExp>,<assocName>,<role1>,<role2>,<targetClass>,<expression>)[exp].param1[exp]
    //             .param1(pList)
    // validate the common parameters
    validateCommonParameters();

    // 5th param is an expression used to filter the instances
    expressionForTarget = (Expression)paramList.get(5);
    if(expressionForTarget.validate()) // validate the expression
    {
      this._dataType.setReferenceTypeName(this.targetClassName);
      this._dataType.setType(TypeConstants.referenceType);
      this._dataType.setIsArray(true);
      if(expressionForTarget.getType().getType() != TypeConstants.booleanType) // needs to be boolean type
     

        logger.severe(Thread.currentThread().getName()+" "+"6th param to collect needs to be a boolean expression");

        throw new IllegalExpressionTypeException(
            "sixth "
                + Messages
                    .getString("SPL_COLLECT_OPERATION_EXP_EXCEPTION3_MSG"));
      }
      if(!noPostCollectOperation) // post collect exists e.g. collect(...)[exp].prop
      {                                //     .prop[exp]   

        // REMOVED BY NRJ
        //symTab.addCollectAnchor(this.targetClassName, qual, instanceInfoList, true);

        postCollectOperation.validate(this.targetClassName);
        TypeInfo tpe=null;
        // validate the expression
        if(postCollectOperation.isMethodOrParamExists())
        {
          tpe = postCollectOperation.getType(); // get the type
          returnClassName = targetClassName; // return type is same as the targetclass

          this._dataType.setIsArray(tpe.getIsArray());
          this._dataType.setType(tpe.getType());

        }
      }



//      if(tpe != PostCollectExpression.POSTCOLLECT_IS_ARRAY) // implies of the form collect(...)[exp].prop...
//      { 
//      dataType = tpe; // return type is same as the type of post collect (either the type of prop or return type of array of type prop
//      // NEED TO SET isArray IF the Property is an array type with no array subscript expression
//      isArray = postCollectOperation.isArray();
//      } 
//      else
//      {
//      dataType = TypeConstants.referenceType; // post collect is simply collect(...)[exp]
//      returnClassName = targetClassName; // return type is same as the targetclass
//      isArray = false; // no array
//      }


    }


    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "validateCollectFlavour1");
    //System.out.println("validateCollectFlavour1 done "+true);

    return true;
  }

  // validate the association
  private void validateAssociation(String sourceCIMClass, String assocName, String roleName1, String roleName2, String resultclassName) throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "validateAssociation");

    //System.out.println("validateCollectFlavour1");

    boolean result = false;
    DataCollector dc = DataCollectorFactory.getDataCollector();
    result = dc.associationExists(sourceCIMClass, symTab.getDefaultQualifier(), resultclassName, assocName, roleName1, roleName2);
    if(!result)
    {

      logger.severe(Thread.currentThread().getName()+" "+"Invalid association " + " sourceClass :"+sourceCIMClass+" namespace :"+symTab.getDefaultQualifier()+ " resultclassName :" + resultclassName + " assocName :"+ assocName+ " roleName1 :" + roleName1 + " roleName2 :"+ roleName2);

      throw new SPLException("Invalid association " + " sourceClass :"+sourceCIMClass+" namespace :"+symTab.getDefaultQualifier()+ " resultclassName :" + resultclassName + " assocName :"+ assocName+ " roleName1 :" + roleName1 + " roleName2 :"+ roleName2);
    }

    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "validateAssociation");


  }
  public Object evaluate() throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "evaluate");

    Object result = null;
    if(collectType == COLLECT_FLAVOUR1)
    {
      //System.out.println("evaluate COLLECT_FLAVOUR1");
      result = evaluateFlavour1();
    }
    else
    {
      //System.out.println("evaluate COLLECT_FLAVOUR2");

      result = evaluateFlavour2();
    }

    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "evaluate");

    return result;
  }

  // evaluating flavour 2
  private Object evaluateFlavour2() throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "evaluateFlavour2");

    //System.out.println("evaluate evaluateFlavour2");

    Object result = null;
    // evaluate the reference expression to obtain the source instance
    Object refExpressionResult = referenceExpression.evaluate();
    String referenceStr=refExpressionResult.toString();
    DataCollector dc = DataCollectorFactory.getDataCollector();

//    String refTypeName=dc.getReferenceTypeName(referenceStr);
    List targetClassInstanceReferences = null;


    // get instances of the targetclass that satisfy the association conditions
    if(logger.isLoggable(Level.FINE))
      logger.fine(Thread.currentThread().getName()+" refExpressionResult evaluateFlavour2 "+referenceStr);
    //System.out.println("targetClassInstanceReferences to dc :"+refExpressionResult+" "+symTab.getDefaultQualifier()+" "+targetClassName+" "+associationName+" "+sourceRole+" "+targetRole);
   
    targetClassInstanceReferences = dc.getAssociatedInstanceReferences(refExpressionResult,symTab.getDefaultQualifier(),targetClassName,associationName,sourceRole,targetRole);
    //System.out.println("targetClassInstanceReferences "+targetClassInstanceReferences.toString());
    if (logger.isLoggable(Level.FINE))
    logger.fine(Thread.currentThread().getName()+" got associated references");

//    targetClassInstance = dc.getAssociatedInstanceReferences(refTypeName, symTab.getDefaultQualifier(), targetClassName,associationName,sourceRole,targetRole, refExpressionResult);
    if (logger.isLoggable(Level.FINE))
    logger.fine(Thread.currentThread().getName()+" got associated instances");

    // filter the List based on the target filter expression
    //System.out.println("filteredTargetClassInstanceReferences to dc :"+targetClassInstanceReferences+" "+symTab.getDefaultQualifier()+" "+this.targetClassName);
   
    List filteredTargetClassInstanceReferences = filterTargetClassInstanceReferencesWithTargetExpression(targetClassInstanceReferences , this.targetClassName,this.symTab.getDefaultQualifier());
    //System.out.println("targetClassInstanceReferences "+filteredTargetClassInstanceReferences.toString());
   
    if (logger.isLoggable(Level.FINE))
      logger.fine(Thread.currentThread().getName()+" got filtered references");

    ArrayList filteredTargetClassInstances = new ArrayList();

    Iterator filteredTargetClassInstanceReferencesIt=filteredTargetClassInstanceReferences.iterator();
    while(filteredTargetClassInstanceReferencesIt.hasNext())
    {
      Object ref=filteredTargetClassInstanceReferencesIt.next();
      Map instanceProperties=dc.getSymbolsForInstance(this.targetClassName,this.symTab.getDefaultQualifier(), ref);
      filteredTargetClassInstances.add(instanceProperties);
    }




    // The return type for flavour 2 is either an array of property values or a property value
    ArrayList listOfValuesForProperty = createListOfValuesForProperty(targetClassPropertyName,filteredTargetClassInstances);

    if(!noPostCollectOperation) // of the form collect(...)[exp]
    {
      result = postCollectOperation.evaluate(listOfValuesForProperty); // evaluation will pick one of the values of the listOfValuesForProperty array
    }
    else
    {
      //Integer index = (Integer)postCollectOperation.evaluate();
      //result = listOfValuesForProperty.get(index.intValue());
      result = listOfValuesForProperty; // there is no post collect therefore result is the entire array of property values
    }

    // return result;
    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "evaluateFlavour2");

    return result;



  }

  //collect(<refExp>,<assocName>,<role1>,<role2>,<targetClass>,<expression>)[exp].param1[exp]
  //             .param1(pList)
  private Object evaluateFlavour1() throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "evaluateFlavour1");
    //System.out.println("evaluate evaluateFlavour1");


    Object result = null;

    //evaluate the the first parameter to get the source instance
    Object refExpressionResult = referenceExpression.evaluate();
    String refExpressionStr=refExpressionResult.toString();
    //System.out.println("self = "+refExpressionResult);
    DataCollector dc = DataCollectorFactory.getDataCollector();
    //NRJ verify this works
//    String refTypeName = referenceExpression.getReferenceTypeName();
    //String refTypeName=dc.getReferenceTypeName(refExpressionStr);
    List targetClassInstanceReferences = null;

    // traverse association to get an array of target class instances. Each instance is a Map of key=values
    if(logger.isLoggable(Level.FINE))
      logger.fine(Thread.currentThread().getName()+" refExpressionResult evaluateFlavour1 "+refExpressionStr);

    targetClassInstanceReferences = dc.getAssociatedInstanceReferences((Object)refExpressionResult,symTab.getDefaultQualifier(),targetClassName,associationName,sourceRole,targetRole);
    //System.out.println("targetClassInstanceReferences size "+targetClassInstanceReferences.size());
    if(logger.isLoggable(Level.FINE))
      logger.fine(Thread.currentThread().getName()+" got associated references");

//    targetClassInstance = dc.getAssociatedInstanceReferences(refTypeName, symTab.getDefaultQualifier(), targetClassName,associationName,sourceRole,targetRole, refExpressionResult);
    if(logger.isLoggable(Level.FINE))
      logger.fine(Thread.currentThread().getName()+" got associated instances");

    // filter the List based on the target filter expression
    List filteredTargetClassInstanceReferences = filterTargetClassInstanceReferencesWithTargetExpression(targetClassInstanceReferences , this.targetClassName,this.symTab.getDefaultQualifier());
    //System.out.println("filteredTargetClassInstanceReferences size "+filteredTargetClassInstanceReferences.size());

    if(logger.isLoggable(Level.FINE))
      logger.fine(Thread.currentThread().getName()+" got filtered references");

    List filteredTargetClassInstances = new ArrayList();

    Iterator filteredTargetClassInstanceReferencesIt=filteredTargetClassInstanceReferences.iterator();
    while(filteredTargetClassInstanceReferencesIt.hasNext())
    {
      Object ref=filteredTargetClassInstanceReferencesIt.next();
      //System.out.println("filter passed : "+ref.toString());
      Map instanceProperties=dc.getSymbolsForInstance(this.targetClassName,this.symTab.getDefaultQualifier(), ref);
      filteredTargetClassInstances.add(instanceProperties);
    }

    if(logger.isLoggable(Level.FINE))
      logger.fine(Thread.currentThread().getName()+" got filtered instances");

    if(!noPostCollectOperation) // post collect exists
    {
      if(postCollectOperation.getType().getIsArray()) // of the form collect(...)[exp]
     
        result = postCollectOperation.evaluate(filteredTargetClassInstances); // will return a map corresponding to the instance to be returned
        int instanceNumber=postCollectOperation.getInstanceNumer();
        //symTab.populateInstanceValuesForCollect(this.targetClassName, this.targetClassName, filteredTargetClassInstances.get(instanceNumber), (Map)result); // populate it in the hashtable to obtain the string expression for the instance
        // NRJ
        symTab.populateInstanceValuesForInstance(this.targetClassName, this.targetClassName,
            filteredTargetClassInstances.get(instanceNumber), (Map)result);
        // populate it in the hashtable to obtain the string expression for the instance
        //result = symTab.getInstance();

     
      else // post collect of the form collect(...)[exp].prop
      {    
        // the result will be calculated as follows for
        // a) in the case prop is not an array
        // 1. Of the array of target class instances passed as the parameter
        // use the exp to pick one of the instances
        // for this instance obtain the value of prop and return
        // b) in the case prop is an array
        // if of the form collect(...)[exp].prop[exp] and exp == 1then the result will be the props[1]
        // if of the form collect(...)[exp].prop and prop is an array then the result will be an array of prop

        result = postCollectOperation.evaluate(filteredTargetClassInstances);

      }
    }
    else // no post collect result is an array of target instances that satisfy the filter
    {
      result = filteredTargetClassInstanceReferences;

    }


    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "evaluateFlavour1");


    return result;
  }

  // for flavour 2 need to extract the values for the property and create an array
  private ArrayList createListOfValuesForProperty(String propertyName, ArrayList filteredTargetClassInstances)
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "createListOfValuesForProperty");
    //System.out.println(" propertyName :"+propertyName);
    //System.out.println(" filteredTargetClassInstances.size() :"+filteredTargetClassInstances.size());
   
    ArrayList propertyList = new ArrayList();
    for(int i=0; i<filteredTargetClassInstances.size(); i++)
    {
      //System.out.println(" inside for");
      Map currMap = (Map)filteredTargetClassInstances.get(i);
      //System.out.println("currMap "+currMap.toString());
     
      Object s = (Object)currMap.get(propertyName);
      //System.out.println("adding property "+propertyName);
      //System.out.println(" object s :"+propertyName+" "+s.toString());
      propertyList.add(s);

    }

    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "createListOfValuesForProperty");

    return propertyList;
  }

  // Given a list of Maps where each map corresponds to an instance of the target class
  // filter out the instances which satisfy the boolean condition
  /*   private ArrayList filterTargetClassInstancesWithTargetExpression(List targetClassInstanceReferences) throws SPLException
    {
        logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "filterTargetClassInstancesWithTargetExpression");


        ArrayList filteredTargetClassInstances = new ArrayList();

        if(targetClassInstanceReferences!=null)
        {
            Iterator targetClassInstancesIt = targetClassInstanceReferences.iterator();
            while(targetClassInstancesIt.hasNext())
            {


                Object instanceRefernce = targetClassInstancesIt.next();
                DataCollector dc= DataCollectorFactory.getDataCollector();
                Map instanceProperties=dc.getSymbolsForInstance(this.targetClassName, symTab.getDefaultQualifier(), instanceRefernce);
                symTab.populateInstanceValuesForInstance(this.targetClassName, this.targetClassName, instanceRefernce, instanceProperties)populateSymbolTableWithInstanceValues(map);
                Boolean result = (Boolean)expressionForTarget.evaluate();
                if(result.booleanValue())
                {
                    filteredTargetClassInstances.add(map);
                }
            } 
        }
        else
        {
            if (logger.isLoggable(Level.FINE))
                logger.fine(Thread.currentThread().getName()+" Zero instances passed in hence zero instance references filtered, therefore returning null ");
        }

        logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "filterTargetClassInstancesWithTargetExpression");

        return filteredTargetClassInstances;
    }
   */

  private ArrayList filterTargetClassInstanceReferencesWithTargetExpression(List targetClassInstanceReferences , String className,String namespc) throws SPLException
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "filterTargetClassInstanceReferencesWithTargetExpression");
    DataCollector dc = DataCollectorFactory.getDataCollector();
    ArrayList filteredTargetClassInstanceReferences = new ArrayList();
    if(targetClassInstanceReferences!=null)
    {


      Iterator it=targetClassInstanceReferences.iterator();
      while(it.hasNext())
      {
        Object cop=(Object)it.next();
        //System.out.println("getSymbolsForInstance "+className+" "+ namespc+" "+ cop);
        Map map = dc.getSymbolsForInstance(className, namespc, cop);
        //System.out.println("map.size() "+map.size()+" "+map.toString());
        //symTab.populateInstanceValuesForCollect(className, className, cop, map);
        //NRJ
        symTab.populateInstanceValuesForInstance(className, className, cop, map);
        Boolean result = (Boolean)expressionForTarget.evaluate();
        //System.out.println("result "+result);
        if(result.booleanValue())
        {
          if(logger.isLoggable(Level.FINE))
            logger.fine(Thread.currentThread().getName()+" cop passed filter "+cop);
          //System.out.println("adding cop to list "+cop.toString());
         
          filteredTargetClassInstanceReferences.add(cop);
        }
        else
        {
          if(logger.isLoggable(Level.FINE))
            logger.fine(Thread.currentThread().getName()+" cop did not pass filter "+cop);
        }
      }
    }
    else
    {
      if (logger.isLoggable(Level.FINE))
        logger.fine(Thread.currentThread().getName()+" Zero instances passed in hence zero instance references filtered, therefore returning null ");
    }


    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "filterTargetClassInstanceReferencesWithTargetExpression");

    return filteredTargetClassInstanceReferences;
  }




  public TypeInfo getType() throws SPLException {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "BasicCollectionExpression");

    // if dataType is not set call validate so taht it gets set in the process
    if(_dataType != null)
    {

      logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "getType");
      return _dataType;

    }

    else
    {
      validate();

      logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "getType");

      return _dataType;
    }


  }


  public String getReferenceTypeName() {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "getReferenceTypeName");


    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "getReferenceTypeName");

    return returnClassName;
  }



  public boolean isArray() {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "isArray");


    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "isArray");

    return this._dataType.getIsArray();
  }

  public String toString()
  {
    logger.entering(sourceClass,Thread.currentThread().getName()+" "+ "toString");

//    String className=this.getClass().getName();

    String str="Collect(";

    Iterator ExpIt=this.paramList.iterator();
    while(ExpIt.hasNext()){
      Expression exp=(Expression)ExpIt.next();
      if(exp!=null){

        String expstr=exp.toString();
        str+=expstr + " , ";
      }

    }
    str=str.substring(0, str.length()-3) +" ) ";
//    if(this.expressionForTarget!=null){
//      str+=" "+this.expressionForTarget.toString()+" ";
//    }
    if(this.postCollectOperation!=null){
      str+="."+this.postCollectOperation.toString()+" ";
    }
//    if(this.referenceExpression!=null){
//      str+=" "+this.referenceExpression.toString()+" ";
//    }

//    str+=" )";


    logger.exiting(sourceClass,Thread.currentThread().getName()+" "+ "toString");

    return str;
  }

  public static String getSourceClass()
  {
    return sourceClass;
  }

  public String getAssociationName()
  {
    return associationName;
  }

  public void setAssociationName(String associationName)
  {
    this.associationName = associationName;
  }

  public int getCollectType()
  {
    return collectType;
  }

  public void setCollectType(int collectType)
  {
    this.collectType = collectType;
  }

  public boolean isNoPostCollectOperation()
  {
    return noPostCollectOperation;
  }

  public void setNoPostCollectOperation(boolean noPostCollectOperation)
  {
    this.noPostCollectOperation = noPostCollectOperation;
  }

  public String getReturnClassName()
  {
    return returnClassName;
  }

  public void setReturnClassName(String returnClassName)
  {
    this.returnClassName = returnClassName;
  }

  public String getTargetClassName()
  {
    return targetClassName;
  }

  public void setTargetClassName(String targetClassName)
  {
    this.targetClassName = targetClassName;
  }



}
TOP

Related Classes of org.apache.imperius.spl.parser.expression.primary.CollectOperation

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.