Save curl response in a variable in Jenkins declarative pipeline - jenkins

I have a Jenkins decalarative pipeline where I am calling some URL via cURL which is returning JSON response. How to catch that JSON in a variable?
Have tried the below code but it's returning entire thing with path and command along with the response
environment {
token = bat(returnStdout: true, script: 'curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\\"username\\" : \\"user\\",\\"password\\" : \\"pwd\\"}"').trim()
}
JSON response
C:\ProgramData\Jenkins\.jenkins\workspace\publish-api>curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\"username\" : \"ap-1\",\"password\" : \"Ap5\"}"
{
"access_token": "axxxx-5ca2-48eb-9eb3-173c44a811",
"token_type": "bearer",
"redirectUrl": "/home/"
}

You can use the readJson method to get to your wished result. You don't necesseraly have to call it in your environment-block.
stage('Curl') {
steps {
script {
def cUrlResponse = bat(returnStdout: true, script: '#curl https://anypoint.mulesoft.com/accounts/login -H "Content-Type: application/json" -d "{\\"${env.username}\\" : \\"user\\",\\"${env.password}\\" : \\"pwd\\"}"').trim()
def responseJson = readJSON text: cUrlResponse
def accessToken = responseJson.access_token
def tokenType = responseJson.token_type
// do other stuff with the variables
}
}
}
To exclude the curl command from the output, add # in front of the script as stated in the documentation.

Related

Jenkins pipeline: passing in data variable as string into curl command

So I'm trying to pass in a string (data) into this sendSlackMessage function but it's not going into the curl command correctly. data is being passed in from my jenkinsfile.
It's working fine in the echo command though.
Can someone tell me what I'm doing wrong?
data = """{'channel': '#mychannel','username': 'jenkins-bot','icon_emoji': ':lol:','text': 'HERERERERE (<$BUILD_URL|Open>)','attachments': [['color': '#36a64f','fields': ['title': 'UPDATING INFOR','value': 'HELLOWORLD','short': 'true']]]}"""
void sendSlackMessage(String data) {
this.steps.sh(returnStdout: true, script: "echo hello world ${data} hello world again")
this.steps.sh(returnStdout: true, script: "curl -X POST -H 'Content-type: application/json' --data '${data}' https://hooks.slack.com/services/T12345671/sdfsdfsdf/sdf7sdf7gsdf")
}
Please try the below implementation
data = """{'channel': '#mychannel','username': 'jenkins-bot','icon_emoji': ':lol:','text': 'HERERERERE (<$BUILD_URL|Open>)','attachments': [['color': '#36a64f','fields': ['title': 'UPDATING INFOR','value': 'HELLOWORLD','short': 'true']]]}"""
void sendSlackMessage(String data) {
List curlCommand = []
curlCommand.add('curl -X POST -H')
curlCommand.add('\'Content-type: application/json\'')
curlCommand.add('--data')
curlCommand.add(data) // Maybe you have to see if you see to add a single quote here and escape it
curlCommand.add('https://hooks.slack.com/services/T12345671')
sh (
returnStdout: true,
script: curlCommand.join(" "),
label: "send slack message"
)
}

Not able to construct proper header for groovy function Get request

Writing my first function here for Groovy native lib and running into an issue. A method to get Github Labels for pull-requests. #param github_token String token with permission to access and read PR information.
getLabelsPerPullRequest.groovy: 19: expecting '}', found ':' # line 19, column 28. 'Authorization': 'token '+ github_token, ^
Here is my function
import groovy.json.JsonSlurper
def getLabelsPerPullRequest(String github_token) {
def labels
def scmHead = jenkins.scm.api.SCMHead.HeadByItem.findHead(currentBuild.rawBuild.getParent())
def repo = scmHead.getSourceRepo()
def prId = scmHead.getId()
if(github_token && github_token != null) {
// Set the call headers with Oauth token.
def headers = "{'Authorization': 'token '+ ${github_token},'Accept': 'application/vnd.github.v3+json'}"
// Construct request number URL in Github
def pr_url = "https://github.optum.com/api/v3/repos/SOP-Bot/${repo}/pulls/${prNbr}"
def json = sh(
script: "curl -X Get ${pr_url} -H ${headers}",
returnStdout: true
)
def prInfo = JsonOutput.toJson(text: json)
labels = prInfo.labels
}
return labels
}
Each header needs to be a separate -H argument. You can do something like this. I added -s to curl because you probably don't want the extra progress output but it may not actually be an issue.
def headers = [
"-H 'Authorization: token ${gitub_token}'",
"-H 'Accept: application/vnd.github.v3+json'"
]
...
def json = sh(
script: "curl -s -X GET ${headers.join(' ')} '${pr_url}'",
returnStdout: true
)

io9 - Alamofire token request fails with 401 error depsite curl from debugPrint works

My question is along the line of a question which has been asked before at Previous question.
I am using Alamofire 3.2.1, XCode 7.3, iOS9.
Here is my code with the intention to obtain a token from OAuth server (localhost) implemented by django oauth toolkit:
let params = ["grant_type": "password",
"username": "rosa",
"password": "rosa1234"]
let request = Alamofire.request(.POST, url, parameters: params).authenticate(user: __clientID, password: __clientSecret)
debugPrint(request)
request.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseSwiftyJSON({ (request, response, json, error) in
debugPrint(response)
if (error != nil) {
print(error.debugDescription)
return completionHandler(token: nil, error: error)
}
// call the completionHandler function (object) to deal with data further
return completionHandler(token: json.string, error: nil)
})
The debug print of request gives a working curl command, which works on a command line:
curl -i \
-X POST \
-u PrtRUN9ra7LHCYWbiReaAjO9I26lJhLhRSAUJgtr:kTvxqKmClDAL3tbdyZdyBZgsfsfXtagMpZyFjSZwpIknxM43l6ZIvJxJGXu2J2FuHf4JMLfopDoAzkF6vHSRq4GZkbnEZSmmUnMvkhMvSucbhWUdzCpxuj9qtc8beaQ3 \
-H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \
-H "User-Agent: IntelliCafe/xsoft.IntelliCafe (1; OS Version 9.3 (Build 13E230))" \
-H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
-H "Accept-Language: en-US;q=1.0" \
-d "grant_type=password&password=rosa1234&username=rosa" \
"http://localhost:8000/o/token/"
But the code does not work in my app. The error is 401:
Optional(<NSHTTPURLResponse: 0x7d183950> { URL: http://localhost:8000/o/token/ } { status code: 401, headers {
"Cache-Control" = "no-store";
"Content-Type" = "application/json";
Date = "Mon, 11 Apr 2016 20:43:48 GMT";
Pragma = "no-cache";
Server = "WSGIServer/0.1 Python/2.7.10";
"X-Frame-Options" = SAMEORIGIN;} })
Optional(Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 401" UserInfo={NSLocalizedFailureReason=Response status code was unacceptable: 401})
This problem is driving me crazy. Any help will be grateful!
Thanks in advance.
I wrote a django rest view to print out the meta data of the request and found out the clientID and clientSecret are not embedded/processed properly by the django server implementation.
Using the Authorization header as shown in Alamofire documentation works.

How do I specify data-binary in Titanium Appcelerator?

I am trying to use the Dropbox API to upload a file. Here is the documentation from Dropbox:
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer <get access token>" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #local_file.txt
I have this in my Appcelerator project:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
//My function
};
xhr.open('POST','https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'My Key');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', '{"path":"/my_path/file.txt","mode":{".tag":"add"}}');
But I can't figure out how to send the data-binary argument. With my current code I can create a file in my Dropbox folder, but is just an empty file.
From http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Network.HTTPClient, it looks like you just pass it into xhr.send(). You can pass a string, an object (which gets form-encoded), or a Titanium.Blob.
(Disclaimer: I've never used Appcelerator, so this is just what I surmise from reading the documentation.)
I figure out a way to do that. In my case I just need to upload a simple data structure, so I am using a JSON object:
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function(e) {
//My function
};
xhr.open('POST','https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'My Key');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', '{"path":"/my_path/file.txt","mode":{".tag":"add"}}');
var my_json = {
"item1" : "content1"
};
xhr.send(JSON.stringify(my_json));
I still can't send a BLOB (like a picture from the phone gallery), but it works if you pass the path of the file:
var my_path = Titanium.Filesystem.getFile(Titanium.Filesystem.tempDirectory,'my_folder');
var newFile = Titanium.Filesystem.getFile(my_path.nativePath,'file.txt');
newFile.createFile();
newFile.write('Content of my text file');
var params = {"data-binary" : newFile};
xhr.send(params);

How to Pass Neo4j 2.0 Server Plugin Parameters

I made a really simple Neo4j 2.0 Server Plugin that works great without any parameters. However, I'm not sure how I'm supposed to pass a string parameter to the plugin. I have one optional parameter called "criteria". This should be very simple. I'm just not very familiar with CURL, java, or REST.
#Name( "getLabelsForSearch" )
#Description( "Get all labels that match the search criteria from the Neo4j graph database" )
#PluginTarget( GraphDatabaseService.class )
public Iterable<String> getLabelsForSearch( #Source GraphDatabaseService graphDb, #Description("The search criteria string") #Parameter (name = "criteria", optional = true) String criteria )
{
ArrayList<String> labels = new ArrayList<>();
labels.add(criteria);
try (Transaction tx = graphDb.beginTx())
{
for ( Label label : GlobalGraphOperations.at(graphDb).getAllLabels() )
{
labels.add(criteria);
//This is just for testing
labels.add(label.name());
}
tx.success();
}
return labels;
}
I tried a few different ways with curl:
curl -X POST http://icexad01:7474/db/data/ext/GetAll/graphdb/getLabelsForSearch?criteria=thisorthat
curl -X POST http://icexad01:7474/db/data/ext/GetAll/graphdb/getLabelsForSearch/criteria/thisorthat
curl -X POST http://icexad01:7474/db/data/ext/GetAll/graphdb/getLabelsForSearch -data { "criteria" : "thisorthat"}
I've been following this page and it has an example of passing a parameter. Maybe I'm just overlooking something?
http://docs.neo4j.org/chunked/snapshot/server-plugins.html
This is the json information I get back when I do a GET request on the url:
http://icexad01:7474/db/data/ext/GetAll/graphdb/getLabelsForSearch/
{
"extends" : "graphdb",
"description" : "Get all labels that match the search criteria from the Neo4j graph database",
"name" : "getLabelsForSearch",
"parameters" : [ {
"description" : "The search criteria string",
"optional" : true,
"name" : "criteria",
"type" : "string"
} ]
}
You need to pass in the parameters in JSON format. Therefore it's crucial to specify the content type and to put the payload in quotes, so try
curl -X POST -H "Content-Type: application/json" -data '{ "criteria" : "thisorthat"}' http://icexad01:7474/db/data/ext/GetAll/graphdb/getLabelsForSearch

Resources