A Standalone Demo that Automatically Logs a JIRA Ticket using Java JIRA API

One needs only add the jira url, username and password. This code will automatically create a jira ticket in the first project available. It also automatically fills in all required fields.

For pom.xml dependencies, see Using the Atlassian JIRA Rest Client.


import java.net.URI;
import java.util.Arrays;
import com.atlassian.jira.rest.client.api.GetCreateIssueMetadataOptions;
import com.atlassian.jira.rest.client.api.GetCreateIssueMetadataOptionsBuilder;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.domain.BasicIssue;
import com.atlassian.jira.rest.client.api.domain.BasicProject;
import com.atlassian.jira.rest.client.api.domain.CimFieldInfo;
import com.atlassian.jira.rest.client.api.domain.CimIssueType;
import com.atlassian.jira.rest.client.api.domain.CimProject;
import com.atlassian.jira.rest.client.api.domain.CustomFieldOption;
import com.atlassian.jira.rest.client.api.domain.EntityHelper;
import com.atlassian.jira.rest.client.api.domain.IssueType;
import com.atlassian.jira.rest.client.api.domain.Project;
import com.atlassian.jira.rest.client.api.domain.input.ComplexIssueInputFieldValue;
import com.atlassian.jira.rest.client.api.domain.input.IssueInput;
import com.atlassian.jira.rest.client.api.domain.input.IssueInputBuilder;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.atlassian.util.concurrent.Promise;

/**
 * This demo is for people who just want to pull in the dependencies of the JIRA API and figure out how to use it independent of this project.
 * 
 * This will create an issue in a random project to get started
 * 
 * @author sizu
 *
 */
public class DirectJIRAAPIUsageDemo {
	public static String URL = "...";
	public static String USERNAME = "...";
	public static String PASSWORD = "...";
	public static void main(String[] args) {
		System.out.println("Creating issue");
		// Connect to JIRA
		final JiraRestClientFactory jiraRestClientFactory = new AsynchronousJiraRestClientFactory();
		JiraRestClient jiraRestClient = jiraRestClientFactory
				.createWithBasicHttpAuthentication(URI.create(URL),
						USERNAME, PASSWORD);
		
		// Automatically Generate Project Key
		String projectKey = null;
		try {
			Promise<Iterable> projects = jiraRestClient.getProjectClient().getAllProjects();
			BasicProject project = projects.get().iterator().next();
			projectKey = project.getKey();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		// Automatically Generate Issue Type ID
		Long issueTypeID = null;
		try {
			Promise project = jiraRestClient.getProjectClient().getProject(projectKey);
			IssueType issueType = project.get().getIssueTypes().iterator().next();
			issueTypeID = issueType.getId();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// Start creating an issue
		IssueInputBuilder issueBuilder = new IssueInputBuilder(projectKey, issueTypeID);
		issueBuilder.setFieldValue("labels", Arrays.asList("DirectJIRAAPIUsageDemo"));
		
		// Grab the meta data to fill in required fields
		GetCreateIssueMetadataOptions options = new GetCreateIssueMetadataOptionsBuilder()
			.withExpandedIssueTypesFields()
			.withProjectKeys(projectKey)
			.build();

		Iterable projects = jiraRestClient.getIssueClient()
				.getCreateIssueMetadata(options).claim();

		CimProject project = projects.iterator().next();
		CimIssueType issueType = EntityHelper.findEntityById(project.getIssueTypes(), issueTypeID);

		for (String key : issueType.getFields().keySet()) {
			CimFieldInfo issueField = issueType.getFields().get(key);
			String fieldID = issueField.getId();
			if(fieldID.equals("project")) { // Skip the project field since it is already filled when issueBuilder was created
				continue;
			}
			
			if (issueField.isRequired()) {
				try {
					// Get allowed value for the required field
					String allowedValue = null;
					for(Object object: issueField.getAllowedValues()) {
						if(object instanceof CustomFieldOption) {
							CustomFieldOption cfo = (CustomFieldOption) object;
							allowedValue = ""+cfo.getId(); // Convert Long to String format
						}
					}
					
					ComplexIssueInputFieldValue value = ComplexIssueInputFieldValue.with("id", allowedValue);
					if(issueField.getSchema().getType().equals("array")) {
						issueBuilder.setFieldValue(fieldID, Arrays.asList(value));
					} else {
						issueBuilder.setFieldValue(fieldID, value);
					}
				} catch (Exception ex) {
					// Does not have allowed value
					issueBuilder.setFieldValue(fieldID, "Test");
				}
			}
		}
		
		// Create Issue
		IssueInput newIssue = issueBuilder.build();
		BasicIssue basicIssue = jiraRestClient.getIssueClient().createIssue(newIssue).claim();
		
		// Close connection
		try {
			jiraRestClient.close();
		} catch (Exception ex) { }
		System.out.println("Key:"+basicIssue.getKey()+" ID:"+basicIssue.getId());
	}
}

Advertisements

Using the Atlassian JIRA Rest Client

See https://ecosystem.atlassian.net/wiki/display/JRJC/Tutorial for more information.

Your pom.xml file (see earlier posts about Java, Maven and Eclipse) needs the following dependency:


    
...
<!-- import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory; -->
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-rest-java-client-core</artifactId>
            <version>2.0.0-m25</version>

<!-- import com.atlassian.jira.rest.client.api.JiraRestClient; -->
<!-- import com.atlassian.jira.rest.client.api.JiraRestClientFactory; -->
<!-- import com.atlassian.jira.rest.client.api.domain.BasicProject; -->
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-rest-java-client-api</artifactId>
            <version>2.0.0-m25</version>
        
...
    

If these dependencies do not bring in the following, you may need these as well to compile (mvn eclipse:clean eclipse:eclipse clean compile):


<!-- com.atlassian.util.concurrent.Promise jar -->
                     <groupId>com.atlassian.util.concurrent</groupId>
                     <artifactId>atlassian-util-concurrent</artifactId>
                     <version>2.4.0-M9</version>
              

<!-- com.google.common.util.concurrent.ListenableFuture jar -->
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>10.0.1</version>
            

You may need the following to run the code in Eclipse (Run As->Java Application). Unfortunately, if you need to repackage any jars to either remove the parent pom file references or change the versions to standard X.X.X.X format, this may require manual dependency management. Hence the long list of dependencies.


<!-- Caused by: java.lang.ClassNotFoundException: com.atlassian.event.api.EventPublisher -->
                     <groupId>com.atlassian.event</groupId>
                     <artifactId>atlassian-event</artifactId>
                     <version>2.2.0</version>

<!-- Caused by: java.lang.ClassNotFoundException: com.atlassian.sal.api.ApplicationProperties -->
                <groupId>com.atlassian.sal</groupId>
                <artifactId>sal-api</artifactId>
                <version>2.7.0</version>

<!-- Caused by: java.lang.ClassNotFoundException: com.atlassian.httpclient.api.HttpClient -->
                <groupId>com.atlassian.httpclient</groupId>
                <artifactId>atlassian-httpclient-api</artifactId>
                <version>0.13.2</version>

<!-- Caused by: java.lang.ClassNotFoundException: com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClient -->
                <groupId>com.atlassian.httpclient</groupId>
                <artifactId>atlassian-httpclient-apache-httpcomponents</artifactId>
                <version>0.13.2</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.DisposableBean -->
                     <groupId>org.springframework</groupId>
                     <artifactId>spring-context</artifactId>
                     <version>3.1.1.RELEASE</version>

<!-- Caused by: java.lang.ClassNotFoundException: javax.ws.rs.core.UriBuilder -->
                     <groupId>com.sun.jersey</groupId>
                     <artifactId>jersey-json</artifactId>
                     <version>1.5</version>

<!-- Caused by: java.lang.ClassNotFoundException: com.sun.ws.rs.ext.RuntimeDelegateImpl -->
                     <groupId>com.sun.jersey</groupId>
                     <artifactId>jersey-client</artifactId>
                     <version>1.5</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.apache.http.nio.reactor.IOReactorExceptionHandler -->
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore-nio</artifactId>
            <version>4.2.2</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.apache.http.impl.client.cache.CachingHttpAsyncClient -->
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpasyncclient-cache</artifactId>
            <version>4.0-beta3-atlassian-1</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.apache.http.impl.nio.conn.PoolingClientAsyncConnectionManager -->
            org.apache.httpcomponents</groupId>
            <artifactId>httpasyncclient</artifactId>
            <version>4.0-beta3-atlassian-1</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.apache.http.client.cache.HttpCacheStorage -->
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient-cache</artifactId>
      <version>4.2.1-atlassian-2</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.apache.http.conn.routing.HttpRoutePlanner -->
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.2.1-atlassian-2</version>

<!-- Caused by: java.lang.ClassNotFoundException: com.atlassian.httpclient.spi.ThreadLocalContextManagers -->
                <groupId>com.atlassian.httpclient</groupId>
                <artifactId>atlassian-httpclient-spi</artifactId>
                <version>0.13.2</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory -->
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>1.6.4</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.apache.http.entity.mime.content.ContentBody -->
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.1.2</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.joda.time.ReadableInstant -->
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>1.6</version>

<!-- Caused by: java.lang.ClassNotFoundException: org.apache.commons.codec.binary.Base64 -->
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.6</version>

Once you have this, the following code should compile to check connection to the JIRA server. This code will print out all the project names from JIRA.

The code assumes the following:

1. JIRA url is “http://myjira.mycompany.com&#8221;
2. JIRA login username is “scott”
3. JIRA login password is “abc123”


import java.net.URI;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClientFactory;
import com.atlassian.jira.rest.client.api.domain.BasicProject;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.atlassian.util.concurrent.Promise;

public class MyJiraRestClientFactory {
	public static void main(String[] args) {
		JiraRestClient jiraRestClient = createJiraRestClient("http://myjira.mycompany.com", "scott", "abc123");
		Promise<Iterable> projects = jiraRestClient.getProjectClient().getAllProjects();
		try {
			for(BasicProject project: projects.get()) {
				System.out.println("ProjectName:"+project.getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	public static JiraRestClient createJiraRestClient(String url, String username, String password) {
		final JiraRestClientFactory jiraRestClientFactory = new AsynchronousJiraRestClientFactory();
		
		return jiraRestClientFactory
				.createWithBasicHttpAuthentication(URI.create(url),
						username, password);
	}
}