I want to connect Java with JIRA trial account. I tested this code:
public class JiraImpl
{
private static URI JIRA_URL = URI.create("https://sonoratest.atlassian.net");
private static final String JIRA_ADMIN_USERNAME = "sonoratestw#gmail.com";
private static final String JIRA_ADMIN_PASSWORD = "sonpass";
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException
{
try
{
AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
JiraRestClient restClient = factory.createWithBasicHttpAuthentication(JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
Iterable<BasicProject> allProjects = restClient.getProjectClient().getAllProjects().claim();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
But when I run it nothing happens. Wahat is the proper way to get data from JIRA using REST API?
Update. I also tried this:
private static URI JIRA_URL = URI.create("https://sonoratest.atlassian.net/rest/auth/1/session");
I get
java.util.concurrent.ExecutionException: RestClientException{statusCode=Optional.of(404), errorCollections=[ErrorCollection{status=404, errors={}, errorMessages=[]}]}
at com.google.common.util.concurrent.AbstractFuture$Sync.getValue(AbstractFuture.java:299)
at com.google.common.util.concurrent.AbstractFuture$Sync.get(AbstractFuture.java:286)
at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:116)
at com.google.common.util.concurrent.ForwardingFuture.get(ForwardingFuture.java:63)
at com.atlassian.jira.rest.client.internal.async.DelegatingPromise.get(DelegatingPromise.java:102)
at com.jira.impl.JiraImpl.main(JiraImpl.java:23)
Caused by: RestClientException{statusCode=Optional.of(404), errorCollections=[ErrorCollection{status=404, errors={}, errorMessages=[]}]}
Try getting an issue first, since that is so basic.
import java.net.URI;
import java.util.Optional;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.atlassian.util.concurrent.Promise;
public class JRC
{
public Issue getIssue(String issueKey) throws Exception
{
final URI jiraServerUri = new URI("https://jira-domain");
final JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(jiraServerUri, "user#domain.com", "password");
Promise issuePromise = restClient.getIssueClient().getIssue(issueKey);
return Optional.ofNullable((Issue) issuePromise.claim()).orElseThrow(() -> new Exception("No such issue"));
}
}
You can also take a look at this code to get a fully working sample:
https://github.com/somaiah/jrjc
Related
I'm learning to create a REST Assured and Cucumber framework from scratch following a tutorial video on Youtube.
Below is the step definition and the method it calls in the RestAssuredExtension class.
#Given("^I perform GET operation for \"([^\"]*)\"$")
public void i_Perform_GET_Operation_For(String url) throws Throwable {
RestAssuredExtension.GetOps(url);
}
package utilities;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.response.ResponseOptions;
import io.restassured.specification.RequestSpecification;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
public class RestAssuredExtension {
public static RequestSpecification Request;
public RestAssuredExtension() {
//Arrange
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.setBaseUri("http://localhost:3000/");
builder.setContentType(ContentType.JSON);
var requestSpec = builder.build();
Request = RestAssured.given().spec(requestSpec);
}
public static ResponseOptions<Response> GetOps(String url) {
//Act
try {
return Request.get(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
}
In the video tutorial, the test passes successfully. But when I run the test myself, it results in the following error:
Step failed
java.lang.NullPointerException: Cannot invoke "io.restassured.specification.RequestSpecification.get(java.net.URI)" because "utilities.RestAssuredExtension.Request" is null
at utilities.RestAssuredExtension.GetOps(RestAssuredExtension.java:42)
at steps.GETPostSteps.i_Perform_GET_Operation_For(GETPostSteps.java:21)
Any takers please?
From the example you have given, I think you have not initialized the RestAssuredExtension.Request field.
In the video (I quickly skimmed it), they provide a hook to create a new instance of the RestAssuredExtension before any tests are executed. This will ensure that the public static class variable Request will have been initialized to a non-null value.
My recommendation, if you want to reduce dependency for setup on the test framework and make use of static methods:
public final class RequestExtension {
private static RequestSpecification request;
// Ensure that no one is able to create an instance and thereby bypass proper initalization
private RequestExtension() {
}
// Ensures the initialization responsibility is within the class itself and not a hidden dependency for other users.
private static void getInstance() {
if (request == null) {
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.setBaseUri("http://localhost:3000/");
builder.setContentType(ContentType.JSON);
var requestSpec = builder.build();
request = RestAssured.given().spec(requestSpec);
}
return request;
}
public static ResponseOptions<Response> GetOps(String url) {
// Initialize
getInstance();
// Act
try {
return request.get(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
}
Otherwise, mixing static methods with dependencies on the instance will keep tripping people up. Would go either with the above or remove static from the class altogether:
public class RequestExtension {
private RequestSpecification request;
public RestAssuredExtension() {
//Arrange
RequestSpecBuilder builder = new RequestSpecBuilder();
builder.setBaseUri("http://localhost:3000/");
builder.setContentType(ContentType.JSON);
var requestSpec = builder.build();
request = RestAssured.given().spec(requestSpec);
}
public ResponseOptions<Response> GetOps(String url) {
//Act
try {
return request.get(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
}
One thing to help with debugging is to follow Java naming conventions. The capitalisation of your class field RequestSpecification makes it read as a class not a field name. (Request vs request) It was the same in the video so its a source issue. :)
I have gradle script which is creating the version in JIRA using the REST API.
But there is jira-rest-java-client also available. I want to use the java library of jira-rest-java-client and wants to do the same stuff in gradle. Can someone provide an example how could I try this.
How to use the jira-rest-java-client library to make connection with JIRA through example?
In Java I am trying to use this JRCJ Library but getting below error through Intellj
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.*;
import com.atlassian.jira.rest.client.api.domain.input.ComplexIssueInputFieldValue;
import com.atlassian.jira.rest.client.api.domain.input.FieldInput;
import com.atlassian.jira.rest.client.api.domain.input.TransitionInput;
import com.atlassian.jira.rest.client.internal.ServerVersionConstants;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.google.common.collect.Lists;
import org.codehaus.jettison.json.JSONException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* A sample code how to use JRJC library
*
* #since v0.1
*/
public class Example1 {
private static URI jiraServerUri = URI.create("http://localhost:2990/jira");
private static boolean quiet = false;
public static void main(String[] args) throws URISyntaxException, JSONException, IOException {
parseArgs(args);
final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, "admin", "admin");
try {
final int buildNumber = restClient.getMetadataClient().getServerInfo().claim().getBuildNumber();
// first let's get and print all visible projects (only jira4.3+)
if (buildNumber >= ServerVersionConstants.BN_JIRA_4_3) {
final Iterable<BasicProject> allProjects = restClient.getProjectClient().getAllProjects().claim();
for (BasicProject project : allProjects) {
if (project == TEST){
println(project);}else {
System.out.println("Project" + "Not Found");
}
}
}
// let's now print all issues matching a JQL string (here: all assigned issues)
if (buildNumber >= ServerVersionConstants.BN_JIRA_4_3) {
final SearchResult searchResult = restClient.getSearchClient().searchJql("assignee is not EMPTY").claim();
for (BasicIssue issue : searchResult.getIssues()) {
println(issue.getKey());
}
}
final Issue issue = restClient.getIssueClient().getIssue("TST-7").claim();
println(issue);
// now let's vote for it
restClient.getIssueClient().vote(issue.getVotesUri()).claim();
// now let's watch it
final BasicWatchers watchers = issue.getWatchers();
if (watchers != null) {
restClient.getIssueClient().watch(watchers.getSelf()).claim();
}
// now let's start progress on this issue
final Iterable<Transition> transitions = restClient.getIssueClient().getTransitions(issue.getTransitionsUri()).claim();
final Transition startProgressTransition = getTransitionByName(transitions, "Start Progress");
restClient.getIssueClient().transition(issue.getTransitionsUri(), new TransitionInput(startProgressTransition.getId()))
.claim();
// and now let's resolve it as Incomplete
final Transition resolveIssueTransition = getTransitionByName(transitions, "Resolve Issue");
final Collection<FieldInput> fieldInputs;
// Starting from JIRA 5, fields are handled in different way -
if (buildNumber > ServerVersionConstants.BN_JIRA_5) {
fieldInputs = Arrays.asList(new FieldInput("resolution", ComplexIssueInputFieldValue.with("name", "Incomplete")));
} else {
fieldInputs = Arrays.asList(new FieldInput("resolution", "Incomplete"));
}
final TransitionInput transitionInput = new TransitionInput(resolveIssueTransition.getId(), fieldInputs, Comment
.valueOf("My comment"));
restClient.getIssueClient().transition(issue.getTransitionsUri(), transitionInput).claim();
}
finally {
restClient.close();
}
}
private static void println(Object o) {
if (!quiet) {
System.out.println(o);
}
}
private static void parseArgs(String[] argsArray) throws URISyntaxException {
final List<String> args = Lists.newArrayList(argsArray);
if (args.contains("-q")) {
quiet = true;
args.remove(args.indexOf("-q"));
}
if (!args.isEmpty()) {
jiraServerUri = new URI(args.get(0));
}
}
private static Transition getTransitionByName(Iterable<Transition> transitions, String transitionName) {
for (Transition transition : transitions) {
if (transition.getName().equals(transitionName)) {
return transition;
}
}
return null;
}
}
Error:
xception in thread "main" java.lang.NoClassDefFoundError: com/atlassian/sal/api/executor/ThreadLocalContextManager
at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.create(AsynchronousJiraRestClientFactory.java:35)
at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.createWithBasicHttpAuthentication(AsynchronousJiraRestClientFactory.java:42)
at Example1.main(Example1.java:34)
Caused by: java.lang.ClassNotFoundException: com.atlassian.sal.api.executor.ThreadLocalContextManager
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 3 more
Moreover I added the JRJC api,core jar in External Libraries but still getting this error?
Could someone tell me what is the issue or where am I missing something?
compile 'com.atlassian.jira:jira-rest-java-client-core:4.0.0'
compile 'com.atlassian.jira:jira-rest-java-client-api:4.0.0'
Simple connection to JIRA:
JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(new URI("https://" + jira_domain),
jira_username, jira_password);
I am having an issue with the OAuthClientImpl.getInstance() method that is on line 26. It is spitting out this error message:
Exception in thread "main" java.lang.ExceptionInInitializerError
at OAuth.main(OAuth.java:26)
Caused by: java.lang.ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
at org.apache.log4j.Logger.getLogger(Logger.java:41)
at com.etrade.etws.oauth.sdk.client.OAuthClientImpl.<init>(OAuthClientImpl.java:22)
at com.etrade.etws.oauth.sdk.client.OAuthClientImpl.<clinit>(OAuthClientImpl.java:24)
... 1 more
It seems to me that the issue is a communication issue between log4j and the E*Trade OAuth jar, although with my limited experience with Java/coding in general I have no idea how to go about fixing this issue, since I couldn't find much helpful information on Google. I decompiled the E*Trade jar and the log4j and found this code:
E*Trade:
public class OAuthClientImpl
implements IOAuthClient
{
private Logger logger = Logger.getLogger(getClass());
private static OAuthClientImpl instance = new OAuthClientImpl();
public static OAuthClientImpl getInstance()
{
return instance;
}
Log4j:
public static Logger getLogger(final Class<?> clazz) {
return (Logger) Category.getInstance((LoggerContext) PrivateManager.getContext(), clazz);
}
Below is my code, it is the E*Trade API sample code with a few minor tweaks.
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import com.etrade.etws.account.Account;
import com.etrade.etws.account.AccountListResponse;
import com.etrade.etws.account.ETWSException;
import com.etrade.etws.oauth.sdk.client.IOAuthClient;
import com.etrade.etws.oauth.sdk.client.OAuthClientImpl;
import com.etrade.etws.oauth.sdk.common.Token;
import com.etrade.etws.sdk.client.ClientRequest;
import com.etrade.etws.sdk.client.Environment;
public class OAuth
{
public static void main(String[] args) throws IOException, URISyntaxException, com.etrade.etws.sdk.common.ETWSException
{
//Variables
IOAuthClient client = null;
ClientRequest request = null;
Token token = null;
String oauth_consumer_key = null; // Your consumer key
String oauth_consumer_secret = null; // Your consumer secret
String oauth_request_token = null; // Request token
String oauth_request_token_secret = null; // Request token secret
client = OAuthClientImpl.getInstance(); // Instantiate IOAUthClient
request = new ClientRequest(); // Instantiate ClientRequest
request.setEnv(Environment.SANDBOX); // Use sandbox environment
request.setConsumerKey(oauth_consumer_key); //Set consumer key
request.setConsumerSecret(oauth_consumer_secret);
token = client.getRequestToken(request); // Get request-token object
oauth_request_token = token.getToken(); // Get token string
oauth_request_token_secret = token.getSecret(); // Get token secret
}
public void OAuthVerify(IOAuthClient client, ClientRequest request) throws IOException, URISyntaxException, com.etrade.etws.sdk.common.ETWSException
{
String authorizeURL = null;
authorizeURL = client.getAuthorizeUrl(request); // E*TRADE authorization URL
URI uri = new java.net.URI(authorizeURL);
Desktop desktop = Desktop.getDesktop();
desktop.browse(uri);
}
}
If I run following java class, no exception or error message occures, but I'm sure that connection cannot be established (GrailsApplication1 is not running, and 'url' is not pointing to any bean):
public class ConnectNow {
private void connect() {
ClientDolphin dClient = new ClientDolphin();
dClient.setClientModelStore(new ClientModelStore(dClient));
String url = "http://localhost:8080/GrailsApplication1/";
ClientConnector connector = new HttpClientConnector(dClient, url);
connector.setCodec(new JsonCodec());
dClient.setClientConnector(connector);
dClient.send("Hi from client");
}
public static void main(String[] args) {
ConnectNow cn = new ConnectNow();
cn.connect();
System.out.println("End");
}
}
Soo, how can I recognize if connection is established? I'm newbie in client/server dev, so maybe I'm missing something obvious.
Thanks for any advice, or doc reference!
Now, I figured it out... Key is that I have to run the code as an Application, in this case javafx app. Then, if you try to transmit something (dClient send "Hi... - in this case), app tries to send a message, and you get ConnectException: Connection refused, if there is nothing running on url.
This seems to me as shortest version of open-dolphin server accessibity test:
import javafx.application.Application;
import javafx.stage.Stage;
import org.opendolphin.core.client.ClientDolphin;
import org.opendolphin.core.client.ClientModelStore;
import org.opendolphin.core.client.comm.ClientConnector;
import org.opendolphin.core.client.comm.HttpClientConnector;
import org.opendolphin.core.comm.JsonCodec;
/**
*
* #author Václav Hanton
*/
public class ConnectNow extends Application {
private void connect() {
ClientDolphin dClient = new ClientDolphin();
ClientModelStore mStore = new ClientModelStore(dClient);
dClient.setClientModelStore(mStore);
String url = "http://localhost:8080/GrailsApplication1/";
ClientConnector connector = new HttpClientConnector(dClient, url);
connector.setCodec(new JsonCodec());
dClient.setClientConnector(connector);
dClient.send("Hi from client");
}
public static void main(String[] args) {
ConnectNow cn = new ConnectNow();
cn.connect();
Application.launch();
}
#Override
public void start(Stage stage) throws Exception {
System.out.println("Started");
}
}
I am running the YouTubeSample given on the google developers website. I have no errors in the code and my imports appear to be fine. But when I run the project I get the aforementioned error.
I have done some searches but to be honest I have been unable to work out what the problem is. I have already tried importing an external jar guava but it didn't help.
Any help is appreciated. Here is the full class
package com.pengilleys.googlesamples;
import java.io.IOException;
import java.util.List;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.util.Key;
public class YouTubeSample {
public static class VideoFeed {
#Key List<Video> items;
}
public static class Video {
#Key String title;
#Key String description;
#Key Player player;
}
public static class Player {
#Key("default") String defaultUrl;
}
public static class YouTubeUrl extends GenericUrl {
#Key final String alt = "jsonc";
#Key String author;
#Key("max-results") Integer maxResults;
YouTubeUrl(String url) {
super(url);
}
}
public static void main(String[] args) throws IOException {
// set up the HTTP request factory
HttpTransport transport = new NetHttpTransport();
final JsonFactory jsonFactory = new JacksonFactory();
HttpRequestFactory factory = transport.createRequestFactory(new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) {
// set the parser
JsonCParser parser = new JsonCParser();
parser.jsonFactory = jsonFactory;
request.addParser(parser);
// set up the Google headers
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-YouTubeSample/1.0");
headers.gdataVersion = "2";
request.headers = headers;
}
});
// build the YouTube URL
YouTubeUrl url = new YouTubeUrl("https://gdata.youtube.com/feeds/api/videos");
url.author = "searchstories";
url.maxResults = 2;
// build the HTTP GET request
HttpRequest request = factory.buildGetRequest(url);
// execute the request and the parse video feed
VideoFeed feed = request.execute().parseAs(VideoFeed.class);
for (Video video : feed.items) {
System.out.println();
System.out.println("Video title: " + video.title);
System.out.println("Description: " + video.description);
System.out.println("Play URL: " + video.player.defaultUrl);
}
}
}
The setup documentation gives a list of dependencies:
Depending on the application you are building, you may also need these dependencies:
Apache HTTP Client version 4.0.3
Google Guava version r09
Jackson version 1.6.7
Google GSON version 1.6
In this case, it looks like it's Guava which is missing. I don't know what you mean about "exporting" Guava, but if you include the Guava r09 jar file in the classpath when you're running the code, it should be fine.
what's the extra ); for above the // build the YouTube URL and did you mean to close main on that line?