How to use Authentication with JIRA REST API in Java - java

hi im creating a simple tool using java to create,update and delete issues(tickets) in jira. i am using rest api following code is im using to authenticate jira and issue tickets.
public class JiraConnection {
public static URI jiraServerUri = URI.create("http://localhost:8090/jira/rest/api/2/issue/HSP-1/");
public static void main(String args[]) throws IOException {
final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri,"vinuvish92#gmail.com","vinu1994");
System.out.println("Sending issue creation requests...");
try {
final List<Promise<BasicIssue>> promises = Lists.newArrayList();
final IssueRestClient issueClient = restClient.getIssueClient();
System.out.println("Sending issue creation requests...");
for (int i = 0; i < 100; i++) {
final String summary = "NewIssue#" + i;
final IssueInput newIssue = new IssueInputBuilder("TST", 1L, summary).build();
System.out.println("\tCreating: " + summary);
promises.add(issueClient.createIssue(newIssue));
}
System.out.println("Collecting responses...");
final Iterable<BasicIssue> createdIssues = transform(promises, new Function<Promise<BasicIssue>, BasicIssue>() {
#Override
public BasicIssue apply(Promise<BasicIssue> promise) {
return promise.claim();
}
});
System.out.println("Created issues:\n" + Joiner.on("\n").join(createdIssues));
} finally {
restClient.close();
}
}
}
according this code i couldn't connect to the jira
**following exception i am getting **
please suggest me best solution to do my task

It seems to me that your error is clearly related to url parameter. The incriminated line and the fact that the error message is about not finding the resource are good indications of it.
You don't need to input the whole endpoint since you are using the JiraRestClient. Depending on the method that you call it will resolve the endpoint. Here is an example that works: as you can see I only input the base url

Related

Unable to get data from java web service

Someone please help me i keep trying but not able to find out why i am unable to get the results.
I have created this java springboot web service where when I run the java application, a web browser page will open and when I type in the URL e.g localhost:8080/runbatchfileparam/test.bat the program will check if the test.bat file exist first. If it does, the web page will show a JSON result {“Result”: true} and the command in the batch file will be executed. If it does not exist, the web page will show {“Result”: false}.
I want to create an ASP.NET Web Service that will use the function created in the java web service. When I run the ASP.NET Web Application, a web browser page will open. User will type in URL something like this: localhost:12345/api/callbatchfile/test.bat. The java web service should be running and I should get either {“Result”: true} or {“Result”: false} when I run the C# ASP.NET Web Application too.
However I only get an empty {} without anything inside the brackets. Why is that so?
Here are my code in ASP.NET
TestController.cs
private TestClient testClient = new TestClient();
public async Task<IHttpActionResult> GET(string fileName)
{
try
{
var result = await testClient.runbatchfile(fileName);
var resultDTO = JsonConvert.DeserializeObject<TestVariable>(result);
return Json(resultDTO);
}
catch (Exception e)
{
var result = "Server is not running";
return Ok(new { ErrorMessage = result });
}
}
TestVariable.cs
public class TestVariable
{
public static int fileName { get; set; }
}
TestClient.cs
private static HttpClient client;
private static string BASE_URL = "http://localhost:8080/";
static TestClient()
{
client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<string> runbatchfile(string fileName)
{
var endpoint = string.Format("runbatchfile/{0}", fileName);
var response = await client.GetAsync(endpoint);
return await response.Content.ReadAsStringAsync();
}
WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "TestBatchClient",
routeTemplate: "api/runbatchfile/{fileName}",
defaults: new { action = "GET", controller = "Test" }
);
Someone please do help me. Thank you so much.
EDIT
Java web service
Application.java
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
BatchFileController.java
private static final String template = "Sum, %s!";
#RequestMapping("/runbatchfile/{param:.+}")
public ResultFormat runbatchFile(#PathVariable("param") String fileName) {
RunBatchFile rbf = new RunBatchFile();
return rbf.runBatch(fileName);
}
ResultFormat
private boolean result;
public ResultFormat(boolean result) {
this.result = result;
}
public boolean getResult() {
return result;
}
RunBatchFile.java
public ResultFormat runBatch(String fileName) {
String var = fileName;
String filePath = ("C:/Users/attsuap1/Desktop/" + var);
try {
Process p = Runtime.getRuntime().exec(filePath);
int exitVal = p.waitFor();
return new ResultFormat(exitVal == 0);
} catch (Exception e) {
e.printStackTrace();
return new ResultFormat(false);
}
}
I am not sure if this helps.. but I suspect that the AsyncTask is not really executing...
var result = await testClient.testCallBatchProject(fileName);
I would try something like below:
await testClient.testCallBatchProject(fileName).Delay(1000);
Can you try and check if the same happens for a synchronous call? .. if it does, we can zero down on the above.

Setting soapui connection timeout programmatically from WsdlRequest

I would like to know a way to set a connection timeout in Soapui java.
I am using soapui version 4.0.1.0
What i have found so far is reading timeout but what i need now is setting a connection timeout.
This question was asked before but no specific answers were given.
Here is my code so far.
It sends and retrieves requests like i want.
But my problem is handling timeouts.
And if possible i would like to ensure if the read timeout is in milliseconds.
public static void main(String[] args) {
WsdlProject project = null;
WsdlInterface[] interfacesInWSDL = null;
try {
SoapUI.setSoapUICore(new StandaloneSoapUICore(true));
project = new WsdlProject();
interfacesInWSDL = WsdlInterfaceFactory.importWsdl(project, "wsdlPath.wsdl", true);
for (int i = 0; i < interfacesInWSDL.length; i++) {
for (Operation op : interfacesInWSDL[i].getOperationList()) {
WsdlOperation operation = (WsdlOperation) op;
WsdlRequest request = operation.addNewRequest("WSDLRequest");
request.setTimeout("10000");//Read timeout
request.setEndpoint("URL");
request.setRequestContent(operation.createRequest(true));
System.out.println(request.getRequestContent());
WsdlSubmitContext submitContext = new WsdlSubmitContext(request);
WsdlSubmit submit = (WsdlSubmit) request.submit(submitContext, false);
Response response = submit.getResponse();
System.out.println(response.getContentAsString());
}
}
} catch (Exception ex) {
//Exception Logger
}
}
Thank you in advance.

java jira rest client timeout issue

I get java.net.SocketTimeoutException when searching in jira. How can I increase the timeout ?
Code:
JiraRestClientFactory restClientFactory = new AsynchronousJiraRestClientFactory();
SearchResult results = null;
try {
URI uri = new URI(jira_url);
restClient = restClientFactory.createWithBasicHttpAuthentication(uri, jira_username, jira_password);
final SearchRestClient searchClient = restClient.getSearchClient();
String jql = searchClient.getFilter(jira_filterid).get().getJql();
// setting max result to 1000 and start with 0
results = searchClient.searchJql(jql, 500, 0).claim();
System.out.println("Took: " + stopWatch.toString() + " to find " + results.getTotal() + " case in jira filter with id " + jira_filterid);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return results;
The searching should not take so long, i think it is when doing claim().
Exception:
java.lang.RuntimeException: java.net.SocketTimeoutException
at com.google.common.base.Throwables.propagate(Throwables.java:160)
at com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClient$3.apply(DefaultHttpClient.java:256)
at com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClient$3.apply(DefaultHttpClient.java:249)
at com.atlassian.util.concurrent.Promises$Of$2.apply(Promises.java:276)
at com.atlassian.util.concurrent.Promises$Of$2.apply(Promises.java:272)
at com.atlassian.util.concurrent.Promises$2.onFailure(Promises.java:167)
at com.google.common.util.concurrent.Futures$4.run(Futures.java:1172)
at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:297)
at com.google.common.util.concurrent.ExecutionList.executeListener(ExecutionList.java:156)
at com.google.common.util.concurrent.ExecutionList.execute(ExecutionList.java:145)
at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:202)
at com.google.common.util.concurrent.SettableFuture.setException(SettableFuture.java:68)
at com.atlassian.httpclient.apache.httpcomponents.SettableFuturePromiseHttpPromiseAsyncClient$1$2.run(SettableFuturePromiseHttpPromiseAsyncClient.java:59)
at com.atlassian.httpclient.apache.httpcomponents.SettableFuturePromiseHttpPromiseAsyncClient$ThreadLocalDelegateRunnable$1.run(SettableFuturePromiseHttpPromiseAsyncClient.java:197)
at com.atlassian.httpclient.apache.httpcomponents.SettableFuturePromiseHttpPromiseAsyncClient.runInContext(SettableFuturePromiseHttpPromiseAsyncClient.java:90)
at com.atlassian.httpclient.apache.httpcomponents.SettableFuturePromiseHttpPromiseAsyncClient$ThreadLocalDelegateRunnable.run(SettableFuturePromiseHttpPromiseAsyncClient.java:192)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:680)
Caused by: java.net.SocketTimeoutException
at org.apache.http.nio.protocol.HttpAsyncRequestExecutor.timeout(HttpAsyncRequestExecutor.java:279)
at org.apache.http.impl.nio.client.LoggingAsyncRequestExecutor.timeout(LoggingAsyncRequestExecutor.java:128)
at org.apache.http.impl.nio.DefaultHttpClientIODispatch.onTimeout(DefaultHttpClientIODispatch.java:136)
at org.apache.http.impl.nio.DefaultHttpClientIODispatch.onTimeout(DefaultHttpClientIODispatch.java:50)
at org.apache.http.impl.nio.reactor.AbstractIODispatch.timeout(AbstractIODispatch.java:169)
at org.apache.http.impl.nio.reactor.BaseIOReactor.sessionTimedOut(BaseIOReactor.java:257)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.timeoutCheck(AbstractIOReactor.java:494)
at org.apache.http.impl.nio.reactor.BaseIOReactor.validate(BaseIOReactor.java:207)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:284)
at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:106)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:604)
... 1 more
I can not Believe i had to got so deep to change it. you can use reflection to achieve it
try (JiraRestClient client = clientFactory.createWithBasicHttpAuthentication(new URI(jira.getUrl()), jira.getUsername(), jira.getPassword())) {
try {
Field f1 = Class.forName("com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClient").getDeclaredField("httpClient");
Field f2 = Class.forName("com.atlassian.jira.rest.client.internal.async.AtlassianHttpClientDecorator").getDeclaredField("httpClient");
Field f3 = Class.forName("com.atlassian.httpclient.apache.httpcomponents.ApacheAsyncHttpClient").getDeclaredField("httpClient");
Field f4 = Class.forName("org.apache.http.impl.client.cache.CachingHttpAsyncClient").getDeclaredField("backend");
Field f5 = Class.forName("org.apache.http.impl.nio.client.InternalHttpAsyncClient").getDeclaredField("defaultConfig");
Field f6 = Class.forName("org.apache.http.client.config.RequestConfig").getDeclaredField("socketTimeout");
f1.setAccessible(true);
f2.setAccessible(true);
f3.setAccessible(true);
f4.setAccessible(true);
f5.setAccessible(true);
f6.setAccessible(true);
Object requestConfig = f5.get(f4.get(f3.get(f2.get(f1.get(client)))));
f6.setInt(requestConfig, 120 * 1000);
f1.setAccessible(false);
f2.setAccessible(false);
f3.setAccessible(false);
f4.setAccessible(false);
f5.setAccessible(false);
f6.setAccessible(false);
} catch (Exception ignore) {
}
// now you can start using it :)
} catch (URISyntaxException | IOException e) {
logger.error("invalid jira server address: " + jira.getUrl(), e);
throw new RuntimeException("can not access jira server");
}
it will buy you 120 seconds of socket time.
one workaround that seams to work is to take 100 result for each iteration and set startAt
results = searchClient.searchJql(jql, 100, 0).claim();
results1 = searchClient.searchJql(jql, 100, 100).claim();
results2 = searchClient.searchJql(jql, 100, 200).claim();
and so on.
Disclaimer: i am using the Groovy programming language, but the syntax is very similar to Java, so you should be able to reuse the code (hint: in Groovy no semi-colons are needed, the return statement is optional, instead of variable declaration i am using def or final only).
I am using the following library versions (gradle style):
compile "com.atlassian.jira:jira-rest-java-client-core:4.0.0"
compile "com.atlassian.fugue:fugue:2.2.1"
Here we have the standard rest client definition:
JiraRestClient getJiraRestClient()
{
// read user specific Jira password settings and build authentification
final inputFile = new File("${System.getProperty('user.home')}/jiraSettings.json")
final authInfo = new JsonSlurper().parseText(inputFile.text)
// setting up the jira client
def restClient = new AsynchronousJiraRestClientFactory()
.createWithBasicHttpAuthentication(
jiraServerUri,
authInfo.jiraUser.toString(),
authInfo.jiraPassword.toString())
restClient
}
I dived into the createWithBasicHttpAuthentication function and extracted and adapted the code (only getClientOptions - I set the socket timeout to 45 seconds, look at HttpClientOptions default settings):
JiraRestClient getJiraRestClient()
{
return new AsynchronousJiraRestClient(jiraServerUri, getHttpClient());
}
HttpClientOptions getClientOptions()
{
def options = new HttpClientOptions();
options.socketTimeout = 45000L;
options
}
DisposableHttpClient getHttpClient()
{
final DefaultHttpClientFactory defaultHttpClientFactory =
new DefaultHttpClientFactory(new AsynchronousHttpClientFactory.NoOpEventPublisher(),
new AsynchronousHttpClientFactory.RestClientApplicationProperties(jiraServerUri),
new ThreadLocalContextManager() {
#Override
public Object getThreadLocalContext() {
return null;
}
#Override
public void setThreadLocalContext(Object context) {}
#Override
public void clearThreadLocalContext() {}
});
final HttpClient httpClient = defaultHttpClientFactory.create(getClientOptions())
return new AtlassianHttpClientDecorator(httpClient, getAuthenticationHandler()) {
#Override
public void destroy() throws Exception {
defaultHttpClientFactory.dispose(httpClient);
}
}
}
BasicHttpAuthenticationHandler getAuthenticationHandler()
{
// read user specific Jira password settings and build authentification
final inputFile = new File("${System.getProperty('user.home')}/jiraSettings.json")
final authInfo = new JsonSlurper().parseText(inputFile.text)
return new BasicHttpAuthenticationHandler(
authInfo.jiraUser.toString(),
authInfo.jiraPassword.toString())
}
The downside is that I might be forced to adapt this code when I switch to a new version of jira-rest-java-client, but I really need this because the timout is just to short, even with heavy use of paging.
java.util.concurrent.Future class has V get(long timeout, TimeUnit unit).
Adding timeout helped me:
String jql = searchClient.getFilter(jira_filterid).get(120, TimeUnit.SECONDS).getJql();

Jira issue type values for Rest api

Where can I find Jira issue type values that we pass to IssueBuilder class constructor?
For ex: If i want to create a issue type of bug using jira rest api , We pass value '1L' to Issue Builder class constructor.
IssueInputBuilder issueBuilder = new IssueInputBuilder("Key", 1l);
Similarly what are the values of other jira issue types ?.. Anybody know the values we need to pass ?
If you are using later Jira REST Java Client API (e.g. 4.0), the interface has been changed. You must use following code to browsing all issue types:
private static final String JIRA_SERVER = "http://jiralab";
public static void main(String[] args) {
try {
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_SERVER);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, "admin", "admin");
listAllIssueTypes(client);
}
catch (Exception ex) {
}
}
private static void listAllIssueTypes(JiraRestClient client) throws Exception {
Promise<Iterable<IssueType>> promise = client.getMetadataClient().getIssueTypes();
Iterable<IssueType> issueTypes = promise.claim();
for (IssueType it : issueTypes) {
System.out.println("Type ID = " + it.getId() + ", Name = " + it.getName());
}
}
If you want to get a list of all available issuetypes, you can use the REST API (/rest/api/2/issuetype). To try that on your JIRA instance, I like to recommend the Atlassian REST API Browser.
Or just look here: Finding the Id for Issue Types
In Java you can get a list of all issuetype object using getAllIssueTypeObjects().

The weird behavior of Apache XML-RPC

There is a issue confused me so much when I using Apache XML RPC
Below is the code
public class AdderImpl implements Adder{
private Object obj=new String("Obj1");
public int add(int pNum1, int pNum2) {
obj="Changed";
return pNum1 + pNum2;
}
public Object get(){
return this.obj;
}
}
when I call the method from the client side the Object value is still Obj1, not the "Changed"
How can I get the changed the value of the obj
Client:
public class Client {
public static void main(String [] args) throws Exception
{
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL("http://127.0.0.1:8080/xmlrpc"));
config.setEnabledForExtensions(true);
config.setConnectionTimeout(60 * 1000);
config.setReplyTimeout(60 * 1000);
XmlRpcClient client = new XmlRpcClient();
client.setTransportFactory(
new XmlRpcCommonsTransportFactory(client));
client.setConfig(config);
// make a call using dynamic proxy
ClientFactory factory = new ClientFactory(client);
Adder adder = (Adder) factory.newInstance(Adder.class);
int sum = adder.add(2, 4);
System.out.println("2 + 4 = " + sum);
System.out.println(adder.get()==null?true:false);
System.out.println(adder.get().toString());
}
}
Thanks in advance
A new handler get's created each time. To obtain the behaviour you want you have the following options:
Write the value to a database/file (i.e. persistence storage) and read/write it from there.
Make the field static, i.e.
private static Object obj=new String("Obj1");
Hope that helps.

Categories

Resources