converting jira json string to java object - java

How can i convert jira json string to java object i want to get the issue details
{
"expand": "schema,names",
"startAt": 0,
"maxResults": 50,
"total": 1,
"issues": [
{
"expand": "editmeta,renderedFields,transitions,changelog,operations",
"id": "10000",
"self": "http://jira.com/rest/api/2/issue/10000",
"key": "APPANLYTIX-1",
"fields": {},
"issuetype": {},
"votes": {},
"resolution": null,
"fixVersions": [{}],
"resolutiondate": null,
"timespent": null,
"reporter": {
"avatarUrls": {},
"displayName": "yyyy Dev",
"active": true
},
"subtasks": [],
"status": {},
"labels": [],
"workratio": 0,
"assignee": {
"avatarUrls": {},
"displayName": "",
"active": true
},
"project": {
"name": "",
"avatarUrls": { }
},
"versions": [{}],
"environment": "windows",
"timeestimate": 28800,
"aggregateprogress": {},
"lastViewed": "2013-07-18T04:39:52.596+0000",
"components": [ ],
"timeoriginalestimate": 28800,
"aggregatetimespent": null
}
]
}
Most of the examples I refereed are using java bean for setting the variables,is there any API for doing this?

If your class has a structure like the json you've showed you can use use the gson library to bind it to the class.

I handle this problem another third party library, you can download this code. And Edit as your scenario.
You should only edit SimpleConfigurationProvider this java class.
You have to specify your privateKey, AccessToken and baseUrl. And then jiraClient Authentication you can receive project and issue thanks to under code block
As a result you can convert java class object as ArrayList and JiraProject[]
https://github.com/symphonyoss/bot-jira
public static void main(String[] args) {
// TODO Auto-generated method stub
JiraOauthClient jiraClient = new JiraOauthClient(new SimpleConfigurationProvider());
JiraProject[] projects = jiraClient.getAllProjects();
for (JiraProject project : projects) {
if (project.getKey().equals("UOCM")) {
ArrayList<JiraIssue> issues = jiraClient.getIssuesForProject(project);
for (JiraIssue issue : issues) {
System.out.println(issue.getId());
///.....
}
}
}
}

Related

Create N number of GCP compute instances using Rest api

How to create n number of instances in GCP using rest api.
in AWS java SDK, there is a method withMaxCount where we specify number of ec2 instances.
Similarly is there anything for GCP compute.
You can use REST API in loop to create instances.
Example request will look something like this:
{
"kind": "compute#instance",
"name": "INSTANCE-NAME",
"zone": "projects/PROJECT-NAME/zones/us-central1-a",
"machineType": "projects/PROJECT-NAME/zones/us-central1-a/machineTypes/e2-medium",
"displayDevice": {
"enableDisplay": false
},
"metadata": {
"kind": "compute#metadata",
"items": []
},
"tags": {
"items": []
},
"disks": [
{
"kind": "compute#attachedDisk",
"type": "PERSISTENT",
"boot": true,
"mode": "READ_WRITE",
"autoDelete": true,
"deviceName": "INSTANCE-NAME",
"initializeParams": {
"sourceImage": "projects/debian-cloud/global/images/debian-10-buster-v20210122",
"diskType": "projects/PROJECT-NAME/zones/us-central1-a/diskTypes/pd-standard",
"diskSizeGb": "10",
"labels": {}
},
"diskEncryptionKey": {}
}
],
"canIpForward": false,
"networkInterfaces": [
{
"kind": "compute#networkInterface",
"subnetwork": "regions/us-central1/subnetworks/default",
"accessConfigs": [
{
"kind": "compute#accessConfig",
"name": "External NAT",
"type": "ONE_TO_ONE_NAT",
"networkTier": "PREMIUM"
}
],
"aliasIpRanges": []
}
],
"description": "",
"labels": {},
"scheduling": {
"preemptible": false,
"onHostMaintenance": "MIGRATE",
"automaticRestart": true,
"nodeAffinities": []
},
"deletionProtection": false,
"reservationAffinity": {
"consumeReservationType": "ANY_RESERVATION"
},
"serviceAccounts": [
{
"email": "111111111111-compute#developer.gserviceaccount.com",
"scopes": [
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/logging.write",
"https://www.googleapis.com/auth/monitoring.write",
"https://www.googleapis.com/auth/servicecontrol",
"https://www.googleapis.com/auth/service.management.readonly",
"https://www.googleapis.com/auth/trace.append"
]
}
],
"shieldedInstanceConfig": {
"enableSecureBoot": false,
"enableVtpm": true,
"enableIntegrityMonitoring": true
},
"confidentialInstanceConfig": {
"enableConfidentialCompute": false
}
}
Replace it with your own project name and service account, and you can test it here.

Elasticsearch - creating index failure when doing it through java API but not manually

I have a complex index with a ngram analyzer. I want to be able to create a new index through the Java API. I am currently using Kotlin for this but using the same framework. I have created the schema for this index as so:
{
"settings": {
"index": {
"max_ngram_diff": 20,
"search.idle.after": "10m"
},
"analysis": {
"analyzer": {
"ngram3_analyzer": {
"tokenizer": "ngram3_tokenizer",
"filter": [
"lowercase"
]
}
},
"tokenizer": {
"ngram3_tokenizer": {
"type": "ngram",
"min_gram": 3,
"max_gram": 20
}
}
}
},
"mappings": {
"dynamic": "strict",
"_doc": {
"properties": {
"name": {
"type": "keyword",
"fields": {
"partial": {
"type": "text",
"analyzer": "ngram3_analyzer",
"search_analyzer": "keyword"
},
"text": {
"type": "text"
}
}
},
"location": {
"type": "geo_shape",
"ignore_malformed": true
},
"type": {
"type": "keyword"
},
"sort": {
"type": "integer"
}
}
}
}
}
This json schema works when manually passing it via a rest client PUT call.
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "new_index_created"
}
Passing the same schema via elastic java API using the following koltin function:
private fun createIndex(index: String, schema: String) {
val createIndexRequest = CreateIndexRequest(index).mapping(schema, XContentType.JSON)
getClient().indices().create(createIndexRequest, RequestOptions.DEFAULT)
}
I get this response:
Elasticsearch exception [type=mapper_parsing_exception, reason=Failed to parse mapping [_doc]: Root mapping definition has unsupported parameters: [settings : {index={max_ngram_diff=20, search.idle.after=10m}, analysis={analyzer={ngram3_analyzer={filter=[lowercase], tokenizer=ngram3_tokenizer}}, tokenizer={ngram3_tokenizer={min_gram=3, type=ngram, max_gram=20}}}}] [mappings : {_doc={properties={name={type=keyword, fields={text={type=text}, partial={search_analyzer=keyword, analyzer=ngram3_analyzer, type=text}}}, location={ignore_malformed=true, type=geo_shape}, sort={type=integer}, type={type=keyword}}}, dynamic=strict}]]
any help on this issue would be great :)
The error you get is because you're passing both mappings and settings into the mapping(...) call.
You can either call mapping() with only the mappings section and setting() with the settings section, or you can call source() like this:
val createIndexRequest = CreateIndexRequest(index).source(schema, XContentType.JSON)
^
|
change this

How to implement Post API JSON with Spring?

I'm having difficulty implementing a JSON to send as a POST call in Spring.
Which is the fastest and most effective way to turn this json into a java object or a map and make the call?
below is an example of a json to send:
{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "edge-ws"
},
"spec": {
"selector": {
"matchLabels": {
"run": "edge-ws"
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"run": "edge-ws"
}
},
"spec": {
"containers": [
{
"name": "edge-ws",
"image": "server-tim:latest",
"imagePullPolicy": "Never",
"ports": [
{
"containerPort": 80
}
]
}
]
}
}
}
}
this and the second body that has a value (nodeport) that must be taken from a field entered by the user front end side.(page created in html)
{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "edge-ws",
"labels": {
"run": "edge-ws"
}
},
"spec": {
"type": "NodePort",
"ports": [
{
"port": 8080,
"targetPort": 80,
"nodePort": 30200,
"protocol": "TCP",
"name": "http"
}
],
"selector": {
"run": "edge-ws"
}
}
}
Both files must be sent with a single click on a button on the front end side.the first call with the first body starts and if everything is ok the second body starts
What should the class that maps objects look like? What should the controller look like instead?
They also gave me an address to call that can only be used on the machine, how can I test this call locally?
Thanks in advance!
You can use google's Gson library to convert the JsonString to Object and then use below code:
Gson gson = new Gson();
Object requestObject = gson.fromJson(jsonString, Object.class);
ResponseObject responseObject = restTemplate.postForObject(url, requestObject, ResponseObject.class);

Using Groovy collection to exactly match the string format

I have a question about matching the exact string format using the groovy collection.
def createPullRequest(projectSlug, repoSlug, title, description, sourceBranch, targetBranch) {
//this is reading in the array with the user names
def names = BitbutkcetUtil.getGroupUsers(teamName, activeOnly)
def prResponse = this.steps.httpRequest(
acceptType: 'APPLICATION_JSON',
authentication: this.userId,
contentType: 'APPLICATION_JSON',
httpMode: 'POST',
ignoreSslErrors: true,
quiet: true,
requestBody: """
{
"title": "${title}",
"description": "${description}",
"state": "OPEN",
"open": true,
"closed": false,
"fromRef": { "id": "${sourceBranch}" },
"toRef": { "id": "${targetBranch}" },
"locked": false,
"reviewers": [
//I want to replace this hardcoded names with the string values inside the array `names`
{ "user": { "name": "HardCoded1" } },
{ "user": { "name": "HardCoded2" } },
{ "user": { "name": "HardCoded3" } },
{ "user": { "name": "HardCoded4" } }
]
}
""",
responseHandle: 'STRING',
url: "https://bitbucket.absolute.com/rest/api/latest/projects/${projectSlug}/repos/${repoSlug}/pull-requests",
validResponseCodes: '200:299')
def pullRequest = this.steps.readJSON(text: prResponse.content)
prResponse.close()
return pullRequest['id']
}
What I want to do is I want to replace the hardcoded names inside the reviewers with the string elements inside the array names. I want to use the collection but I have to match the exact format
{ "user": { "name": "HardCoded1" } },
{ "user": { "name": "HardCoded2" } },
{ "user": { "name": "HardCoded3" } },
{ "user": { "name": "HardCoded4" } }
Right now, I have [reviewers: names.collect{ [user: [name: it]] }], and it is outputting the following:
[reviewers:[[user:[name:name1]],
[user:[name:name2]],
[user:[name:name3]],
[user:[name:name4]]]]
How can I make it so that the output is in the following format?
"reviewers": [
//I want to replace this hardcoded names with the string values inside the array `names`
{ "user": { "name": "HardCoded1" } },
{ "user": { "name": "HardCoded2" } },
{ "user": { "name": "HardCoded3" } },
{ "user": { "name": "HardCoded4" } }
]
Any help would be greatly appreciated!
What you see is a result of calling toString() method on a list of map elements. For a valid JSON representation, you may pass a result of the collect() method to a JsonOutput.toJSON(). Something like this:
requestBody: """
{
"title": "${title}",
"description": "${description}",
"state": "OPEN",
"open": true,
"closed": false,
"fromRef": { "id": "${sourceBranch}" },
"toRef": { "id": "${targetBranch}" },
"locked": false,
"reviewers": ${JsonOutput.toJson(names.collect{ [user: [name: it]] })}
}
"""
JsonOutput.toJSON() may need script approval when it gets used for the first time in Jenkins Pipeline.

Building JSON programmatically in java

I need to build a below JSON programmatically. But,need a elegant way to convert from Java object to JSON. so that, i can avoid string builder to build the below JSON.
I aware of that, sometimes,I have array of parameters for the specific key while building JSON.
Please share the generic way to solve that.
Please share some thoughts to this.
{
"tropo": [
{
"ask": {
"attempts": 3,
"say": [
{
"value": "Hi.",
"event": "timeout"
},
{
"value": "Hello",
"event": "nomatch:1"
},
{
"value": "Hello2",
"event": "nomatch:2"
},
{
"value": "Satheesh",
"voice": "veronica"
}
],
"choices": {
"value": "Yes(1,Yes),No(2,No)",
"mode": "ANY"
},
"voice": "veronica",
"recognizer": "en-us",
"timeout": 8,
"name": "year",
"minConfidence": 39,
"required": true
}
},
{
"on": {
"next": "https://test.app.com/WAP2/",
"event": "continue"
}
},
{
"on": {
"next": "https://test.app.com/WAP2/",
"event": "incomplete"
}
},
{
"on": {
"next": "",
"event": "hangup"
}
}
]
}
As paulsm4 said, I'd have a look at gson. It's easy to use, you can find a lot of example of how it works all over the web (official user guide).
Example:
Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));
Gson gson = new Gson();
System.out.println(gson.toJson(employee));
Output:
{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}
From howtodoinjava.com/'s Google Gson Tutorial : Convert Java Object to / from JSON.

Categories

Resources