On Camunda-Spring Integration TaskDefinition is null for active task - java

I have integrated Camunda Engine with Spring in our application. I want to find properties assigned to each active task for the running process instance. I am able to get the task instances with following code
List<Task> tasks = this.taskService.createTaskQuery().processInstanceId("12").list()
but if i cast task object into TaskEntity and then use getTaskDefinition() , I get null.
Other way to get task details is through ProcessDefinitionEntity.getTaskDefinitions() but it also returns null.
How should I get the task detail?

For read properties and documentation attributes use the BPMN Model API.
This example use a elementId for read both.
String processDefinitionId = repositoryService.createProcessDefinitionQuery()
.processDefinitionKey(DEFINITON_KEY).singleResult().getId();
BpmnModelInstance bpmnModelInstance = repositoryService.getBpmnModelInstance(processDefinitionId);
ServiceTask serviceTask = (ServiceTask) bpmnModelInstance.getModelElementById(ELEMENT_ID);
// Documentation, is a collection, but the modeler supports only one attribute
Collection<Documentation> documentations = serviceTask.getDocumentations();
// Properties
Collection<Property> properties = serviceTask.getProperties();

Above answer gave me a hint but didn't solve the problem completely so here is my code which is serving the purpose.
My usertask in .bpmn file looks like:
<bpmn:userTask id="Task_063x95d" name="Tech Task">
<bpmn:documentation>SUCCESS,FAIL</bpmn:documentation>
<bpmn:extensionElements>
<camunda:inputOutput>
<camunda:inputParameter name="language">Java</camunda:inputParameter>
<camunda:outputParameter name="Platform">Linux</camunda:outputParameter>
</camunda:inputOutput>
<camunda:properties>
<camunda:property name="user" value="Test_User" />
</camunda:properties>
</bpmn:extensionElements>
<bpmn:incoming>SequenceFlow_1xjoyjq</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_028pkxo</bpmn:outgoing>
</bpmn:userTask>
I have analysed the .bpmn file and then just rendered its elements with help of below code
// Active tasks for currently running instanceId(input to below code)
List<Task> tasks = this.taskService.createTaskQuery().processInstanceId(instanceId).list();
String documentation= null;
for (Task task : tasks)
{
//This gives [documentation][1] field.
documentation = task.getDescription();
UserTaskImpl modelElementById = (UserTaskImpl) bpmnModelInstance.getModelElementById(tasks.get(0)
.getTaskDefinitionKey());
ExtensionElements childElementsByType2 = modelElementById.getExtensionElements();
Collection<ModelElementInstance> elements = childElementsByType2.getElements();
for (ModelElementInstance elem : elements)
{
//To access all properties.
if (elem instanceof CamundaPropertiesImpl)
{
CamundaPropertiesImpl camundaPropertiesImpl = (CamundaPropertiesImpl) elem;
Collection<CamundaProperty> camundaProperties = camundaPropertiesImpl.getCamundaProperties();
for (CamundaProperty test : camundaProperties)
{
System.out.println("camunda property name :" + test.getCamundaName() + " $ " + test.getCamundaValue());
}
}
else if (elem instanceof CamundaInputOutputImpl)
{
// To access input/output param
CamundaInputOutputImpl camundaInputOutputImpl = (CamundaInputOutputImpl) elem;
for (CamundaInputParameter test : camundaInputOutputImpl.getCamundaInputParameters())
{
log.info("camunda input params name :" + test.getCamundaName() + " $ " + test.getTextContent());
}
for (CamundaOutputParameter test : camundaInputOutputImpl.getCamundaOutputParameters())
{
log.info("camunda output params name :" + test.getCamundaName() + " $ " + test.getTextContent());
}
}
}
}

Related

bitcoinJ get transaction value

I downloaded a lot of blockchain data using https://bitcoin.org, I took some file and I try to analyse it with bitcoinj library.
I would like to get information from every transaction:
-who send bitcoins,
-how much,
-who receive bitcoins.
I use:
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>0.15.10</version>
</dependency>
I have a code:
NetworkParameters np = new MainNetParams();
Context.getOrCreate(MainNetParams.get());
BlockFileLoader loader = new BlockFileLoader(np,List.of(new File("test/resources/blk00450.dat")));
for (Block block : loader) {
for (Transaction tx : block.getTransactions()) {
System.out.println("Transaction ID" + tx.getTxId().toString());
for (TransactionInput ti : tx.getInputs()) {
// how to get wallet addresses of inputs?
}
// this code works for 99% of transactions but for some throws exceptions
for (TransactionOutput to : tx.getOutputs()) {
// sometimes this line throws: org.bitcoinj.script.ScriptException: Cannot cast this script to an address
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
System.out.println("out value:" + to.getValue().toString());
}
}
}
Can you share some snippet that will work for all transactions in the blockchain?
There are at least two type of transaction, P2PKH and P2SH.
Your code would work well with P2PKH, but wouldn not work with P2SH.
You can change the line from:
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
to:
System.out.println("out address:" + to.getAddressFromP2PKHScript(np)!=null?to.getAddressFromP2PKHScript(np):to.getAddressFromP2SH(np));
The API of Bitcoin says the methods getAddressFromP2PKHScript() and getAddressFromP2SH() are deprecated, and I have not find suitable method.
However, P2SH means "Pay to Script Hash", which means it could contain two or more public keys to support multi-signature. Moreover, getAddressFromP2SH() returns only one address, perhaps this is the reason why it is deprecated.
I also wrote a convinient method to check the inputs and outputs of a block:
private void printCoinValueInOut(Block block) {
Coin blockInputSum = Coin.ZERO;
Coin blockOutputSum = Coin.ZERO;
System.out.println("--------------------Block["+block.getHashAsString()+"]------"+block.getPrevBlockHash()+"------------------------");
for(Transaction tx : block.getTransactions()) {
Coin txInputSum = tx.getOutputSum();
Coin txOutputSum = tx.getOutputSum();
blockInputSum = blockInputSum.add(txInputSum);
blockOutputSum = blockOutputSum.add(txOutputSum);
System.out.println("Tx["+tx.getTxId()+"]:\t" + txInputSum + "(satoshi) IN, " + txOutputSum + "(satoshi) OUT.");
}
System.out.println("Block total:\t" + blockInputSum + "(satoshi) IN, " + blockOutputSum + "(satoshi) OUT. \n");
}

How to read all google adwords targeting options using AWQL or Selectors?

For example, I want to read Age Ranges, Genders, Operating Systems, etc, which are supported in google adwords. I want to read the above said targeting options using either AWQL or Selector?
I am able to read those targeting options using ConstantDataService.
AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
ConstantDataServiceInterface constantDataService =
adWordsServices.get(this.session, ConstantDataServiceInterface.class);
AgeRange []ageRanges = constantDataService.getAgeRangeCriterion();
for(AgeRange a : ageRanges) {
System.out.println(a.getId() + " :: " + a.getAgeRangeType() + " :: " + a.getCriterionType() + " :: " + a.getType());
}
But I am unable to apply filters. I saw that I can apply filters if I use AWQL or Selector? I tried the following
AdGroupCriterionServiceInterface adGroupCriterionService =
adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
// Create selector.
SelectorBuilder builder = new SelectorBuilder();
Selector selector = builder
.fields("Id", "AgeRangeType")
.build();
int PAGE_SIZE = 100;
ServiceQuery serviceQuery = new ServiceQuery.Builder().fields(AdGroupCriterionField.Id, AdGroupCriterionField.AgeRangeType).limit(0, PAGE_SIZE).build();
// Set selector paging = the most important change is to set numberResults to 0.
AdGroupCriterionPage page = null;
do {
serviceQuery.nextPage(page);
page = adGroupCriterionService.query(serviceQuery.toString());
if (page.getEntries() != null) {
for (AdGroupCriterion criterion : page.getEntries()) {
System.out.printf("Campaign with name '%s' and ID %d was found.%n", criterion.getAdGroupCriterionType(),
criterion.getCriterion());
}
} else {
System.out.println("No criterion were found.");
}
} while(serviceQuery.hasNext(page));
but not working as expected.
Can someone tell me how to read targeting options using AWQL or Selector?

Softlayer JAVA API sample to get all the configurations for “Hourly/Pre-set Configuration Bare Metal Servers”

I'm trying to get all the configurations for hourly bare metal servers on SoftLayer, but failed. Is there a Java sample for it?
What I want to get is the items like in the following link (DataCenter name, OS list, CPU/GPU list, etc):
https://gist.github.com/bmpotter/a0d9a386d8681bdab456/revisions
I can get the OS reference code list with following codes, but this is the only one that I can get now :)
Hardware.Service hardwareService = Hardware.service(client);
Configuration configuration = hardwareService.getCreateObjectOptions();
List<Option> options = configuration.getOperatingSystems();
for (Option option : options) {
Hardware hardware = option.getTemplate();
String osRefCode = hardware.getOperatingSystemReferenceCode();
System.out.println("osRefCode : " + osRefCode );
}
I cannot get DataCenter name list and other configurations (E.g. cpu count) with following codes:
List<Option> options = configuration.getDatacenters();
for (Option option : options) {
Hardware hardware = option.getTemplate();
String dcName = hardware.getDatacenterName();
System.out.println("dcName : " + dcName );
}
There should be something wrong, but I don't know why.
It will be great if there is a Java Sample codes for this.
Thanks.
I recomend you to debug your code in order to know how you need to access the properties properly, I got some values for you:
List<Option> options2 = configuration.getDatacenters();
for (Option option : options2) {
Hardware hardware = option.getTemplate();
String dcName = hardware.getDatacenter().getName();
System.out.println("dcName : " + dcName );
}
List<Option> options3 = configuration.getProcessors();
for (Option option : options3) {
System.out.println("processors");
System.out.println("item prices");
System.out.println("hourly recurring fee" + option.getItemPrice().getHourlyRecurringFee());
System.out.println("item");
System.out.println("desciption" + option.getItemPrice().getItem().getDescription());
Hardware hardware = option.getTemplate();
System.out.println("Template");
System.out.println("processorCoreAmount : " + hardware.getProcessorCoreAmount() );
System.out.println("memoryCapacity : " + hardware.getMemoryCapacity() );
}
}

How to get client list using SOAP Web Services in Netsuite ERP?

I am really new to SOAP web services and to Netsuite ERP and I am trying to generate a report in my company where I need to obtain all the Clients and their Invoices using the data available in Netsuite ERP. I followed the Java and Axis tutorial they offer with their sample app for the ERP and I successfully created a Java project in Eclipse that consumes the WSDL for netsuite 2015-2 and compiles the needed classes to run the sample app. So, I followed an example found in their CRM exapmle app to obtain a Client's information but the only problem is that their example method needs you to introduce the Client's ID. Here is the sample code:
public int getCustomerList() throws RemoteException,
ExceededUsageLimitFault, UnexpectedErrorFault, InvalidSessionFault,
ExceededRecordCountFault, UnsupportedEncodingException {
// This operation requires a valid session
this.login(true);
// Prompt for list of internalIds and put in an array
_console
.write("\ninternalIds for records to retrieved (separated by commas): ");
String reqKeys = _console.readLn();
String[] internalIds = reqKeys.split(",");
return getCustomerList(internalIds, false);
}
private int getCustomerList(String[] internalIds, boolean isExternal)
throws RemoteException, ExceededUsageLimitFault,
UnexpectedErrorFault, InvalidSessionFault, ExceededRecordCountFault {
// Build an array of RecordRef objects and invoke the getList()
// operation to retrieve these records
RecordRef[] recordRefs = new RecordRef[internalIds.length];
for (int i = 0; i < internalIds.length; i++) {
RecordRef recordRef = new RecordRef();
recordRef.setInternalId(internalIds[i]);
recordRefs[i] = recordRef;
recordRefs[i].setType(RecordType.customer);
}
// Invoke getList() operation
ReadResponseList getResponseList = _port.getList(recordRefs);
// Process response from get() operation
if (!isExternal)
_console.info("\nRecords returned from getList() operation: \n");
int numRecords = 0;
ReadResponse[] getResponses = getResponseList.getReadResponse();
for (int i = 0; i < getResponses.length; i++) {
_console.info("\n Record[" + i + "]: ");
if (!getResponses[i].getStatus().isIsSuccess()) {
_console.errorForRecord(getStatusDetails(getResponses[i]
.getStatus()));
} else {
numRecords++;
Customer customer = (Customer) getResponses[i].getRecord();
_console.info(" internalId="
+ customer.getInternalId()
+ "\n entityId="
+ customer.getEntityId()
+ (customer.getCompanyName() == null ? ""
: ("\n companyName=" + customer
.getCompanyName()))
+ (customer.getEntityStatus() == null ? ""
: ("\n status=" + customer.getEntityStatus().getName()))
+ (customer.getEmail() == null ? ""
: ("\n email=" + customer.getEmail()))
+ (customer.getPhone() == null ? ""
: ("\n phone=" + customer.getPhone()))
+ "\n isInactive="
+ customer.getIsInactive()
+ (customer.getDateCreated() != null ? ""
: ("\n dateCreated=" + customer
.getDateCreated().toString())));
}
}
return numRecords;
}
So as you can see, this method needs the internal ID of each Customer which I find not useful as I have a many Customers and I don't want to pass each Customer's ID. I read their API docs (which I find hard to navigate and kind of useless) and I found a web service called getAll() that gives all the records given a getAllRecord object which requires a getAllRecordType object. However, the getAllRecordType object does not support Customer entities, so I can't obtain all the customers on the ERP this way.
Is there an easy way to obtain all the Customers in my Netsuite ERP (maybe using other thing rather than the SOAP Web Services they offer? I am desperate about this situation as understanding how Netsuite's Web Services API has been really troublesome.
Thanks!
You would normally use a search to select a list of customers. On a large account you would not normally get all customers on any regular basis. If you are trying to get the invoices you might just find it more practical to get those with a search.
You wrote "in your company". Are you trying to write an application of some sort? If this is an internal project (and even if it's not) you'll probably find using SuiteScripts much more efficient in terms of your time and frustration level.
I made it using the following code on my getCustomerList method:
CustomerSearch customerSrch = new CustomerSearch();
SearchResult searchResult = _port.search(customerSrch);
System.out.println(searchResult.getTotalRecords());
RecordList rl = searchResult.getRecordList();
for (int i = 0; i <searchResult.getTotalRecords()-1; i++) {
Record r = rl.getRecord(i);
System.out.println("Customer # " + i);
Customer testcust = (Customer)r;
System.out.println("First Name: " + testcust.getFirstName());
}

Apache Commons - NNTP - "Article To List" - AWT

I am currently using Apache Commons Net to develop my own NNTP reader. Using the tutorial available I was able to use some of their code to allow me to get articles back.
The Code I am using from NNTP Section -
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
I need to take the articles and turn them into a List type so I can send them to AWT using something like this -
List x = (List) b.GetGroupList(dog);
f.add(CreateList(x));
My Entire code Base for this section is -
public void GetThreadList(String Search) throws SocketException, IOException {
String hostname = USE_NET_HOST;
String newsgroup = Search;
NNTPClient client = new NNTPClient();
client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
client.connect(hostname);
client.authenticate(USER_NAME, PASS_WORD);
if(!client.authenticate(USER_NAME, PASS_WORD)) {
System.out.println("Authentication failed for user " + USER_NAME + "!");
System.exit(1);
}
String fmt[] = client.listOverviewFmt();
if (fmt != null) {
System.out.println("LIST OVERVIEW.FMT:");
for(String s : fmt) {
System.out.println(s);
}
} else {
System.out.println("Failed to get OVERVIEW.FMT");
}
NewsgroupInfo group = new NewsgroupInfo();
client.selectNewsgroup(newsgroup, group);
long lowArticleNumber = group.getFirstArticleLong();
long highArticleNumber = lowArticleNumber + 5000;
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
try {
if (client.isConnected()) {
client.disconnect();
}
}
catch (IOException e) {
System.err.println("Error disconnecting from server.");
e.printStackTrace();
}
}
and -
public void CreateFrame() throws SocketException, IOException {
// Make a new program view
Frame f = new Frame("NNTP Reader");
// Pick my layout
f.setLayout(new GridLayout());
// Set the size
f.setSize(H_SIZE, V_SIZE);
// Make it resizable
f.setResizable(true);
//Create the menubar
f.setMenuBar(CreateMenu());
// Create the lists
UseNetController b = new UseNetController(NEWS_SERVER_CREDS);
String dog = "*";
List x = (List) b.GetGroupList(dog);
f.add(CreateList(x));
//f.add(CreateList(y));
// Add Listeners
f = CreateListeners(f);
// Show the program
f.setVisible(true);
}
I just want to take my list of returned news articles and send them to the display in AWT. Can any one explain to me how to turn those Articles into a list?
Welcome to the DIY newsreader club. I'm not sure if you are trying to get a list of newsgroups on the server, or articles.You have already have your Articles in an Iterable Collection. Iterate through it appending what you want in the list from each article. You probably aren't going to want to display the whole article body in a list view. More likely the message id, subject, author or date (or combination as a string). For example for a List of just subjects:
...
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
Iterator<Article> it = articles.iterator();
while(it.hasNext()) {
Article thisone = it.next();
MyList.add(thisone.getSubject());
//MyList should have been declared up there somewhere ^^^ and
//your GetThreadList method must include List in the declaration
}
return MyList;
...
My strategy has been to retrieve the articles via an iterator in to an SQLite database with the body, subject, references etc. stored in fields. Then you can create a list sorted just how you want, with a link by primary key to retrieve what you need for individual articles as you display them. Another strategy would be an array of message_ids or article numbers and fetch each one individually from the news server as required. Have fun - particularly when you are coding for Android and want to display a list of threaded messages in the correct sequence with suitable indents and markers ;). In fact, you can learn a lot by looking at the open source Groundhog newsreader project (to which I am eternally grateful).
http://bazaar.launchpad.net/~juanjux/groundhog/trunk/files/head:/GroundhogReader/src/com/almarsoft/GroundhogReader

Categories