Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.kie.remote.services.rest;
  
  import static org.kie.remote.common.rest.RestEasy960Util.defaultVariant;
  import static org.kie.remote.common.rest.RestEasy960Util.getVariant;
  
  import java.util.Arrays;
  import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  javax.inject.Inject;
 import  javax.servlet.http.HttpServletRequest;
 import  javax.ws.rs.core.Context;
 import  javax.ws.rs.core.HttpHeaders;
 import  javax.ws.rs.core.Response;
 import  javax.ws.rs.core.Response.ResponseBuilder;
 import  javax.ws.rs.core.UriInfo;
 import  javax.ws.rs.core.Variant;
 
 import  org.jbpm.kie.services.impl.model.ProcessAssetDesc;
 import  org.jbpm.process.audit.AuditLogService;
 import  org.jbpm.services.api.model.ProcessDefinition;
 import  org.jbpm.services.task.commands.TaskCommand;
 import  org.jbpm.services.task.query.TaskSummaryImpl;
 import  org.kie.api.command.Command;
 import  org.kie.api.task.model.Group;
 import  org.kie.api.task.model.OrganizationalEntity;
 import  org.kie.api.task.model.Status;
 import  org.kie.api.task.model.User;
 import  org.kie.internal.task.api.TaskModelProvider;
 import  org.kie.internal.task.api.model.InternalOrganizationalEntity;
 import  org.kie.internal.task.api.model.InternalTask;
 import  org.kie.services.client.serialization.jaxb.impl.JaxbPaginatedList;
 import  org.kie.services.client.serialization.jaxb.impl.process.JaxbProcessDefinition;
 import  org.slf4j.Logger;
 import  org.slf4j.LoggerFactory;
 
 public class ResourceBase {
 
     protected static final Logger logger = LoggerFactory.getLogger(ResourceBase.class);
    
     @Inject
     
     @Context
     private UriInfo uriInfo;
     
     @Context
     private HttpServletRequest httpRequest;

    
In order to be able to inject a mock instance for tests.

Parameters:
processRequestBean
 
     public void setProcessRequestBeanProcessRequestBean processRequestBean ) {
         this. = processRequestBean;
     }
    
     
In order to be able to inject a mock instance for tests.

Parameters:
uriInfo
 
     void setUriInfo(UriInfo uriInfo) { 
         this. = uriInfo;
     }
   
    
In order to be able to inject a mock instance for tests.

Parameters:
httpRequest
 
     void setHttpServletRequest(HttpServletRequest httpRequest) { 
         this. = httpRequest;
     }
     
     // Any query parameters used in REST calls (besides the query operations), should be added here 
     
     static String PAGE_LONG_PARAM = "page";
     static String PAGE_SHORT_PARAM = "p";
     static String SIZE_LONG_PARAM = "pagesize";
     static String SIZE_SHORT_PARAM = "s";
    
     public static Set<StringpaginationParams = new HashSet<String>();
     static { 
     };
     
    public static final String PROC_INST_ID_PARAM_NAME = "runtimeProcInstId";
    
    public AuditLogService getAuditLogService() { 
        return .getAuditLogService();
    }
    
    // execute --------------------------------------------------------------------------------------------------------------------
    
    @SuppressWarnings("rawtypes")
        // If exceptions are happening here, then there is something REALLY wrong and they should be thrown.
        JaxbCommandsResponse jaxbResponse = new JaxbCommandsResponse(request);
        List<Command> commands = request.getCommands();
        if (commands != null) {
            int cmdListSize = commands.size(); 
           
            // First check to make sure that all commands will be processed
            for (int i = 0; i < cmdListSize; ++i) {
                Command<?> cmd = commands.get(i);
                if (!AcceptedServerCommands.isAcceptedCommandClass(cmd.getClass()) ) {
                    throw KieRemoteRestOperationException.forbidden("The execute REST operation does not accept " + cmd.getClass().getName() + " instances.");
                }
            }
           
            // Execute commands
            for (int i = 0; i < cmdListSize; ++i) {
                Command<?> cmd = commands.get(i);
                .processCommand(cmdrequestijaxbResponse);
            }
        }
        if (commands == null || commands.isEmpty()) {
            .info("Commands request object with no commands sent!");
        }
        return jaxbResponse;
    }
    
    // JSON / JAXB ---------------------------------------------------------------------------------------------------------------
    
    protected static Response createCorrectVariant(Object responseObj, HttpHeaders headers) { 
        return createCorrectVariant(responseObjheadersnull);
    }
    
    protected static Response createCorrectVariant(Object responseObj, HttpHeaders headers, javax.ws.rs.core.Response.Status status) { 
        ResponseBuilder responseBuilder = null;
        Variant v = getVariant(headers);
        ifv == null ) { 
            v = defaultVariant;
        }
        ifstatus != null ) { 
            responseBuilder = Response.status(status).entity(responseObj).variant(v);
        } else { 
            responseBuilder = Response.ok(responseObjv);
        }
        return responseBuilder.build();
    }
    
    // Request Params -------------------------------------------------------------------------------------------------------------
    
    protected Map<StringString[]> getRequestParams() {
        return .getParameterMap();
    }
    protected static String getStringParam(String paramNameboolean requiredMap<StringString[]> paramsString operation) {
        String [] paramValues = getStringListParam(paramNamerequiredparamsoperation);
        if( ! required && (paramValues.length == 0) ) { 
            return null;
        }
        if (paramValues.length != 1) {
            throw KieRemoteRestOperationException.badRequest("One and only one '" + paramName + "' query parameter required for '" + operation
                    + "' operation (" + paramValues.length + " passed).");
        }
        return paramValues[0];
    }
    private static final String [] EMPTY_STRING_ARR = new String[0];
    
    protected static List<StringgetStringListParamAsList(String paramNameboolean requiredMap<StringString[]> paramsString operation) {
        String [] strList = getStringListParam(paramNamerequiredparamsoperation);
        ifstrList.length == 0 ) { 
            return .;
        }
        return Arrays.asList(strList);
    }
    
    protected static String[] getStringListParam(String paramNameboolean requiredMap<StringString[]> paramsString operation) {
        String[] paramValues = null;
        for (Entry<StringString[]> entry : params.entrySet()) {
            if (entry.getKey().equalsIgnoreCase(paramName)) {
                paramValues = entry.getValue();
                break;
            }
        }
        if (paramValues == null) {
            if (required) {
                throw KieRemoteRestOperationException.badRequest("Query parameter '" + paramName + "' required for '" + operation
                        + "' operation.");
            }
            return ;
        }
        return paramValues;
    }
    
    protected static Object getObjectParam(String paramNameboolean requiredMap<StringString[]> paramsString operation) {
        String paramVal = getStringParam(paramNamerequiredparamsoperation);
        if (!required && paramVal == null) {
            return null;
        }
        return getObjectFromString(paramNameparamVal);
    }
    protected static List<LonggetLongListParam(String paramNameboolean requiredMap<StringString[]> paramsString operation,
            boolean mustBeLong) {
        String [] paramValues = getStringListParam(paramNamerequiredparamsoperation);
        List<LonglongValues = new ArrayList<Long>();
        forString strVal : paramValues ) { 
           longValues.add((LonggetNumberFromString(paramNamestrValmustBeLong));
        }
        return longValues;
    }
    
    protected static Number getNumberParam(String paramNameboolean requiredMap<StringString[]> paramsString operation,
            boolean mustBeLong) {
        String paramVal = getStringParam(paramNamerequiredparamsoperation);
        if (!required && paramVal == null) {
            return null;
        }
        return getNumberFromString(paramNameparamValmustBeLong);
    }
    private static Object getObjectFromString(String keyString mapVal) {
        if (mapVal.matches("^\".*\"$")) {
            return mapVal.substring(1, mapVal.length()-1);
        } else if (!mapVal.matches("^\\d+[li]?$")) {
            return mapVal;
        } else {
            return getNumberFromString(keymapValfalse);
        }
    }

    
Returns a Long if no suffix is present. Otherwise, possible suffixes are:
  • i : returns an Integer
  • l : returns an Long

Parameters:
paramName
paramVal
Returns:
    private static Number getNumberFromString(String paramNameString paramValboolean mustBeLong) {
        if (paramVal.matches("^\\d+[li]?$")) {
            if (paramVal.matches(".*i$")) {
                if (mustBeLong) {
                    throw KieRemoteRestOperationException.badRequestparamName 
                            + " parameter is numerical but contains the \"Integer\" suffix 'i' and must have no suffix or \"Long\" suffix 'l' ("
                            + paramVal + ")");
                }
                paramVal = paramVal.substring(0, paramVal.length() - 1);
                if (paramVal.length() > 9) {
                    throw KieRemoteRestOperationException.badRequest(paramName + " parameter is numerical but too large to be an integer ("
                            + paramVal + "i)");
                }
                return Integer.parseInt(paramVal);
            } else {
                if (paramVal.length() > 18) {
                    throw KieRemoteRestOperationException.badRequest(paramName + " parameter is numerical but too large to be a long ("
                            + paramVal + ")");
                }
                if (paramVal.matches(".*l$")) {
                    paramVal = paramVal.substring(0, paramVal.length() - 1);
                }
                return Long.parseLong(paramVal);
            }
        }
        throw KieRemoteRestOperationException.badRequest(paramName + " parameter does not have a numerical format (" + paramVal + ")");
    }
    protected static Map<StringObjectextractMapFromParams(Map<StringString[]> paramsString operation) {
        Map<StringObjectmap = new HashMap<StringObject>();
        for (Entry<StringString[]> entry : params.entrySet()) {
            if (entry.getKey().startsWith("map_")) {
                String key = entry.getKey();
                String[] paramValues = entry.getValue();
                if (paramValues.length != 1) {
                    throw KieRemoteRestOperationException.badRequest("Only one map_* (" + key + ") query parameter allowed for '" + operation
                            + "' operation (" + paramValues.length + " passed).");
                }
                String mapKey = key.substring("map_".length());
                String mapVal = paramValues[0].trim();
                map.put(mapKeygetObjectFromString(keymapVal));
            }
        }
        return map;
    }
    protected static List<OrganizationalEntity> getOrganizationalEntityListFromParams(Map<StringString[]> paramsboolean requiredString operation) {
        List<OrganizationalEntity> orgEntList = new ArrayList<OrganizationalEntity>();
        String [] users = getStringListParam("user"falseparamsoperation);
        String [] groups = getStringListParam("group"falseparamsoperation);
        if (required && (users.length == 0) && (groups.length == 0)) {
            throw KieRemoteRestOperationException.badRequest("At least 1 query parameter (either 'user' or 'group') is required for the '" + operation + "' operation.");
        }
        
        forString user : users ) {
            User newuser = TaskModelProvider.getFactory().newUser();
            ((InternalOrganizationalEntity) newuser).setId(user);
            orgEntList.add(newuser);
        }
        forString group : groups ) {
            Group newuser = TaskModelProvider.getFactory().newGroup();
            ((InternalOrganizationalEntity) newuser).setId(group);
            orgEntList.add(newuser);
        }
        
        return orgEntList;
    }
    
    protected static TaskSummaryImpl convertTaskToTaskSummary(InternalTask task) {
       TaskSummaryImpl taskSummary = new TaskSummaryImpl(
               task.getId().longValue(),
               task.getNames().get(0).getText(),
               task.getSubjects().get(0).getText(),
               task.getDescriptions().get(0).getText(),
               task.getTaskData().getStatus(),
               task.getPriority(),
               task.getTaskData().isSkipable(),
               task.getTaskData().getActualOwner(),
               task.getTaskData().getCreatedBy(),
               task.getTaskData().getCreatedOn(),
               task.getTaskData().getActivationTime(),
               task.getTaskData().getExpirationTime(),
               task.getTaskData().getProcessId(),
               task.getTaskData().getProcessSessionId(),
               task.getTaskData().getProcessInstanceId(),
               task.getTaskData().getDeploymentId(),
               task.getSubTaskStrategy(),
               task.getTaskData().getParentId()
               );
       return taskSummary;
    }
    
    protected static List<Status> convertStringListToStatusListList<StringstatusStrList ) { 
        List<Status> statuses = null;
        ifstatusStrList != null && ! statusStrList.isEmpty() ) { 
            statuses = new ArrayList<Status>();
            forString statusStr : statusStrList ) { 
                try { 
                    statuses.add(getEnum(statusStr));
                } catch(IllegalArgumentException iae) { 
                    throw KieRemoteRestOperationException.badRequest(statusStr + " is not a valid status type for a task." );
                }
            }
        }
        return statuses;
    }
    
    // Pagination ----------------------------------------------------------------------------------------------------------------
    
    static int PAGE_NUM = 0;
    static int PAGE_SIZE = 1;
   
    protected static int [] getPageNumAndPageSize(Map<StringString[]> paramsString oper) {
        int [] pageInfo = new int[2];
        
        int p = 0;
        Number page = getNumberParam(falseparamsoperfalse);
        ifpage != null ) { 
            p = page.intValue();
        } else { 
            Number pageShort = getNumberParam(falseparamsoperfalse);
            ifpageShort != null ) { 
                p = pageShort.intValue();
            }
        }
        ifp < 0 ) { 
            p = 0;
        }
        
        int s = 0;
        Number pageSize = getNumberParam(falseparamsoperfalse);
        ifpageSize != null ) { 
            s = pageSize.intValue();
        } else { 
            Number pageSizeShort = getNumberParam(falseparamsoperfalse);
            ifpageSizeShort != null ) { 
                s = pageSizeShort.intValue();
            }
        }
        ifs < 0 ) { 
            s = 0;
        }
        
        pageInfo[] = p;
        pageInfo[] = s;
        
        return pageInfo;
    }
   
    protected static <T> List<T> paginate(int[] pageInfoList<T> results) { 
        List<T> pagedResults = new ArrayList<T>();
        assert pageInfo[0] >= 0;
        ifpageInfo[1] > 0 && pageInfo[0] == 0 ) { 
            pageInfo[0] = 1;
        }
        ifpageInfo[0] == 0 && pageInfo[1] == 0) { 
            return results;
        }  else ifpageInfo[0] > 0 ) { 
            // for( i  = start of page; i < start of next page && i < num results; ++i ) 
            forint i = (pageInfo[0]-1)*pageInfo[1]; i < pageInfo[0]*pageInfo[1] && i < results.size(); ++i ) { 
                pagedResults.add(results.get(i));
            }
        }
        return pagedResults;
    }
    
    protected static int getMaxNumResultsNeeded(int [] pageInfo) { 
        int numResults = pageInfo[]*pageInfo[];
        ifnumResults == 0 ) { 
            numResults = 1000;
        } 
        return numResults;
    }
   
    protected static <T, R extends JaxbPaginatedList<T>> R 
        paginateAndCreateResult(Map<StringString[]> paramsString operList<T> results, R resultList) { 
        
        // paginate
        int [] pageInfo = getPageNumAndPageSize(paramsoper); 
        return paginateAndCreateResult(pageInforesultsresultList);
    }
        
    protected static <T, R extends JaxbPaginatedList<T>> R 
        paginateAndCreateResult(int [] pageInfoList<T> results, R resultList) { 
        
        ifpageInfo[0] == 0 && pageInfo[1] == 0 ) { 
            // no pagination
            resultList.addContents(results);
            return resultList;
        }
        
        results = paginate(pageInforesults);
       
        // create result
        resultList.addContents(results);
        resultList.setPageNumber(pageInfo[]);
        resultList.setPageSize(pageInfo[]);
        
        return resultList;
    }
    // URL/Context helper methods -------------------------------------------------------------------------------------------------
    
    protected String getBaseUri() { 
        return .getBaseUri().toString();
    }
    
    protected String getRequestUri() { 
        return .getRequestURI();
    }
    
    protected String getRelativePath() { 
        String url =  .getRequestURI();
        url.replaceAll".*/rest""");
        return url;
    }
    
    // Other helper methods ------------------------------------------------------------------------------------------------------
    
    protected static Status getEnum(String value) {
        value = value.substring(0,1).toUpperCase() + value.substring(1).toLowerCase();
        try { 
            return Status.valueOf(value);
        } catchIllegalArgumentException iae ) { 
           ifvalue.equalsIgnoreCase("inprogress") )  { 
               return Status.InProgress;
           }
           throw iae;
        }
    }
  
    protected JaxbProcessDefinition convertProcAssetDescToJaxbProcDef(ProcessDefinition procAssetDesc) {
        JaxbProcessDefinition jaxbProcDef = new JaxbProcessDefinition(); 
        jaxbProcDef.setDeploymentId(((ProcessAssetDesc)procAssetDesc).getDeploymentId());
        jaxbProcDef.setForms(((ProcessAssetDesc)procAssetDesc).getForms());
        jaxbProcDef.setId(procAssetDesc.getId());
        jaxbProcDef.setName(procAssetDesc.getName());
        jaxbProcDef.setPackageName(procAssetDesc.getPackageName());
        jaxbProcDef.setVersion(procAssetDesc.getVersion());
        
        return jaxbProcDef;
    }
 
    // TODO: shouldn't this also take a process runtime id for per-process runtimes? 
    public <T> T doRestTaskOperation(TaskCommand<T> cmd) { 
        return .doRestTaskOperation(nullnullnullnullcmd);
    }
    
    protected <T> T doRestTaskOperationWithTaskId(Long taskId, TaskCommand<T> cmd) { 
        return .doRestTaskOperation(taskIdnullnullnullcmd);
    }
    
    protected <T> T doRestTaskOperationWithDeploymentId(String deploymentId, TaskCommand<T> cmd) { 
        return .doRestTaskOperation(nulldeploymentIdnullnullcmd);
    }
New to GrepCode? Check out our FAQ X