how do we provide Json data for bulkimportcustomfieldvalues without using curl?

I am writing a python script which is executing successfully if I provide the URL,headers and data using the curl command in the below format:

curl -u -k <username>:<password> "https://<JIRA url>/rest/scriptrunner/latest/canned/com.onresolve.scriptrunner.canned.jira.admin.BulkImportCustomFieldValues" -H "X-Atlassian-token: no-check" -H "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" -H "Accept: application/json" --data "@add-opt.json"

When I try to provide the same data using httpRequest,I am unable to go through.

request =  Request(https://<JIRA url>/rest/scriptrunner/latest/canned/com.onresolve.scriptrunner.canned.jira.admin.BulkImportCustomFieldValues", data="@add-opt.json", headers={"Authorization": " Basic " + b64encode(<username> + ":" + <password>), "Content-Type": "application/json"})

I have imported all the necessary libraries,but I still get an internal server error.

Is it possible to bypass the curl command?

 

2 answers

2 votes
Vasiliy Zverev Community Champion Mar 17, 2016

Here is code example on Java to make REST calls without curl:

package ru.phosagro.jira.rest;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import javax.json.*;

public class testREST_CreateIssue {
    public static void main(String[] args) {
        try {
            URL jiraREST_URL = new URL("http://172.27.211.65:8080/rest/api/2/issue/IC38-15");
            URLConnection urlConnection = jiraREST_URL.openConnection();
            urlConnection.setDoInput(true);

            HttpURLConnection conn = (HttpURLConnection) jiraREST_URL.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);

            System.out.println(getJSON_Body());

            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Authorization", "Basic " + Base64.encode("name:pass".getBytes(), 0));
            conn.setRequestProperty("Content-Type", "application/json");
            conn.getOutputStream().write(getJSON_Body().getBytes());

            try {
                InputStream inputStream = conn.getInputStream();

                for(int iByte = 0; iByte &lt; inputStream.available(); ++iByte ){

                }
            }
            catch (IOException e){
                System.out.println(e.getMessage());
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getJSON_Body() {
        JsonObject createIssue = Json.createObjectBuilder()
            .add("fields",
                    Json.createObjectBuilder().add("project",
                            Json.createObjectBuilder().add("key", "IC38"))
                            .add("summary", "\u0415\u0436\u0435\u043D\u0435\u0434\u0435\u043B\u044C\u043D\u044B\u0439 \u043E\u0442\u0447\u0435\u0442 (11)")
                            .add("duedate", "2016-03-18")
                            .add("issuetype",
                                    Json.createObjectBuilder().add("id", "10903"))
            ).build();

        return createIssue.toString();
    }


}

+1 but people might find it easier to use HttpBuilder, which is included with the plugin and available to scripts.

Thanks for the response Jamie and Vasiliy. I have no java knowledge and beginning to learn it.My python file looks like below.Please suggest where am I going wrong.

 

from urllib2 import Request, urlopen
from urllib import urlencode
from json import load, dumps
import base64
from base64 import b64encode
from base64 import b64decode
import subprocess
import urllib2

scriptParams = urllib.urlencode({
"FIELD_FCS": "10804",
"FIELD_IMPORT_VALUES": "abc\ndef\nghi\n",
"canned-script": "com.onresolve.scriptrunner.canned.jira.admin.BulkImportCustomFieldValues"
})

baseURL = '<jira_URL>/rest/scriptrunner/latest/canned/com.onresolve.scriptrunner.canned.jira.admin.BulkImportCustomFieldValues/'
headers = {"Authorization": " Basic " + b64encode("username" + ":" + "password"), "Content-Type": "application/json"}
request = Request(baseURL, data=scriptParams, headers=headers)

request.get_method = lambda: 'POST'

response_body = urlopen(request).read()
print response_body

--------------------------------------------------------------------------------------------------------------------------

 

Output:

File "C:\Python27\Lib\urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python27\Lib\urllib2.py", line 397, in open
response = meth(req, response)
File "C:\Python27\Lib\urllib2.py", line 510, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\Lib\urllib2.py", line 435, in error
return self._call_chain(*args)
File "C:\Python27\Lib\urllib2.py", line 369, in _call_chain
result = func(*args)
File "C:\Python27\Lib\urllib2.py", line 518, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 500: Internal Server Error

I think I am starting to understand what you are trying to do now. There is this docn: https://scriptrunner.adaptavist.com/latest/jira/builtin-scripts.html#_executing_built_in_scripts_remotely

Beyond that I cannot help you with python, maybe try a python forum, or perhaps someone else here can.

0 votes

how are you running this script?

Suggest an answer

Log in or Sign up to answer
Community showcase
Published Oct 31, 2018 in Marketplace Apps

Marketplace Spotlight: Zephyr

Hello Atlassian Community! Each month, we run a series of Spotlights to highlight Marketplace vendors and apps that our team thinks this Community would find valuable. In last month's Spotlig...

304 views 0 1
Read article

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you