org.kie.api.runtime.process.WorkItemManager Java Examples
The following examples show how to use
org.kie.api.runtime.process.WorkItemManager.
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 |
@Test public void testServiceTaskNoInterfaceName() throws Exception { KieBase kbase = createKnowledgeBase("BPMN2-ServiceTask-web-service.bpmn2"); ksession = createKnowledgeSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler("Service Task", new SystemOutWorkItemHandler() { @Override public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { assertEquals("SimpleService", workItem.getParameter("Interface")); assertEquals("hello", workItem.getParameter("Operation")); assertEquals("java.lang.String", workItem.getParameter("ParameterType")); assertEquals("##WebService", workItem.getParameter("implementation")); assertEquals("hello", workItem.getParameter("operationImplementationRef")); assertEquals("SimpleService", workItem.getParameter("interfaceImplementationRef")); super.executeWorkItem(workItem, manager); } }); Map<String, Object> params = new HashMap<String, Object>(); WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession .startProcess("org.jboss.qa.jbpm.CallWS", params); assertProcessInstanceFinished(processInstance, ksession); }
Example #2
Source File: ParserWorkItemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 6 votes |
@Test public void testJsonToObject() { WorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter(ParserWorkItemHandler.INPUT, PERSON_JSON); workItem.setParameter(ParserWorkItemHandler.FORMAT, ParserWorkItemHandler.JSON); workItem.setParameter(ParserWorkItemHandler.TYPE, "org.jbpm.process.workitem.parser.Person"); handler.executeWorkItem(workItem, manager); Map<String, Object> results = ((TestWorkItemManager) manager).getResults(workItem.getId()); Person result = (Person) results.get(ParserWorkItemHandler.RESULT); assertEquals(AGE, result.getAge()); assertEquals(NAME, result.getName()); }
Example #3
Source File: JPAWorkItemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 6 votes |
private List<Product> getAllProducts() throws Exception { WorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter(JPAWorkItemHandler.P_ACTION, JPAWorkItemHandler.QUERY_ACTION); workItem.setParameter(JPAWorkItemHandler.P_QUERY, "SELECT p FROM Product p"); UserTransaction ut = getUserTransaction(); ut.begin(); handler.executeWorkItem(workItem, manager); ut.commit(); Map<String, Object> results = ((TestWorkItemManager) manager).getResults(workItem.getId()); @SuppressWarnings("unchecked") List<Product> products = (List<Product>) results.get(JPAWorkItemHandler.P_QUERY_RESULTS); return products; }
Example #4
Source File: SpeedLimitsWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 6 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { String[] placeIds = ((String) workItem.getParameter("PlaceIds")).split(","); try { RequiredParameterValidator.validate(this.getClass(), workItem); Map<String, Object> results = new HashMap<>(); SpeedLimit[] speedLimits = RoadsApi.speedLimits(geoApiContext, placeIds).await(); results.put(RESULTS_VALUE, speedLimits); workItemManager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { handleException(e); } }
Example #5
Source File: JPAWorkItemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 6 votes |
private Product getProduct(String id) throws Exception { WorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter(JPAWorkItemHandler.P_ACTION, JPAWorkItemHandler.GET_ACTION); workItem.setParameter(JPAWorkItemHandler.P_TYPE, "org.jbpm.process.workitem.jpa.Product"); workItem.setParameter(JPAWorkItemHandler.P_ID, id); UserTransaction ut = getUserTransaction(); ut.begin(); handler.executeWorkItem(workItem, manager); ut.commit(); Map<String, Object> results = ((TestWorkItemManager) manager).getResults(workItem.getId()); Product product = (Product) results.get(JPAWorkItemHandler.P_RESULT); return product; }
Example #6
Source File: CreateGroupWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 6 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); String groupName = (String) workItem.getParameter("GroupName"); String groupDescription = (String) workItem.getParameter("GroupDescription"); Group group = GroupBuilder.instance() .setName(groupName) .setDescription(groupDescription).buildAndCreate(oktaClient); Map<String, Object> results = new HashMap<>(); results.put(RESULTS_VALUE, group.getId()); workItemManager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { handleException(e); } }
Example #7
Source File: IntermediateEventTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Test @Disabled("Transfomer has been disabled") public void testMessageIntermediateThrowWithTransformation() throws Exception { KieBase kbase = createKnowledgeBaseWithoutDumper("BPMN2-IntermediateThrowEventMessageWithTransformation.bpmn2"); ksession = createKnowledgeSession(kbase); final StringBuffer messageContent = new StringBuffer(); ksession.getWorkItemManager().registerWorkItemHandler("Send Task", new SendTaskHandler(){ @Override public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { // collect message content for verification messageContent.append(workItem.getParameter("Message")); super.executeWorkItem(workItem, manager); } }); Map<String, Object> params = new HashMap<String, Object>(); params.put("x", "MyValue"); ProcessInstance processInstance = ksession.startProcess( "MessageIntermediateEvent", params); assertProcessInstanceCompleted(processInstance); assertThat(messageContent.toString()).isEqualTo("MYVALUE"); }
Example #8
Source File: StatefulKnowledgeSessionImpl.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public WorkItemManager getWorkItemManager() { if (workItemManager == null) { workItemManager = config.getWorkItemManagerFactory().createWorkItemManager(this.getKnowledgeRuntime()); Map<String, Object> params = new HashMap<String, Object>(); params.put("ksession", this.getKnowledgeRuntime()); Map<String, WorkItemHandler> workItemHandlers = config.getWorkItemHandlers(params); if (workItemHandlers != null) { for (Map.Entry<String, WorkItemHandler> entry : workItemHandlers.entrySet()) { workItemManager.registerWorkItemHandler(entry.getKey(), entry.getValue()); } } } return workItemManager; }
Example #9
Source File: CamelFileTest.java From jbpm-work-items with Apache License 2.0 | 5 votes |
@Test public void testSingleFileWithHeaders() throws IOException { Set<String> headers = new HashSet<String>(); headers.add("CamelFileName"); FileCamelWorkitemHandler handler = new FileCamelWorkitemHandler(headers); handler.setLogThrownException(true); final String testData = "test-data"; final WorkItem workItem = new WorkItemImpl(); workItem.setParameter("path", tempDir.getAbsolutePath()); workItem.setParameter("payload", testData); workItem.setParameter("CamelFileName", testFile.getName()); WorkItemManager manager = new DefaultWorkItemManager(null); handler.executeWorkItem(workItem, manager); Assert.assertTrue("Expected file does not exist.", testFile.exists()); String resultText = FileUtils.readFileToString(testFile, StandardCharsets.UTF_8); Assert.assertEquals(resultText, testData); }
Example #10
Source File: ArchiveWorkItemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { String archive = (String) workItem.getParameter("Archive"); List<File> files = (List<File>) workItem.getParameter("Files"); try { RequiredParameterValidator.validate(this.getClass(), workItem); OutputStream outputStream = new FileOutputStream(new File(archive)); ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", outputStream); if (files != null) { for (File file : files) { final TarArchiveEntry entry = new TarArchiveEntry("testdata/test1.xml"); entry.setModTime(0); entry.setSize(file.length()); entry.setUserId(0); entry.setGroupId(0); entry.setMode(0100000); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file), os); } } os.closeArchiveEntry(); os.close(); manager.completeWorkItem(workItem.getId(), null); } catch (Exception e) { handleException(e); manager.abortWorkItem(workItem.getId()); } }
Example #11
Source File: JPAWorkItemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 5 votes |
@Test(expected = WorkItemHandlerRuntimeException.class) public void queryWithParameterActionTestInvalidParams() throws Exception { WorkItemManager manager = new TestWorkItemManager(); String DESC = "Cheese"; Product p1 = new Product("Bread", 2f); Product p2 = new Product("Milk", 3f); Product p3 = new Product(DESC, 5f); create(p1); create(p2); create(p3); WorkItemImpl workItem = new WorkItemImpl(); Map<String, Object> params = new HashMap<>(); UserTransaction ut = getUserTransaction(); ut.begin(); handler.executeWorkItem(workItem, manager); ut.commit(); assertNotNull(((TestWorkItemManager) manager).getResults()); assertEquals(0, ((TestWorkItemManager) manager).getResults().size()); }
Example #12
Source File: ParserWorkItemHandlerTest.java From jbpm-work-items with Apache License 2.0 | 5 votes |
@Test(expected = WorkItemHandlerRuntimeException.class) public void testXmlToObjectInvalidParams() { WorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); handler.executeWorkItem(workItem, manager); Map<String, Object> results = ((TestWorkItemManager) manager).getResults(workItem.getId()); assertNotNull(results); assertEquals(0, results); }
Example #13
Source File: EthereumUtils.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public static void observeContractEvent(Web3j web3j, String contractEventName, String contractAddress, List<TypeReference<?>> indexedParameters, List<TypeReference<?>> nonIndexedParameters, String eventReturnType, KieSession kieSession, String signalName, boolean doAbortOnUpdate, WorkItemManager workItemManager, WorkItem workItem) { Event event = new Event(contractEventName, indexedParameters, nonIndexedParameters); EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, contractAddress); filter.addSingleTopic(EventEncoder.encode(event)); Class<Type> type = (Class<Type>) AbiTypes.getType(eventReturnType); TypeReference<Type> typeRef = TypeReference.create(type); web3j.ethLogObservable(filter).subscribe( eventTrigger -> { kieSession.signalEvent(signalName, FunctionReturnDecoder.decode( eventTrigger.getData(), Arrays.asList(typeRef)).get(0).getValue()); if (doAbortOnUpdate) { workItemManager.completeWorkItem(workItem.getId(), null); } } ); }
Example #14
Source File: DownloadFileWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
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 #15
Source File: CreateGistWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); Document content = (Document) workItem.getParameter("Content"); String description = (String) workItem.getParameter("Description"); String isPublicStr = (String) workItem.getParameter("IsPublic"); Map<String, Object> results = new HashMap<String, Object>(); GistService gistService = auth.getGistService(this.userName, this.password); Gist gist = new Gist(); gist.setPublic(Boolean.parseBoolean(isPublicStr)); gist.setDescription(description); GistFile file = new GistFile(); file.setContent(new String(content.getContent(), StandardCharsets.UTF_8)); file.setFilename(content.getName()); gist.setFiles(Collections.singletonMap(file.getFilename(), file)); gist = gistService.createGist(gist); results.put(RESULTS_VALUE, gist.getHtmlUrl()); workItemManager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { handleException(e); } }
Example #16
Source File: JqlSearchWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); String jqlQuery = (String) workItem.getParameter("SearchQuery"); if (auth == null) { auth = new JiraAuth(userName, password, repoURI); } Map<String, Object> results = new HashMap<String, Object>(); Map<String, String> resultIssues = new HashMap<>(); NullProgressMonitor progressMonitor = new NullProgressMonitor(); SearchResult searchResult = auth.getSearchRestClient().searchJql(jqlQuery, progressMonitor); Iterable<BasicIssue> foundIssues = searchResult.getIssues(); for (BasicIssue issue : foundIssues) { resultIssues.put(issue.getKey(), issue.getSelf().toURL().toString()); } results.put(RESULTS_VALUE, resultIssues); workItemManager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { logger.error("Error executing workitem: " + e.getMessage()); handleException(e); } }
Example #17
Source File: UIWorkItemHandler.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public void complete(WorkItem workItem, Map<String, Object> results) { WorkItemManager manager = workItems.get(workItem); if (manager != null) { manager.completeWorkItem(workItem.getId(), results); workItems.remove(workItem); reloadWorkItemsList(); } selectButton.setEnabled(getSelectedWorkItem() != null); }
Example #18
Source File: UpdateVideoMetadataWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); String videoEndPoint = (String) workItem.getParameter("VideoEndpoint"); String name = (String) workItem.getParameter("Name"); String description = (String) workItem.getParameter("Description"); String license = (String) workItem.getParameter("License"); String privacyView = (String) workItem.getParameter("PrivacyView"); String privacyEmbed = (String) workItem.getParameter("PrivacyEmbed"); String reviewLink = (String) workItem.getParameter("ReviewLink"); Vimeo vimeo = (Vimeo) workItem.getParameter("Vimeo"); Map<String, Object> results = new HashMap<>(); if (vimeo == null) { vimeo = new Vimeo(accessToken); } VimeoResponse vimeoResponse = vimeo.updateVideoMetadata(videoEndPoint, name, description, license, privacyView, privacyEmbed, Boolean.parseBoolean(reviewLink)); results.put(RESULT, vimeoResponse.getStatusCode()); workItemManager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { handleException(e); } }
Example #19
Source File: UIWorkItemHandler.java From kogito-runtimes with Apache License 2.0 | 5 votes |
public void abort(WorkItem workItem) { WorkItemManager manager = workItems.get(workItem); if (manager != null) { manager.abortWorkItem(workItem.getId()); workItems.remove(workItem); reloadWorkItemsList(); } selectButton.setEnabled(getSelectedWorkItem() != null); }
Example #20
Source File: TransformWorkItemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); Object in = workItem.getParameter(INPUT_KEY); String outputType = (String) workItem.getParameter(OUTPUT_TYPE_KEY); Object output = Class.forName(outputType).getDeclaredConstructor().newInstance(); Method txMethod = this.findTransform(output.getClass(), in.getClass()); if (txMethod != null) { Object out = txMethod.invoke(null, in); Map<String, Object> result = new HashMap<String, Object>(); result.put(VARIABLE_OUTPUT_NAME, out); manager.completeWorkItem(workItem.getId(), result); } else { logger.error("Failed to find a transform "); } } catch (Exception e) { handleException(e); } }
Example #21
Source File: SendMailWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { String paramTo = (String) workItem.getParameter("To"); String paramFrom = (String) workItem.getParameter("From"); String paramSubject = (String) workItem.getParameter("Subject"); String paramBodyText = (String) workItem.getParameter("BodyText"); Document paramAttachment = (Document) workItem.getParameter("Attachment"); try { RequiredParameterValidator.validate(this.getClass(), workItem); Gmail gmailService = auth.getGmailService(appName, clientSecret); Message outEmailMessage = sendMessage(gmailService, paramTo, paramFrom, paramSubject, paramBodyText, paramAttachment); workItemManager.completeWorkItem(workItem.getId(), outEmailMessage); } catch (Exception e) { handleException(e); } }
Example #22
Source File: GetApplicationsWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); String appids = (String) workItem.getParameter("AppIds"); List<OktaApplication> retAppList = new ArrayList<>(); ApplicationList appList = oktaClient.listApplications(); if (appids != null && appids.length() > 0) { List<String> appidsList = Arrays.asList(appids.split(",")); appList.stream() .filter(app -> appidsList.contains(app.getId())) .forEach(app -> retAppList.add(new OktaApplication(app))); } else { // get all appList.stream().forEach(app -> retAppList.add(new OktaApplication(app))); } Map<String, Object> results = new HashMap<>(); results.put(RESULTS_VALUE, retAppList); workItemManager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { handleException(e); } }
Example #23
Source File: CamelFtpTest.java From jbpm-work-items with Apache License 2.0 | 5 votes |
@Test public void testFtp() throws IOException { FTPCamelWorkitemHandler handler = new FTPCamelWorkitemHandler(); final String testData = "test-data"; final WorkItem workItem = new WorkItemImpl(); workItem.setParameter("username", USER); workItem.setParameter("password", PASSWD); workItem.setParameter("hostname", HOST); workItem.setParameter("port", PORT.toString()); workItem.setParameter("directoryname", testFile.getParentFile().getName()); workItem.setParameter("CamelFileName", testFile.getName()); workItem.setParameter("payload", testData); WorkItemManager manager = new DefaultWorkItemManager(null); handler.executeWorkItem(workItem, manager); Assert.assertTrue("Expected file does not exist.", testFile.exists()); String resultText = FileUtils.readFileToString(testFile); Assert.assertEquals(resultText, testData); }
Example #24
Source File: SignallingTaskHandlerDecorator.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@Override public void handleAbortException(Throwable cause, WorkItem workItem, WorkItemManager manager) { if( getAndIncreaseExceptionCount(workItem.getProcessInstanceId()) < exceptionCountLimit ) { workItem.getParameters().put(this.workItemExceptionParameterName, cause); ((org.drools.core.process.instance.WorkItemManager) manager).signalEvent(this.eventType, (org.drools.core.process.instance.WorkItem) workItem, workItem.getProcessInstanceId()); } }
Example #25
Source File: GetBalanceWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
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 #26
Source File: PostMessageToChannelWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { try { String channelName = (String) workItem.getParameter("ChannelName"); String message = (String) workItem.getParameter("Message"); boolean foundChannel = false; ChannelsListResponse channelListResponse = auth.authChannelListRequest(accessToken); List<Channel> channelList = channelListResponse.getChannels(); for (Channel channel : channelList) { if (channel.getName().equals(channelName)) { auth.authChatPostMessageRequest(channel.getId(), accessToken, message); foundChannel = true; } } if (foundChannel) { workItemManager.completeWorkItem(workItem.getId(), null); } else { throw new IllegalArgumentException("Unable to find channel: " + channelName); } } catch (Exception e) { handleException(e); } }
Example #27
Source File: DetectFacesWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 5 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); Document detectionImage = (Document) workItem.getParameter("ImageToDetect"); Map<String, Object> widResults = new HashMap<String, Object>(); VisualRecognition service = auth.getService(apiKey); ByteArrayInputStream imageStream = new ByteArrayInputStream(detectionImage.getContent()); DetectFacesOptions detectFacesOptions = new DetectFacesOptions.Builder() .imagesFile(imageStream) .build(); DetectedFaces result = service.detectFaces(detectFacesOptions).execute(); if (result == null || result.getImages() == null || result.getImages().size() < 1) { logger.error("Unable to detect faces on provided image."); workItemManager.abortWorkItem(workItem.getId()); } else { List<FaceDetectionResult> resultList = new ArrayList<>(); for (ImageWithFaces imageWithFaces : result.getImages()) { for (Face face : imageWithFaces.getFaces()) { resultList.add(new FaceDetectionResult(imageWithFaces, face)); } } widResults.put(RESULT_VALUE, resultList); workItemManager.completeWorkItem(workItem.getId(), widResults); } } catch (Exception e) { handleException(e); } }
Example #28
Source File: CurrentWeatherWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 4 votes |
public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); String cityName = (String) workItem.getParameter("CityName"); String countryCode = (String) workItem.getParameter("CountryCode"); Map<String, Object> results = new HashMap<String, Object>(); CurrentWeatherData cwd = new CurrentWeatherData(); if (owm == null) { owm = new OWM(apiKey); } CurrentWeather currentWeather; if (countryCode == null) { currentWeather = owm.currentWeatherByCityName(cityName); } else { currentWeather = owm.currentWeatherByCityName(cityName, Country.valueOf(countryCode)); } if (currentWeather.hasRespCode() && currentWeather.getRespCode() == 200) { if (currentWeather.hasCityName()) { cwd.setCityName(currentWeather.getCityName()); } if (currentWeather.hasDateTime()) { cwd.setDate(currentWeather.getDateTime()); } if (currentWeather.hasMainData()) { cwd.setTemp(currentWeather.getMainData().getTemp()); cwd.setMinTemp(currentWeather.getMainData().getTempMin()); cwd.setMaxTemp(currentWeather.getMainData().getTempMax()); cwd.setPressure(currentWeather.getMainData().getPressure()); cwd.setHumidity(currentWeather.getMainData().getHumidity()); } if (currentWeather.hasRainData()) { cwd.setPrecipitation(currentWeather.getRainData().getPrecipVol3h()); } if (currentWeather.hasCloudData()) { cwd.setCloud(currentWeather.getCloudData().getCloud()); } if (currentWeather.hasSnowData()) { cwd.setSnow(currentWeather.getSnowData().getSnowVol3h()); } if (currentWeather.hasWindData()) { cwd.setWidDegree(currentWeather.getWindData().getDegree()); cwd.setWindSpeed(currentWeather.getWindData().getSpeed()); cwd.setWindGust(currentWeather.getWindData().getGust()); } if (currentWeather.hassystemData()) { cwd.setSunrise(currentWeather.getSystemData().getSunriseDateTime()); cwd.setSunset(currentWeather.getSystemData().getSunsetDateTime()); } } else { logger.error("Unable to retrieve weather info."); } results.put(RESULTS_VALUES, cwd); workItemManager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { handleException(e); } }
Example #29
Source File: IFTTTWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 4 votes |
public void abortWorkItem(WorkItem wi, WorkItemManager wim) { }
Example #30
Source File: ClassifyImageWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 4 votes |
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); } }