Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.kie.remote.services.rest.query;
  
  import static org.kie.remote.services.rest.ResourceBase.*;
  import static org.kie.internal.query.QueryParameterIdentifiers.OLD_VALUE_LIST;
  import static org.kie.internal.query.QueryParameterIdentifiers.VALUE_LIST;
  import static org.kie.internal.query.QueryParameterIdentifiers.VARIABLE_ID_LIST;
  import static org.kie.internal.query.QueryParameterIdentifiers.VARIABLE_INSTANCE_ID_LIST;
  import static org.kie.internal.query.QueryParameterIdentifiers.VAR_VALUE_ID_LIST;
  import static org.kie.remote.services.rest.query.QueryResourceData.actionParamNameMap;
 import static org.kie.remote.services.rest.query.QueryResourceData.getDates;
 import static org.kie.remote.services.rest.query.QueryResourceData.getInts;
 import static org.kie.remote.services.rest.query.QueryResourceData.getLongs;
 import static org.kie.remote.services.rest.query.QueryResourceData.getTaskStatuses;
 import static org.kie.remote.services.rest.query.QueryResourceData.metaRuntimeParams;
 import static org.kie.remote.services.rest.query.QueryResourceData.metaRuntimeParamsShort;
 import static org.kie.remote.services.rest.query.QueryResourceData.paramNameActionMap;
 import static org.kie.remote.services.rest.query.QueryResourceData.varInstQueryParams;
 import static org.kie.remote.services.rest.query.QueryResourceData.varInstQueryParamsShort;
 
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  org.kie.api.task.model.Status;
 import  org.kie.internal.query.data.QueryData;
 import  org.kie.services.client.serialization.jaxb.impl.query.JaxbQueryProcessInstanceResult;
 import  org.kie.services.client.serialization.jaxb.impl.query.JaxbQueryTaskResult;
 
 
     protected ResourceBase resourceBase;
     
     public AbstractInternalQueryHelper(ResourceBase resourceBase) { 
        this. = resourceBase;
     }
 
     public void dispose() { 
         this. = null;
     }

    
Create the RemoteServicesQueryCommandBuilder instances used by the particular Query Helper implementation.

Parameters:
identity The identity of the user doing the REST call, needed when querying Tasks
 
     protected abstract void createAndSetQueryBuilders(String identity);
  
    
Calculates and returns the offset and max results information to be used in the query.

Parameters:
pageInfo Pagination information ([0] is page number, [1] is page size)
Returns:
a int array with the calculated offset and maximum number of results
 
     protected static int getOffset(int [] pageInfo) { 
         int offset = 0;
         ifpageInfo[0] == 0 && pageInfo[1] > 0 ) { 
             pageInfo[0] = 1;
         } 
         ifpageInfo[0] > 1 && pageInfo[1] > 0 ) {
             offset = (pageInfo[0]-1)*pageInfo[1];
         } 
         return offset;
     }
    
    
  1. Use the created RemoteServicesQueryCommandBuilder instances to execute the query via the backend.
  2. Create and fill a result instance (a JaxbQueryProcessInstanceResult or JaxbQueryTaskResult) with the information from the results of the queries

    Parameters:
    onlyRetrieveLastVarLogs Whether to
    workFlowInstanceVariables (UNFINISHED FEATURE) whether to use the information from variable instance logs or from the process instance variables themselves.
    pageInfo pagination information
    Returns:
 
     protected abstract R doQueryAndCreateResultObjects(boolean onlyRetrieveLastVarLogsboolean workFlowInstanceVariablesint [] pageInfo);

    
This method is the internal logic that
  1. preprocesses the list of query parameters passed to the ../rest/query/runtime/{task,process} operation
  2. builds and executes a query to retrieved the requested information
  3. converts the results to a JaxbQueryTaskResult or JaxbQueryProcessInstanceResult instance
There are some design patterns here that future developers should be aware of:
  1. The meta-message format: We translate the REST query parameters to a list of QueryAction instances to the actual QueryData, instead of directly translating REST query parameters to QueryData information. This effectively decouples the REST query parameters from the query builders, giving us more flexibility/maintainability in the code.

Parameters:
identity The identity of the caller, needed when doing task queries
queryParams The query parameters map returned by the JAX-RS logic
pageInfo The pagination information
maxResults The maximum number of results to be returned, determined by the pagination information
Returns:
A JaxbQueryTaskResult or JaxbQueryProcessInstanceResult containing a list of entities containing task and process variable information
    public R queryTaskOrProcInstAndAssociatedVariablesString identityMap<StringString[]> queryParamsint[] pageInfo) {
    
        // UNFINISHED FEATURE: use in-memory/process instance variables
        // 1. meta (in-memory or history variable values?) 
        boolean workFlowInstanceVariables = determineWorkFlowInstanceVariableUse(queryParams);
    
        // UNFINISHED FEATURE: use in-memory/process instance variables
        Map<StringStringprocVarValues;
        ifworkFlowInstanceVariables ) {
            procVarValues = new HashMap<StringString>();
        }
    
        // 0. Retrieve *all* variable log values, or just the most recent? 
        boolean onlyRetrieveLastVarLogs = true;
        String [] paramVals = queryParams.remove("all");
        ifparamVals != null ) { 
           onlyRetrieveLastVarLogs = false;
        }
        // Hold the information for parameters like "var_myVar=myVal" or "varregex_myVar=my*"
        Map<StringStringvarValueMap = new HashMap<StringString>();
        Map<StringStringvarRegexMap = new HashMap<StringString>();
    
        // 1. Create the query action queue, that is then processed to fill the query
        Queue<QueryActionqueryActionQueue = fillQueryActionQueueFromQueryParams(queryParamsvarValueMapvarRegexMap);
    
        // 2. Setup query builders
        createAndSetQueryBuilders(identity);
    
        // 3. process the query action queue, thus creating the {@link QueryData} instance for the query builders 
        processQueryActionQueue(queryActionQueuevarValueMapvarRegexMapworkFlowInstanceVariables);
    
        // 4. execute the query via the backend, which uses the creatd {@link QueryData} instance
        return doQueryAndCreateResultObjects(onlyRetrieveLastVarLogsworkFlowInstanceVariablespageInfo);
    }
    public R queryTasksOrProcInstsAndVariablesMap<StringString[]> queryParamsint[] pageInfo) {
       return queryTaskOrProcInstAndAssociatedVariables(nullqueryParamspageInfo);
    }
    
    
Figure out whether or not we're getting audit variable logs or workflow instance variables.

Parameters:
queryParams The map of (REST operation) query parameters
Returns:
Whether or not to use workflow instance variables
    protected boolean determineWorkFlowInstanceVariableUse(Map<StringString[]> queryParams) { 
        Boolean workFlowInstanceVariables = null;
        ifqueryParams.containsKey([0]) || queryParams.containsKey([0]) ) {
            workFlowInstanceVariables = true;
            queryParams.remove([0]);
            queryParams.remove([0]);
        }
        ifqueryParams.containsKey([1]) || queryParams.containsKey([1]) ) {
            ifworkFlowInstanceVariables != null ) {
                throw KieRemoteRestOperationException
                        .badRequest("Only one of the 'memory' and 'history' query parameters may be specified.");
            }
            workFlowInstanceVariables = false;
            queryParams.remove([1]);
            queryParams.remove([1]);
        }
        ifworkFlowInstanceVariables == null ) {
            workFlowInstanceVariables = false;
        }
        return workFlowInstanceVariables;
    }

    
Parse the given query parameters to create an ArrayDeque of QueryAction. The Queue of QueryAction is then acted upon by the {{@link #processQueryActionQueue(ArrayDeque, Map, Map, boolean)} method, which applies the different query actions to build the query requested via the query builder instances.

Parameters:
queryParams a Map of the received query parameters
varValueMap a Map that maps query variable names to the passed values
varRegexMap a Map that maps query variable names to the passed regexs for the specified variable
Returns:
A Queue of QueryAction instances
            Map<StringString[]> queryParams,
            Map<StringStringvarValueMap
            Map<StringStringvarRegexMap) { 
        
        ArrayDeque<QueryActionqueryActionQueue = new ArrayDeque<QueryAction>();
        
        // Go through all parameters and build a queue of {@link QueryAction) instances to be executed in the following loop
        forEntry<StringString[]> entry : queryParams.entrySet() ) {
            String orig_param = entry.getKey();
            if..contains(orig_param) ) {
                continue;
            }
            String[] paramParts = orig_param.split("_");
            String param = paramParts[0];
            ifparamParts.length >= 2 ) {
               
                if[2].equals(paramParts[0]) 
                    || [3].equals(paramParts[0]) 
                    || [3].equals(paramParts[0]) ) {
                    // check that variable parameter has only been submitted once as query parameter
                    String[] values = queryParams.get(orig_param);
                    ifvalues.length > 1 ) {
                        throw KieRemoteRestOperationException.badRequest("Only one value per variable parameter: '" + orig_param + "'");
                    }
                    String value = values[0];
                    // The variable may contain a "_": compensate for that by readding the rest of the split parts
                    String varName = null;
                    StringBuilder nameBuilder = new StringBuilder(paramParts[1]);
                    forint i = 2; i < paramParts.length; ++i ) {
                        nameBuilder.append("_").append(paramParts[i]);
                    }
                    varName = nameBuilder.toString();
                    // add action data to queue
                    Integer queryActionInt = .get(paramParts[0]);
                    String [] data = { varName };
                    QueryAction queryAction = new QueryAction(orig_paramqueryActionIntdata);
                    queryActionQueue.add(queryAction);
                    
                    // IF: 
                    // - the query parameter starts with 'var', then it's an 'equals' operation ("var_partid=23a")
                    // - the query parameter starts with 'varregex' or 'vr', then it's an regex operation ( "vr_partid=23*" )
                    if[2].equals(paramParts[0]) ) {
                        varValueMap.put(varNamevalue);
                    } else {
                        varRegexMap.put(varNamevalue);
                        queryAction.regex = true;
                    }
                    continue;
                }
                ifparamParts.length > 2 ) {
                    throw KieRemoteRestOperationException.badRequest("Query parameter '" + orig_param + "' is not supported.");
                }
                Integer action = .get(paramParts[0]);
                ifaction == null ) {
                    throw KieRemoteRestOperationException.badRequest("Query parameter '" + orig_param + "' is not supported.");
                }
                QueryAction queryAction = new QueryAction(orig_paramactionentry.getValue());
                queryActionQueue.add(queryAction);
                if"min".equals(paramParts[1]) ) {
                    queryAction.min = true;
                } else if"max".equals(paramParts[1]) ) {
                    queryAction.max = true;
                } else if"re".equals(paramParts[1]) ) {
                    queryAction.regex = true;
                } else {
                    throw KieRemoteRestOperationException.badRequest("Query parameter '" + orig_param + "' is not supported.");
                }
            } else {
                Integer action = .get(param);
                ifaction != null ) {
                    queryActionQueue.add(new QueryAction(orig_paramactionentry.getValue()));
                } else {
                    throw KieRemoteRestOperationException.badRequest("Query parameter '" + orig_param + "' is not supported.");
                }
            }
        }
        return queryActionQueue;
    }
  
    
If the QueryAction instance is a regex instance, this prepares the query builder instance to process the next parameter is as a regular expression, a.k.a. regex. The method must be called a second time to "de-activate" the regex interpretation by the query builder instance.

Parameters:
queryAction The QueryAction instance with the actual parameter
on Whether regular expressions should be turned on or off for the query builders
    private void setRegexOnOffQueryAction queryActionboolean on ) { 
        ifqueryAction.regex ) {
            ifon ) {
                forRemoteServicesQueryCommandBuilder queryCmdBuilder : getQueryBuilders() ) {
                    queryCmdBuilder.like();
                }
            } else {
                forRemoteServicesQueryCommandBuilder queryCmdBuilder : getQueryBuilders() ) {
                    queryCmdBuilder.equals();
                }
                queryAction.regex = false;
            }
        }
    }
    private static Set<StringVAR_QUERY_SPECIFIC_PARAMETER_LIST_IDS = new HashSet<String>();
    static { 
       .add(VARIABLE_ID_LIST);
       .add(VARIABLE_INSTANCE_ID_LIST);
       .add(OLD_VALUE_LIST);
       .add(VAR_VALUE_ID_LIST);
    }
    
    protected boolean variableCriteriaInQuery(QueryData queryData) { 
        if( ! queryData.intersectParametersAreEmpty() )  {
           forString key : queryData.getIntersectParameters().keySet() ) { 
              if.contains(key) ) { 
                 return true
              }
           }
        }
        return false;
     }
    
    
This is the main core of logic for the query helper classes. Initially, in methods called before this method, we converted the (REST operation) query methods to a Deque of QueryAction instances. We're using a Queue instead of a List because I may eventually want to add new QueryAction elements to the queue during processing: once I'm sure that I won't be doing that, I'll move this back to a List which is more efficient and performant. In this method, we go through each element (in the order that it was added) and translate the REST query parameter to a action on the query builder(s) so that the requested query can be built an executed.

Parameters:
queryActionQueue An ordered collection of QueryAction instances
varValueMap A Map mapping the variable name to the variable's value
varRegexMap A Map mapping the variable name to a regex for the variable's value
workFlowInstanceVariables Whether or not variable values should be retrieved from the audit logs or the process instance
    protected void processQueryActionQueue
            Queue<QueryActionqueryActionQueue,
            Map<StringStringvarValueMap,
            Map<StringStringvarRegexMap,
            boolean workFlowInstanceVariables
            ) { 
        int[] intData;
        long[] longData;
        Date[] dateData;
        while( !queryActionQueue.isEmpty() ) {
            QueryAction queryAction = queryActionQueue.poll();
            String[] data = queryAction.paramData;
            int action = queryAction.action;
            switch ( action ) {
            // general
            case 0: // processinstanceid
                assert "processinstanceid".equals(.get(action)): action + " : processinstanceid";
                longData = getLongs(actiondata);
                ifqueryAction.min || queryAction.max ) {
                    iflongData.length > 1 ) {
                        throw KieRemoteRestOperationException.notFound("Only 1 '" + queryAction.paramName
                                + "' parameter is accepted");
                    }
                    ifqueryAction.min ) {
                        processInstanceIdMin(longData);
                        queryAction.min = false;
                    } else ifqueryAction.max ) {
                        processInstanceIdMax(longData);
                        queryAction.max = false;
                    }
                } else {
                    processInstanceId(longData);
                }
                break;
            case 1: // processid
                assert "processid".equals(.get(action)): action + " : processid";
                setRegexOnOff(queryActiontrue);
                processId(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 2: // workitemid
                assert "workitemid".equals(.get(action)): action + " : workitemid";
                longData = getLongs(actiondata);
                workItemId(longData);
                break;
            case 3: // deploymentid
                assert "deploymentid".equals(.get(action)): action + " : deploymentid";
                setRegexOnOff(queryActiontrue);
                deploymentId(data);
                setRegexOnOff(queryActionfalse);
                break;
    
            // task
            case 4: // task id
                assert "taskid".equals(.get(action)): action + " : taskid";
                longData = getLongs(actiondata);
                ifqueryAction.min || queryAction.max ) {
                    iflongData.length > 1 ) {
                        throw KieRemoteRestOperationException.notFound("Only 1 '" + queryAction.paramName
                                + "' parameter is accepted");
                    }
                    ifqueryAction.min ) {
                        taskIdMax(longData[0]);
                        queryAction.min = false;
                    } else ifqueryAction.max ) {
                        taskIdMin(longData[0]);
                        queryAction.max = false;
                    }
                } else {
                    taskId(longData);
                }
                break;
            case 5: // initiator
                assert "initiator".equals(.get(action)): action + " : initiator";
                setRegexOnOff(queryActiontrue);
                initiator(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 6: // stakeholder
                assert "stakeholder".equals(.get(action)): action + " : stakeholder";
                setRegexOnOff(queryActiontrue);
                stakeHolder(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 7: // potential owner
                assert "potentialowner".equals(.get(action)): action + " : potentialowner";
                setRegexOnOff(queryActiontrue);
                potentialOwner(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 8: // task owner
                assert "taskowner".equals(.get(action)): action + " : taskowner";
                setRegexOnOff(queryActiontrue);
                taskOwner(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 9: // business admin
                assert "businessadmin".equals(.get(action)): action + " : businessadmin";
                setRegexOnOff(queryActiontrue);
                businessAdmin(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 10: // task status
                assert "taskstatus".equals(.get(action)): action + " : taskstatus";
                Status[] statuses = getTaskStatuses(data);
                taskStatus(statuses);
                break;
    
            // process instance
            case 11: // process instance status
                assert "processinstancestatus".equals(.get(action)): action + " : processinstancestatus";
                intData = getInts(actiondata);
                processInstanceStatus(intData);
                break;
            case 12: // process version
                assert "processversion".equals(.get(action)): action + " : processversion";
                setRegexOnOff(queryActiontrue);
                processVersion(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 13: // start date
                assert "startdate".equals(.get(action)): action + " : startdate";
                dateData = getDates(actiondata);
                ifqueryAction.min || queryAction.max ) {
                    ifdateData.length != 1 ) {
                        throw KieRemoteRestOperationException.notFound("Only 1 '" + queryAction.paramName
                                + "' parameter is accepted");
                    }
                    ifqueryAction.min ) {
                        startDateMin(dateData[0]);
                        queryAction.min = false;
                    } else ifqueryAction.max ) {
                        startDateMax(dateData[0]);
                        queryAction.max = false;
                    }
                } else {
                    startDate(dateData);
                }
                break;
            case 14: // end date
                assert "enddate".equals(.get(action)): action + " : enddate";
                dateData = getDates(actiondata);
                ifqueryAction.min || queryAction.max ) {
                    ifdateData.length > 1 ) {
                        throw KieRemoteRestOperationException.notFound("Only 1 '" + queryAction.paramName
                                + "' parameter is accepted");
                    }
                    ifqueryAction.min ) {
                        endDateMin(dateData[0]);
                        queryAction.min = false;
                    } else ifqueryAction.max ) {
                        endDateMax(dateData[0]);
                        queryAction.max = false;
                    }
                } else {
                    endDate(dateData);
                }
                break;
    
            // variable instance
            case 15: // var id
                assert "varid".equals(.get(action)): action + " : varid";
                ifqueryAction.regex && workFlowInstanceVariables ) {
                    String param = .get(action);
                    throw KieRemoteRestOperationException.badRequest("Regular expresssions are not supported on the '" + param
                            + "' parameter " + "when retrieving in-memory process variables");
                }
                setRegexOnOff(queryActiontrue);
                variableId(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 16: // var value
                assert "varvalue".equals(.get(action)): action + " : varvalue";
                ifqueryAction.regex && workFlowInstanceVariables ) {
                    String param = .get(action);
                    throw KieRemoteRestOperationException.badRequest("Regular expresssions are not supported on the '" + param
                            + "' parameter " + "when retrieving in-memory process variables");
                }
                setRegexOnOff(queryActiontrue);
                value(data);
                setRegexOnOff(queryActionfalse);
                break;
            case 17: // var
                assert "var".equals(.get(action)): action + " : var";
                variableValue(data[0], varValueMap.get(data[0]));
                break;
            case 18: // varregex
                assert "varregex".equals(.get(action)): action + " : varregex";
                setRegexOnOff(queryActiontrue);
                variableValue(data[0], varRegexMap.get(data[0]));
                setRegexOnOff(queryActionfalse);
                break;
    
            default:
                throw KieRemoteRestOperationException.internalServerError("Please contact the developers: state [" + action + "] should not be possible.");
            }
            ifqueryAction.min || queryAction.max || queryAction.regex ) {
                throw KieRemoteRestOperationException.notFound("Query parameter '" + queryAction.paramName + "' is not supported.");
            }
        }
    }
   
New to GrepCode? Check out our FAQ X