What is the right way to save the process instance id(s) created? - bpmn

Using Camunda as the tool for orchestration of the microservices. At later time, I find the process_instances_id generated necessary for continuing a particular process by using it in messageEventReceived(). Code as follows:
val processid = getProcessID(key1, key2)
val runtimeService = processengine.getRuntimeService
val subscription = runtimeService.createEventSubscriptionQuery
.eventType("message")
.eventName(eventname)
.processInstanceId(executionid)
.singleResult
runtimeService.messageEventReceived(subscription.getEventName, subscription.getExecutionId)
As of this moment the processid is saved and then retrieved from the database using the getProcessID(...) function when necessary. Is this proper?
Does camunda already have the list of process_ids in its own database? If so, how do I retrieve a particular process instance id just giving composite key(s)? Is that even possible?

It is the common way. You can also use the public api to get the process instance and his id via the process definition key.
See the following example from the documentation:
runtimeService.createProcessInstanceQuery()
.processDefinitionKey("invoice")
.list();
For your given example there is also a simpler way. It is possible to correlate the message via the runtime service.
See this example from the documenation:
runtimeService.createMessageCorrelation("messageName")
.processInstanceBusinessKey("AB-123")
.setVariable("payment_type", "creditCard")
.correlate();

You can use
runtimeService.createProcessInstanceQuery().list();
the query supports fluent criteria for filtering, for example on process_key, variables, businessKey ...

Related

How to use numeric chat IDs to avoid expensive `get_entity(channel_name)` calls?

As per this comment, I'm trying to use numeric channel IDs in my telethon code, so that I don't end up spamming the Telegram API with expensive name lookup calls and getting throttled, but I'm having some difficulty.
e.g. assuming I've already instantiated and connected client:
messages = client.get_messages(numeric_channel_id)
...fails with this error:
ValueError: Could not find the input entity for PeerUser(user_id=[numeric_channel_id]) (PeerUser)
I think there's some cacheing going on, because if I do a get_entity call using the account name first, then the get_messages call works. i.e. something like this:
client.get_entity(channel_name_which_belongs_to_numeric_channel_id)
messages = client.get_messages(numeric_channel_id)
That works just fine, but now I'm doing the expensive get_entity(name) call which is what I'm trying to avoid (because it will result in FloodWaitError problems).
Is there any way I can use the numeric ID of a channel to avoid the expensive get_entity call, in this scenario?
I've also tried forcing the entity type to Channel, like this:
channel = Channel(id=numeric_channel_id, title=None, photo=None, date=None)
messages = client.get_messages(channel)
...but the results are the same, except that the error mentions PeerChannel rather than PeerUser
ID usage is not going to work unless you cached the target as you stated, that's the only way to use the integer id.
you must have met the entity from events or manual requests (say, username fetching).
you should be using client.get_input_entity('username')
it will try to search the local cache first for the saved id + hash that equals the passed username, if found it won't do ResolveUsername (heavy one) and use the local access_hash + id and return you an inputPeer. you pass that to any request you want.
you mustn't use id alone unless you're certain you have met its holder, in other words, id you use has to be something you found out from within the library and within the same session, not something you knew/found out externally.
There is no magical way to fetch something with id you claim you know, if you actually know it, the lib has to create (when the access_hash is present) an InputPeer
As the other answer states, fetching by username will always work but is expensive. However note that such a call will fill the cache so it can later be fetched again much more cheaply by ID.
If you really need a stable reference to some entity and cannot rely on the session cache, and want to avoid usernames, the documentation for Entities vs. Input Entities may be helpful.
What it boils down to is, you can do this:
print(await client.get_input_entity('username'))
...which will show something like:
InputPeerChannel(channel_id=1066197625, access_hash=-6302373944955169144)
...and then, the account that made the get_input_entity call will always be able to use the printed result, without the need for it to be in cache:
from telethon.tl.types import InputPeerChannel
USERNAME = InputPeerChannel(channel_id=1066197625, access_hash=-6302373944955169144)
# ...
await client.send_message(USERNAME, 'Hi') # works without cache

How to query Sagas stored in SQL Persistence table

I need to query a property of Saga Data class to get a list. It is stored on SqlPersistance table [Data] column as a serialized object.
Think about a scenario that my SagaData has a property called UserName, so I want to query every saga related to that user.
In a sloppy way, I can query the column content, get the list and can create Saga objects out of the content, by querying like:
SELECT [Id]
,[Correlation_TaskId]
,[Metadata]
,[Data]
,[PersistenceVersion]
,[SagaTypeVersion]
,[Concurrency]
FROM [myWonderfulDb].[dbo].[MyWonderfulPeristanceTable]
where JSON_VALUE(Data,'$.Username') = 'arthur'
but I am looking for an elegant way to do it by possibly using NserviceBus API's.
There is a SagaFinder implementation described in ParticularSoftware documentation (link: https://docs.particular.net/persistence/sql/saga-finder) but this returns only one object which does not perfectly fit into my scenario.
Here how it is implemented in the documentation:
class SqlServerSagaFinder :
IFindSagas<MySagaData>.Using<MyMessage>
{
public Task<MySagaData> FindBy(MyMessage message, SynchronizedStorageSession session, ReadOnlyContextBag context)
{
return session.GetSagaData<MySagaData>(
context: context,
whereClause: "JSON_VALUE(Data,'$.PropertyPathInJson') = #propertyValue",
appendParameters: (builder, append) =>
{
var parameter = builder();
parameter.ParameterName = "propertyValue";
parameter.Value = message.PropertyValue;
append(parameter);
});
}
}
Any ideas appreciated. Thank you!
We have guidance about querying saga state available at
https://docs.particular.net/nservicebus/sagas/#querying-saga-data
In short, you can query the saga data, there is no out of the box way provided by NServiceBus because we recommend using a different approach instead:
the saga to publish events containing the required data and have handlers that process these events and store the data in one or more read model(s) for querying purposes.
The major points why we don't recommend it is in my viewpoint these two
By exposing the data outside of the safeguards of the business logic in the saga the risk is that the data is not treated as
read-only. Eventually, a component tries to bypass the saga and
directly modify the data.
Querying the data might require additional indexes, resources etc. which need to be managed by the component issuing the query.
Those additional resources can influence saga performance.
The only purpose of the SagaFinder is to find a single instance of a certain saga that correlates with the incoming message. I'm not aware of any framework functionalities to query saga (data) instances.

ORM for Spring-MongoDB integration with native querying support

I am a new to using Mongo DB and exploring the frameworks around for migrating from mysql to mongodb. So far from my findings I have been able to figure out SpringMongo as the best solution to my requirements.
The only problem is that instead of using a DSL based or abstract querying mechanism, I wished the framework allowed me to pass plain json string as arguments to the different methods exposed by the API(find, findOne) so that the query parameters can be written out to an external file (using a key to refer) and passed to the methods by reading and parsing at run time. But the framework should be capable of mapping the results to the domain objects.
Is there a way in spring-mongo to achieve this? Or is there any other frameworks on the same lines
You could use Spring Data to do that, just use the BasicQuery class instead of Query class. Your code will look like the following:
/* Any arbitrary string that could to parsed to DBObject */
Query q = new BasicQuery("{ filter : true }");
List<Entity> entities = this.template.find(q, Entity.class);
If you want more details:
http://static.springsource.org/spring-data/data-mongo/docs/current/reference/html/#mongo.query
http://static.springsource.org/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/query/BasicQuery.html
Well I got to find this one in the Spring data MongoOperations...
String jsonCommand = "{username: 'mickey'}";
MongoOperations mongoOps = //get mongooperations implemantation
mongoOps.executeCommand(jsonCommand)
It returns an instance of CommandResult that encapsulates the result.

Native Query Mapping on the fly openJPA

I am wondering if it is possible to map a named native query on the fly instead of getting back a list of Object[] and then looping through and setting up the object that way. I have a call which I know ill return a massive data set and I want to be able to map it right to my entity. Can I do that or will I have to continue looping through the result set.
Here is what I am doing now...
List<Provider> ObjList = (List<Provider>) emf.createNativeQuery(assembleQuery(organizationIDs, 5)).getResultList();
That is my entity, the List (my entity is the provider). Normally I would just return a List<Object[]>
and then I would loop through that to get back all the objects and set them up as new providers and add them to a list....
//List<Provider> provList = new ArrayList<Provider>();
/*for(Object[] obj: ObjList)
{
provList.add(this.GetProviderFromObj(obj));
}*/
As you can see I commented that section of the code out to try this out. I know you can map named native queries if you put your native query in the entity itself and then call it via createNamedQuery. I would do it that way, but I need to use the IN oracle keyword because I have a list of ID's that I want to check against. It is not just one that is needed. And as we all know, native queruies don't handle the in keyword to well. Any advice?
Sigh, If only the IN keyword was supported well for NamedNativeQueries.
Assuming that Provider is configured as a JPA entity, you should be able to specify the class as the second parameter to your createNativeQuery call. For example:
List<Provider> ObjList = (List<Provider>) emf.createNativeQuery(assembleQuery(organizationIDs, 5), Provider.class).getResultList();
According to the documentation, "At a minimum, your SQL must select the class' primary key columns, discriminator column (if mapped), and version column (also if mapped)."
See the OpenJPA documentation for more details.

Tridion 2011 - Engine.GetObject overloads

I found the following difference between the old VBScript API and the .Net API:
In the old VBScript API it's possible to invoke "TDSE.getObject" to retrieve a Tridion object passing by the webdav path, an integer to select how to open it (read only, read and write, etc) and the ID of the publication where there is the exact element of the blueprint we want.
In the new .Net API all I found was "Engine.GetObject" but it only receives the TCM ID or the webdav path of an element.
Our scenario is the following; in the old VBScript code, this overload of the getObject method was used to avoid some permission issues detected while using TCM IDs instead of the webdav paths and because it's much more handful when you need to copy the code between different environments (see DEV, PREPROD and PROD for example), avoiding changing TCM IDs.
So my questions are:
Is there and overload like the old one in the new .Net API?
If not, is there a way of retrieving items by webdav keeping in mind that some of them could be localized and changed from their parent? (the old way works with this, if you send the root webdav path it will retrieve local objects even if their names aren't exactly the same as the parents)
Thank you!
Do you want to be able to use the webdav url of the top-level item, and specify the publication id from which to get the item?
I would create an extension method on Engine that does this for you:
public static T GetObject<T>(this Engine engine, string webDavUrl, int publicationId)
where T : IdentifiableObject
{
[logic to retreive the item and then if needed
get the correct tcm uri and get the intended item]
return item as T;
}
However, this is quite an expensive operation since you get two objects instead of one. So I dont know if I would use this method very often.
Here some samples
IdentifiableObject item = engine.GetObject(new TcmUri("tcm:5-677"));
//will give you the latest approved version in the publication 5.
IdentifiableObject item = engine.GetObject(new TcmUri("tcm:5-677-v0"));
//will give you the WF or Editable version.
TcmUri uri = new TcmUri("tcm:5-677");
uri.PublicationId = 6;
IdentifiableObject item = engine.GetObject(uri);
//will give you the latest approved version in the publication 6.
Engine.GetObject has 4 overloaded method.
GetObject(Session, string)
GetObject(string)
GetObject(TcmUri)
GetObject(Item)
You can check the Tom.Net Api for more details.
Actually, using Engine.GetObject Method (String) should work.
public virtual IdentifiableObject GetObject(
string itemUriOrWebDavUrl
)
You can do something in this way:-
Get the Object based on WebDav URL
Get the TCM ID from this object
Based on your publication, modified your TCM ID accordingly and do your stuff
OR
Try something this way too:-
Repository testRepository = (Repository)session.GetObject("tcm:0-2-1");
Component testComponent = (Component)testRepository.GetObject(webdavURL); //Assuming actual TCM ID is "tcm:1-3"
Console.WriteLine(testComponent.Id); // should show "tcm:2-3"
// Do Your Other Stuff