Java Code Examples for org.kie.api.runtime.process.WorkItem#getParameter()

The following examples show how to use org.kie.api.runtime.process.WorkItem#getParameter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ActivityTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallActivityWithContantsAssignment() throws Exception {
    KieBase kbase = createKnowledgeBaseWithoutDumper("subprocess/SingleTaskWithVarDef.bpmn2",
            "subprocess/InputMappingUsingValue.bpmn2");
    ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("CustomTask", handler);
    Map<String, Object> params = new HashMap<String, Object>();
    ProcessInstance processInstance = ksession.startProcess("defaultPackage.InputMappingUsingValue", params);

    WorkItem workItem = handler.getWorkItem();
    assertNotNull(workItem);

    Object value = workItem.getParameter("TaskName");
    assertNotNull(value);
    assertEquals("test string", value);

    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);

    assertProcessInstanceCompleted(processInstance);
}
 
Example 2
Source File: AddCalendarWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    Map<String, Object> results = new HashMap<String, Object>();

    String paramCalendarSummary = (String) workItem.getParameter("CalendarSummary");

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        com.google.api.services.calendar.Calendar client = auth.getAuthorizedCalendar(appName,
                                                                                      clientSecret);

        results.put(RESULTS_CALENDAR,
                    addCalendar(client,
                                paramCalendarSummary));

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 3
Source File: GetExistingPastebinWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {
        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        Map<String, Object> results = new HashMap<String, Object>();

        String pastebinKey = (String) workItem.getParameter("PastebinKey");

        PastebinLink pastebinLink = (PastebinLink) workItem.getParameter("PastebinLink");
        if (pastebinLink == null) {
            pastebinLink = Pastebin.getPaste(pastebinKey);
        }

        pastebinLink.fetchContent();
        results.put(RESULTS_VALUE,
                    pastebinLink.getPaste().getContents());
        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 4
Source File: ListImagesWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    Map<String, Object> results = new HashMap<>();

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String showAll = (String) workItem.getParameter("ShowAll");

        if (dockerClient == null) {
            DockerClientConnector connector = new DockerClientConnector();
            dockerClient = connector.getDockerClient();
        }

        ListImagesCmd listImagesCmd = dockerClient.listImagesCmd();
        if (showAll != null && Boolean.parseBoolean(showAll)) {
            listImagesCmd = listImagesCmd.withShowAll(true);
        }

        List<Image> images = listImagesCmd.exec();

        results.put(RESULTS_DOCUMENT,
                    images);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Unable to get list of containers: " + e.getMessage());
        handleException(e);
    }
}
 
Example 5
Source File: GetBalanceWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {
        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String serviceURL = (String) workItem.getParameter("ServiceURL");

        Map<String, Object> results = new HashMap();

        if (web3j == null) {
            web3j = Web3j.build(new HttpService(serviceURL));
        }

        auth = new EthereumAuth(walletPassword,
                                walletPath,
                                classLoader);
        Credentials credentials = auth.getCredentials();

        results.put(RESULTS_VALUE,
                    EthereumUtils.getBalanceInEther(credentials,
                                                    web3j));

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Error executing workitem: " + e.getMessage());
        handleException(e);
    }
}
 
Example 6
Source File: ListContainersWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    Map<String, Object> results = new HashMap<>();

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String statusFilter = (String) workItem.getParameter("StatusFilter");

        if (dockerClient == null) {
            DockerClientConnector connector = new DockerClientConnector();
            dockerClient = connector.getDockerClient();
        }

        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd()
                .withShowAll(true).withShowSize(true);

        if (statusFilter != null && statusFilter.trim().length() > 0) {
            listContainersCmd = listContainersCmd.withStatusFilter(statusFilter);
        }

        List<Container> containers = listContainersCmd.exec();

        results.put(RESULTS_DOCUMENT,
                    containers);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Unable to get list of containers: " + e.getMessage());
        handleException(e);
    }
}
 
Example 7
Source File: DownloadFileWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    Map<String, Object> results = new HashMap<String, Object>();

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        if (auth == null) {
            auth = new DropboxAuth();
        }

        client = auth.authorize(clientIdentifier,
                                accessToken);

        String dropboxDocumentPath = (String) workItem.getParameter("DocumentPath");

        InputStream inStream = client.files().downloadBuilder(dropboxDocumentPath)
                .start().getInputStream();

        Path path = Paths.get(dropboxDocumentPath);

        Document doc = new DocumentImpl();
        doc.setName(path.getFileName().toString());
        doc.setIdentifier(dropboxDocumentPath);
        doc.setLastModified(new Date());
        doc.setContent(IOUtils.toByteArray(inStream));

        results.put(RESULTS_DOCUMENT,
                    doc);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Unable to download file: " + e.getMessage());
        handleException(e);
    }
}
 
Example 8
Source File: AddTaskWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    String taskName = (String) workItem.getParameter("TaskName");
    String taskKind = (String) workItem.getParameter("TaskKind");

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        Tasks service = auth.getTasksService(appName,
                                             clientSecret);

        TaskList taskList = new TaskList();
        taskList.setTitle(taskName);
        taskList.setId(taskName);
        taskList.setKind(taskKind);
        taskList.setUpdated(new DateTime(new Date()));

        service.tasklists().insert(taskList).execute();

        workItemManager.completeWorkItem(workItem.getId(),
                                         null);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 9
Source File: MavenEmbedderCommand.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
protected Object getData(CommandContext ctx,
                         String name) {
    WorkItem workItem = (WorkItem) ctx.getData("workItem");
    Object data = null;
    if (workItem != null) {
        data = workItem.getParameter(name);
    }

    if (data == null) {
        data = ctx.getData(name);
    }

    return data;
}
 
Example 10
Source File: ListRepositoriesWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        Map<String, Object> results = new HashMap<String, Object>();

        String user = (String) workItem.getParameter("User");

        RepositoryService repoService = auth.getRespositoryService(this.userName,
                                                                   this.password);

        List<Repository> userRepos = repoService.getRepositories(user);
        List<RepositoryInfo> resultRepositoryInformation = new ArrayList<>();

        if (userRepos != null) {
            for (Repository repo : userRepos) {
                resultRepositoryInformation.add(new RepositoryInfo(repo));
            }
        } else {
            logger.info("No repositories found for " + user);
        }

        results.put(RESULTS_VALUE,
                    resultRepositoryInformation);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 11
Source File: GetUsersWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String userids = (String) workItem.getParameter("UserIds");

        List<OktaUser> retUserList = new ArrayList<>();

        UserList userList = oktaClient.listUsers();

        if (userids != null && userids.length() > 0) {
            List<String> useridsList = Arrays.asList(userids.split(","));
            userList.stream()
                    .filter(usr -> useridsList.contains(usr.getId()))
                    .forEach(usr -> retUserList.add(new OktaUser(usr)));
        } else {
            // get all
            userList.stream().forEach(usr -> retUserList.add(new OktaUser(usr)));
        }

        Map<String, Object> results = new HashMap<>();
        results.put(RESULTS_VALUE,
                    retUserList);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 12
Source File: ExecWorkItemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager manager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String command = (String) workItem.getParameter("Command");
        List<String> arguments = (List<String>) workItem.getParameter("Arguments");

        Map<String, Object> results = new HashMap<>();

        CommandLine commandLine = CommandLine.parse(command);
        if (arguments != null && arguments.size() > 0) {
            commandLine.addArguments(arguments.toArray(new String[0]),
                                     true);
        }

        parsedCommandStr = commandLine.toString();

        DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);
        executor.execute(commandLine);

        results.put(RESULT,
                    outputStream.toString());

        outputStream.close();

        manager.completeWorkItem(workItem.getId(),
                                 results);
    } catch (Throwable t) {
        handleException(t);
    }
}
 
Example 13
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
public static void runTestSignallingExceptionServiceTask(KieSession ksession) throws Exception {
    // Setup
    String eventType = "exception-signal";
    SignallingTaskHandlerDecorator signallingTaskWrapper = new SignallingTaskHandlerDecorator(ServiceTaskHandler.class, eventType);
    signallingTaskWrapper.setWorkItemExceptionParameterName(ExceptionService.exceptionParameterName);
    ksession.getWorkItemManager().registerWorkItemHandler("Service Task", signallingTaskWrapper);
   
    Object [] caughtEventObjectHolder = new Object[1];
    caughtEventObjectHolder[0] = null;
    ExceptionService.setCaughtEventObjectHolder(caughtEventObjectHolder);
    
    // Start process
    Map<String, Object> params = new HashMap<String, Object>();
    String input = "this is my service input";
    params.put("serviceInputItem", input );
    ProcessInstance processInstance = ksession.startProcess("ServiceProcess", params);

    // Check that event was passed to Event SubProcess (and grabbed by WorkItemHandler);
    assertThat(caughtEventObjectHolder[0] != null && caughtEventObjectHolder[0] instanceof WorkItem).isTrue().withFailMessage("Event was not passed to Event Subprocess.");
    WorkItem workItem = (WorkItem) caughtEventObjectHolder[0];
    Object throwObj = workItem.getParameter(ExceptionService.exceptionParameterName);
    assertThat(throwObj instanceof Throwable).isTrue().withFailMessage("WorkItem doesn't contain Throwable.");
    assertThat(((Throwable) throwObj).getMessage().endsWith(input)).isTrue().withFailMessage("Exception message does not match service input.");

    // Complete process
    assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_ACTIVE).withFailMessage("Process instance is not active.");
    ksession.getWorkItemManager().completeWorkItem(workItem.getId(), null);
    
    processInstance = ksession.getProcessInstance(processInstance.getId());
    if( processInstance != null ) {
        assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED).withFailMessage("Process instance is not completed.");
    } // otherwise, persistence use => processInstance == null => process is completed
}
 
Example 14
Source File: AddUserToGroupWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String userId = (String) workItem.getParameter("UserId");
        String groupId = (String) workItem.getParameter("GroupId");

        User user = oktaClient.getUser(userId);
        if (user == null) {
            throw new IllegalArgumentException("Not able to find user with id: " + userId);
        }

        Group group = oktaClient.getGroup(groupId);
        if (group != null) {
            throw new IllegalArgumentException("Not able to find group with id: " + groupId);
        }

        user.addToGroup(groupId);

        workItemManager.completeWorkItem(workItem.getId(),
                                         null);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 15
Source File: ResolveIssueWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String issueKey = (String) workItem.getParameter("IssueKey");
        String resolution = (String) workItem.getParameter("Resolution");
        String resolutionComment = (String) workItem.getParameter("ResolutionComment");

        if (auth == null) {
            auth = new JiraAuth(userName,
                                password,
                                repoURI);
        }

        NullProgressMonitor progressMonitor = new NullProgressMonitor();
        Issue issue = auth.getIssueRestClient().getIssue(issueKey,
                                                         progressMonitor);

        if (issue != null) {
            Iterable<Transition> transitions = auth.getIssueRestClient().getTransitions(issue.getTransitionsUri(),
                                                                                        progressMonitor);

            Transition resolveIssueTransition = getTransitionByName(transitions,
                                                                    "Resolve Issue");
            Collection<FieldInput> fieldInputs = Arrays.asList(new FieldInput("resolution",
                                                                              resolution));
            TransitionInput transitionInput = new TransitionInput(resolveIssueTransition.getId(),
                                                                  fieldInputs,
                                                                  Comment.valueOf(resolutionComment));
            auth.getIssueRestClient().transition(issue.getTransitionsUri(),
                                                 transitionInput,
                                                 progressMonitor);

            workItemManager.completeWorkItem(workItem.getId(),
                                             null);
        } else {
            logger.error("Could not find issue with key: " + issueKey);
            throw new IllegalArgumentException("Could not find issue with key: " + issueKey);
        }
    } catch (Exception e) {
        logger.error("Error executing workitem: " + e.getMessage());
        handleException(e);
    }
}
 
Example 16
Source File: MatchesInfoWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String summonerName = (String) workItem.getParameter("SummonerName");
        String numOfMatchesStr = (String) workItem.getParameter("NumOfMatches");

        int numOfMatches = 1;
        if (numOfMatchesStr != null && numOfMatchesStr.trim().length() > 0) {
            numOfMatches = Integer.parseInt(numOfMatchesStr);
        }

        String summonerPlatform = (String) workItem.getParameter("SummonerPlatform");

        Map<String, Object> results = new HashMap<String, Object>();

        Platform platform = RiotUtils.getPlatform(summonerPlatform);

        if (riotAuth == null) {
            riotAuth = new RiotAuth();
        }

        riotApi = riotAuth.getRiotApi(apiKey);
        Summoner summoner = riotApi.getSummonerByName(platform,
                                                      summonerName);

        if (summoner != null) {
            List<Match> matchesList = new ArrayList<>();
            MatchList matchList = riotApi.getMatchListByAccountId(platform,
                                                                  summoner.getAccountId());

            List<MatchReference> matchReferenceList = RiotUtils.geNumberOfPlayedMatches(matchList.getMatches(),
                                                                                        numOfMatches);

            for (MatchReference matchReference : matchReferenceList) {

                matchesList.add(riotApi.getMatch(platform,
                                                 matchReference.getGameId()));
            }

            results.put(RESULTS_VALUE,
                        RiotUtils.getPlayedMatches(matchesList,
                                                   numOfMatches));

            workItemManager.completeWorkItem(workItem.getId(),
                                             results);
        } else {
            throw new IllegalArgumentException("Could not find summoner with name: " + summonerName + " and platform: " + summonerPlatform);
        }
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 17
Source File: CreateUserWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String userEmail = (String) workItem.getParameter("UserEmail");
        String userFirstName = (String) workItem.getParameter("UserFirstName");
        String userLastName = (String) workItem.getParameter("UserLastName");
        String userActive = (String) workItem.getParameter("UserActive");
        String userGroupIds = (String) workItem.getParameter("UserGroupIds");
        String userLogin = (String) workItem.getParameter("UserLogin");
        String userPassword = (String) workItem.getParameter("UserPassword");
        String userSecurityQuestion = (String) workItem.getParameter("UserSecurityQuestion");
        String userSecurityAnswer = (String) workItem.getParameter("UserSecurityAnswer");

        UserBuilder userBuilder = UserBuilder.instance()
                .setEmail(userEmail)
                .setFirstName(userFirstName)
                .setLastName(userLastName);

        if (userActive != null) {
            userBuilder = userBuilder.setActive(Boolean.parseBoolean(userActive));
        }

        if (userGroupIds != null) {
            List<String> groupIdsList = Arrays.asList(userGroupIds.split(","));
            for (String grp : groupIdsList) {
                userBuilder = userBuilder.addGroup(grp);
            }
        }

        if (userLogin != null) {
            userBuilder = userBuilder.setLogin(userLogin);
        }

        if (userPassword != null) {
            userBuilder = userBuilder.setPassword(userPassword.toCharArray());
        }

        if (userSecurityQuestion != null) {
            userBuilder = userBuilder.setSecurityQuestion(userSecurityQuestion);
        }

        if (userSecurityAnswer != null) {
            userBuilder = userBuilder.setSecurityQuestionAnswer(userSecurityAnswer);
        }

        User user = userBuilder.buildAndCreate(oktaClient);

        Map<String, Object> results = new HashMap<>();
        results.put(RESULTS_VALUE,
                    user.getId());

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example 18
Source File: TransactExistingContractWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    try {
        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String serviceURL = (String) workItem.getParameter("ServiceURL");
        String contractAddress = (String) workItem.getParameter("ContractAddress");
        String waitForReceiptStr = (String) workItem.getParameter("WaitForReceipt");
        String methodName = (String) workItem.getParameter("MethodName");
        Type methodInputType = (Type) workItem.getParameter("MethodInputType");
        String depositAmount = (String) workItem.getParameter("DepositAmount");

        Map<String, Object> results = new HashMap<String, Object>();

        if (web3j == null) {
            web3j = Web3j.build(new HttpService(serviceURL));
        }

        auth = new EthereumAuth(walletPassword,
                                walletPath,
                                classLoader);
        Credentials credentials = auth.getCredentials();

        int depositEtherAmountToSend = 0;
        if (depositAmount != null) {
            depositEtherAmountToSend = Integer.parseInt(depositAmount);
        }

        boolean waitForReceipt = false;
        if (waitForReceiptStr != null) {
            waitForReceipt = Boolean.parseBoolean(waitForReceiptStr);
        }

        List<Type> methodInputTypeList = new ArrayList<>();
        if (methodInputType != null) {
            methodInputTypeList = Collections.singletonList(methodInputType);
        }

        TransactionReceipt transactionReceipt = EthereumUtils.transactExistingContract(
                credentials,
                web3j,
                depositEtherAmountToSend,
                EthereumUtils.DEFAULT_GAS_PRICE,
                EthereumUtils.DEFAULT_GAS_LIMIT,
                contractAddress,
                methodName,
                methodInputTypeList,
                null,
                waitForReceipt,
                EthereumUtils.DEFAULT_SLEEP_DURATION,
                EthereumUtils.DEFAULT_ATTEMPTS);

        results.put(RESULTS,
                    transactionReceipt);

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Error executing workitem: " + e.getMessage());
        handleException(e);
    }
}
 
Example 19
Source File: JPAWorkItemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem wi,
                            WorkItemManager wim) {
    Object actionParam = wi.getParameter(P_ACTION);
    Object entity = wi.getParameter(P_ENTITY);
    Object id = wi.getParameter(P_ID);
    Object type = wi.getParameter(P_TYPE);
    Object queryName = wi.getParameter(P_QUERY);
    Object queryParams = wi.getParameter(P_QUERY_PARAMS);
    Map<String, Object> params = new HashMap<String, Object>();
    List<Object> queryResults = Collections.emptyList();
    String action;

    // Only QUERY does no require an entity parameter
    if (entity == null && P_ACTION.equals(QUERY_ACTION)) {
        throw new IllegalArgumentException(
                "An entity is required. Use the 'entity' parameter");
    }
    action = String.valueOf(actionParam).trim().toUpperCase();
    logger.debug("Action {} on {}",
                 action,
                 entity);
    EntityManager em = emf.createEntityManager();
    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            wi);

        // join the process transaction
        em.joinTransaction();
        switch (action) {
            case DELETE_ACTION:
                doDelete(em,
                         entity,
                         id);
                break;
            case GET_ACTION:
                if (id == null || type == null) {
                    throw new IllegalArgumentException(
                            "Id or type can't be null when getting an entity");
                }
                // only works with long for now
                entity = doGet(em,
                               type.toString(),
                               Long.parseLong(id.toString()));
                break;
            case UPDATE_ACTION:
                doUpdate(em,
                         entity);
                break;
            case CREATE_ACTION:
                em.persist(entity);
                break;
            case QUERY_ACTION:
                if (queryName == null) {
                    throw new IllegalArgumentException("You must provide a '"
                                                               + P_QUERY + "' parameter to run named queries.");
                }
                queryResults = doQuery(em,
                                       String.valueOf(queryName),
                                       queryParams);
                break;
            default:
                throw new IllegalArgumentException(
                        "Action " + action + " not recognized. Use 'delete', 'create', 'update', query, or 'get'");
        }
        params.put(P_RESULT,
                   entity);
        params.put(P_QUERY_RESULTS,
                   queryResults);
        wim.completeWorkItem(wi.getId(),
                             params);
    } catch (Exception e) {
        logger.debug("Error performing JPA action ",
                     e);
        handleException(e);
    } finally {
        em.close();
    }
}
 
Example 20
Source File: ClassifyImageWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        Document classificationImage = (Document) workItem.getParameter("ImageToClassify");

        Map<String, Object> widResults = new HashMap<String, Object>();

        VisualRecognition service = auth.getService(apiKey);

        ByteArrayInputStream imageStream = new ByteArrayInputStream(classificationImage.getContent());

        ClassifyOptions classifyOptions = new ClassifyOptions.Builder()
                .imagesFile(imageStream)
                .imagesFilename(classificationImage.getName())
                .parameters("{\"owners\": [\"me\"]}")
                .build();
        ClassifiedImage result = service.classify(classifyOptions).execute().getImages().get(0);
        if (result.getError() != null) {
            ErrorInfo errorInfo = result.getError();
            logger.error("Error classifying image: " + errorInfo.getDescription());
            workItemManager.abortWorkItem(workItem.getId());
        } else {
            List<ImageClassificationResult> resultList = new ArrayList<>();
            for (ClassifierResult classification : result.getClassifiers()) {
                for (ClassResult classResult : classification.getClasses()) {
                    resultList.add(new ImageClassificationResult(classification,
                                                                 classResult));
                }

                widResults.put(RESULT_VALUE,
                               resultList);
            }
            workItemManager.completeWorkItem(workItem.getId(),
                                             widResults);
        }
    } catch (Exception e) {
        handleException(e);
    }
}