Replace multiple symbols in kotlin string - kotlin

I am trying to construct string from this:
"title": {
"text": "{0} shared a feeling",
"actions": [
{
"text": "User+021122",
"action": "some_action"
}
],
"badgeName": "avatar-5"
}
So i need not to replace {0} with actions[0].text.
I also can have multiple actions and initial text like
"{0} shared a feeling and {1} did nice job"

If I understood correctly, you are getting a given String that represents a message format, and you want to replace placeholders with actual text. You can use Java's MessageFormat to do so:
import java.text.MessageFormat
val pattern = "{0} shared a feeling and {1} did nice job"
val result = MessageFormat.format(pattern, "John", "Carl")
println(result)
This prints:
John shared a feeling and Carl did nice job
Of course, in your case the actual text is coming as part of the JSON, so it's just a matter of extracting the information you need from the JSON (you can use Jackson or Moshi to do so, for example) and then use MessageFormat as described above.

Related

Add Date-Variable to Camunda-BPMN via Rest

I have a camunda bpmn workflow where the start-events required some variables.
One of the needed variable is of type 'date':
{
"variables": {
"stichtagFrist": {
"value": "2021-09-08T00:00:00",
"type": "date"
}
}
}
now trying to add a new Instance having the above mentioned json, I get the following exception:
Cannot instantiate process definition d1f43d8e-211f-11ec-8fdf-0242ac110002: Cannot convert value '2021-09-08T00:00:00' of type 'date' to java type java.util.Date"
How do I need to POST the json that Camunda can interpret it as "date" so that I can use this variable e.g. in timer-events etc.?
Are there any rules for booleans too?
https://github.com/camunda/camunda-bpm-platform/blob/7c5bf37307d3eeac3aee5724b6e4669a9992eaba/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VariableValueDto.java#L109
Uses a Jackson ObjectMapper to parse the value. It requires this format:
{
"variables": {
"stichtagFrist": {
"value": "2021-09-08T00:00:00.0+0000",
"type": "date"
}
}
}
From the documentation:
In the REST API, the type names start with a capital letter, i.e., String instead of string.
Try "Date" instead of "date", that should do the trick.

Using Junit assert on json array of elements fails on first element

I'm trying to use Katalon Studio for some webservice automation. I have been following this guide on how to parse returned Json body using jsonslurper.
https://docs.katalon.com/katalon-studio/tutorials/parse_json_responses.html
Everything is working fine as described in the guide. I wanted to see if I can use junit asserts, specifically the assertEquals() for better error text.
Given we have this
import groovy.json.JsonSlurper
String jsonString = {"menu": {
"id": "file",
"tools": {
"actions": [
{"id": "new", "title": "New File"},
{"id": "open", "title": "Open File"},
{"id": "close", "title": "Close File"}
],
"errors": []
}}}
JsonSlurper slurper = new JsonSlurper()
Map parsedJson = slurper.parseText(jsonString)
def array1 = parsedJson.menu.tools.actions
String onlickValue1 = ""
for(def member : array1) {
assertEquals("Open File", member.title)
break
}
What I'm having trouble with, is that my assert will thrown an error when comparing the very first title element it encounters (which is "New File").
What I intend is to loop through all the elements in the array and assert my expected value against all of them. If my expected value doesn't exist, then I'd fail.
I feel like I'm missing something, because we've done something similar in the past with java, but I just can't see it here.
So I figured out the problem was my inexperience/ignorance. When looking for solutions online I failed to understand with absolute certainty what the code I'm trying to implement is doing. I was using a for.each loop to assert elements in the array against my expected value. Which of course was failing, correctly, for every element that didn't match my expected value. So I made it work by adding an if statement as below:
String expectedValue = ''
for(def member : array1) {
if (member.title=="Open File")
{
expectedValue = member.title
}
break
}
assertEquals("Open File", member.title)
Also a simpler way I discovered is to use assertJ in the following way
assertThat(member).contains("Open File")
I understand there are better solutions to achieve what I'm trying to do. But for purposes of this question I considered it solved.

Key construction in Tink for KeysetHandle

The following lines show how to generate a key in Tink:
keysetHandle=KeysetHandle.generateNew(AeadKeyTemplates.AES128_GCM)
privateKeysetHandle = KeysetHandle.generateNew(SignatureKeyTemplates.ECDSA_P256)
Could you show me how to construct a key given the parameters such as key bytes and related parameters?
It is also possible to create a key by loading the parameters from JSON:
String keysetFilename = "my_keyset.json";
KeysetHandle keysetHandle = CleartextKeysetHandle.read(
JsonKeysetReader.withFile(new File(keysetFilename)));
How is the key format in JSON defined?
Maarten Bodewes: would you mind tell us what wrong with the APIs, and how you think it should be changed? We're all ears for feedback.
Ursa Major: we don't want users to deal with keys directly, because it's easy to mess up. It's why we provide APIs that generate, persist and load keys. The Java HOWTO [1] shows how to do this.
It looks like you have an existing key, in some other format, that you want to use it with Tink. Tink's keys are stored in protobuf. Each key type is defined in its own protobuf. You can find all definitions at https://github.com/google/tink/tree/master/proto. Tink doesn't work with individual keys, but keysets which are also protobuf. You can convert existing keys to Tink's keysets by providing an implementation of KeysetReader. SignaturePemKeysetReader [2] is an example that converts certain PEM keys to Tink.
If you encounter any further issue, feel free to comment or email the mailing list at tink-users#googlegroups.com.
Hope that helps,
Thai.
[1] https://github.com/google/tink/blob/master/docs/JAVA-HOWTO.md
[2] https://github.com/google/tink/blob/master/java_src/src/main/java/com/google/crypto/tink/signature/SignaturePemKeysetReader.java
edit: update the second link.
I've had a similar problem, but with HMAC in unit tests. Hope it helps.
Example JSON:
{
"primaryKeyId": 2061245617,
"key": [{
"keyData": {
"typeUrl": "type.googleapis.com/google.crypto.tink.HmacKey",
"keyMaterialType": "SYMMETRIC",
"value": "EgQIAxAgGiB9qbGjo1sA41kHHKbELAKmFzj3cNev0GJ3PpvhR00vuw=="
},
"outputPrefixType": "TINK",
"keyId": 2061245617,
"status": "ENABLED"
}]
}
code used to generate it (Scala):
import com.google.crypto.tink.mac.MacConfig
MacConfig.register()
def generate(): Unit = {
import java.io.ByteArrayOutputStream
import java.nio.charset.StandardCharsets
import com.google.crypto.tink.mac.HmacKeyManager
import com.google.crypto.tink.{CleartextKeysetHandle, JsonKeysetWriter, KeysetHandle}
val generatedKeyset = KeysetHandle.generateNew(HmacKeyManager.hmacSha256Template())
val output = new ByteArrayOutputStream
CleartextKeysetHandle.write(generatedKeyset, JsonKeysetWriter.withOutputStream(output))
println(output.toString(StandardCharsets.UTF_8))
}
generate()
Loading the JSON and usage:
import com.google.crypto.tink.{CleartextKeysetHandle, JsonKeysetReader}
val hmacKeyset = CleartextKeysetHandle.read(
JsonKeysetReader.withString(...)
)
val mac = hmacKeyset.getPrimitive(classOf[Mac])
mac.computeMac(...)
Keep in mind this is totally insecure and should never be used outside tests.
Relevant parts of the implementation:
JsonKeysetReader.keyFromJson
hmac.proto
MacIntegrationTest
EDIT:
Even easier way to generate a keyset JSON:
$ tinkey create-keyset --key-template HMAC_SHA256_256BITTAG
{
"primaryKeyId": 1132518908,
"key": [{
"keyData": {
"typeUrl": "type.googleapis.com/google.crypto.tink.HmacKey",
"keyMaterialType": "SYMMETRIC",
"value": "EgQIAxAgGiDwIucBpWJ8WHVIEKIdEVQlfynm+4QS8sKUVUga2JzRlw=="
},
"outputPrefixType": "TINK",
"keyId": 1132518908,
"status": "ENABLED"
}]
}

How do I use JSONSchema to accept any object string value, regardless of its key?

I have a system that is receiving JSON messages which contain metadata from a static analysis of a file. The names of these fields are dynamically generated from the scan and can be any valid string, but the value is always a valid string.
e.g.
{
"filename": "hello.txt",
...
"meta": {
"some file property": "any string",
"some other file property": "another string",
...
}
}
I have no way of knowing what the keys in meta will be before receiving the message, nor do I know how many keys there will be. Is there a way of capturing in a JSONSchema that it doesn't matter what keys are present, so long as their values are always strings?
I think you're looking for additionalProperties
Validation with "additionalProperties" applies only to the child
values of instance names that do not match any names in "properties",
and do not match any regular expression in "patternProperties".
The value of additionalProperties can be a JSON Schema, like so
...
"additionalProperties" : {
"type": "string"
}
...
Feel free to let me know if I've missed anything in my explanation, or ask any further questions.

IBM Worklight - How to construct a JSON object in SQL adapter

To construct a JSON object in a SQL adapter I have tried the following:
{
'PatientID':4,
'FName':'test',
'LName':'test',
'AGE':1,
'DOB':1988-09-01,
'GENDER':'m',
'BG':'A+'
}
However I get an error:
{
"errors": [
"Runtime: Method createSQLStatement was called inside a JavaScript function."
],
"info": [
],
"isSuccessful": false,
"warnings": [
]
}
Full size image
First, in the "Invoke Procedure Data" window for your adapter, don't wrap the object in quotes. If you do, it will think that the entire thing is a string.
If you remove the beginning and ending quotes then you almost have it correct. The window will take valid JSON objects, but only if all non integers are strings. Since 1988-09-01 is not a valid integer, it must be wrapped in quotes. You should be able to copy/paste this object into the wizard:
{
'PatientID':4,
'FName':'test',
'LName':'test',
'AGE':1,
'DOB':"1988-09-01",
'GENDER':'m',
'BG':'A+'
}
createSQLStatement API should not be used inside of your functions. You it outside of functions, just like tutorial shows (slide 10) http://public.dhe.ibm.com/software/mobile-solutions/worklight/docs/v600/04_03_SQL_adapter_-_Communicating_with_SQL_database.pdf