Create an issue to JIRA by Java Code - java

I am able to connect to JIRA by JIRARestClient API and also able to get the information about issue but whenever I am trying to create issue by below code, getting this error "RestClientException{statusCode=Optional.of(400), errorCollections=[ErrorCollection{status=400, errors={issuetype=valid issue type is required}, errorMessages=[]}]}"
IssueRestClient issueClient = new AsynchronousJiraRestClientFactory()
.createWithBasicHttpAuthentication(baseUri, username, password).getIssueClient();
IssueType issueType = new IssueType(null, 0L, "bug", false, "my issue", null);
BasicProject basicProject = new BasicProject(null, "CPQ", 1L, null);
IssueInput newIssue = new IssueInputBuilder(basicProject,issueType,"Mopendra").build();
String issueCreated = issueClient.createIssue(newIssue).claim().getKey();
can anyone please help me on this?

the cause is that you should use valid issue type that exists in your Jira and fill parameters correctly. You can fetch existing issue types and choose one you need. See
Jira issue type values for Rest api

Please refer the below-working code. This should solve your problem.
//call method createIssue
final String issueKey = myJiraClient.createIssue("YOUR_PRAJECT_NAME", 1L, "Issue created from Standalone App");
// method declaration
private String createIssue(String projectKey, Long iType, String issueSummary) {
IssueRestClient issueClient = restClient.getIssueClient();
BasicProject cpqProject = null;
IssueType issueType = null;
try {
final Iterable<BasicProject> projects = restClient.getProjectClient().getAllProjects().claim();
System.out.println("======================getting all projoects======================");
for (BasicProject project : projects) {
if(project.getKey().equalsIgnoreCase("cpq")) {
cpqProject = project;
}
}
Promise<Project> project = restClient.getProjectClient().getProject(projectKey);
for(IssueType type : (project.get()).getIssueTypes()) {
if(type.getName().equalsIgnoreCase("Bug")){
issueType = type;
}
}
} catch (Exception e) {
e.printStackTrace();
}
IssueInput newIssue = new IssueInputBuilder(cpqProject, issueType, issueSummary).build();
return issueClient.createIssue(newIssue).claim().getKey();
}

Related

How to implement triple or more segment navigation in OData 4

I'm working on rest serivce with OData v4 protocol using olingo. I got stack on navigation when i'v got let's say:
Company.svc/Departaments(x)/Employees(x)/BussinesTrips
In Olingo's tutorial there is an example where is 2 segments navigation. Where first segment is UriResourceEntitySet and second is UriResourceNavigation.
In the example, these two (especialy entitySet) are needed as parameters in method which gets related entity collection from storage.
In my example there is Company.svc/UriResourceEntitySet/UriResourceNavigation/UriResourceNavigation, what i can say from UriInfo parameter.
I'v no clue how to do that. Should i change the method or somehow force the penulimate segment to be EntitySet.
Thanks for intrest, and im wait for callback.
#Override
public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
String lastUri = "lastUriResource";
String sourceNavigationUri = "sourceUriResource";
EdmEntitySet responseEntitySet = null;
EntityCollection responseEntityCollection = null;
List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
UriResource uriResource = resourcePaths.get(0);
if (!(uriResource instanceof UriResourceEntitySet)) {
throw new ODataApplicationException("Only EntitySet is supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
}
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) uriResource;
EdmEntitySet startEntitySet = uriResourceEntitySet.getEntitySet();
if (resourcePaths.size() == 1) {
responseEntitySet = startEntitySet;
responseEntityCollection = storage.readEntitySetData(responseEntitySet);
} else {
startEntitySet = Util.getNavigationTargetEntitySet(uriInfo);
HashMap<String, UriResource> uriResourceHashMap = Util.getLastNavigationAndItsSource(uriInfo);
UriResource lastUriResource = uriResourceHashMap.get(lastUri);
UriResource sourceUriResource = uriResourceHashMap.get(sourceNavigationUri);
EdmNavigationProperty edmNavigationProperty = null;
if (!(lastUriResource instanceof UriResourceNavigation)) {
throw new ODataApplicationException("Only navigation is supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
}
edmNavigationProperty = ((UriResourceNavigation) lastUriResource).getProperty();
if (!(sourceUriResource instanceof UriResourceEntitySet)) {
throw new ODataApplicationException("Only Entity Set is supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
}
uriResourceEntitySet = (UriResourceEntitySet) sourceUriResource;
startEntitySet = uriResourceEntitySet.getEntitySet();
responseEntitySet = Util.getNavigationTargetEntitySet(uriInfo);
EdmEntityType targetEntityType = edmNavigationProperty.getType();
List<UriParameter> keyParameters = uriResourceEntitySet.getKeyPredicates();
Entity sourceEntity = storage.readEntityData(startEntitySet, keyParameters);
if (sourceEntity == null) {
throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
}
responseEntityCollection = storage.getRelatedEntityCollection(sourceEntity, targetEntityType);
}
ContextURL contextUrl = ContextURL.with().entitySet(responseEntitySet).build();
final String id = request.getRawBaseUri() + "/" + responseEntitySet.getName();
EntityCollectionSerializerOptions options = EntityCollectionSerializerOptions.with().id(id).contextURL(contextUrl).build();
EdmEntityType edmEntityType = responseEntitySet.getEntityType();
ODataSerializer serializer = odata.createSerializer(responseFormat);
SerializerResult serializerResult = serializer.entityCollection(serviceMetaData, edmEntityType, responseEntityCollection, options);
InputStream inputStream = serializerResult.getContent();
response.setContent(inputStream);
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
}
}
Departaments(x) is UriResourceEntitySet. You probably got its EdmEntitySet. Let's say it is stored in prevEdmEntitySet variable.
Employees(x) is UriResourceNavigation. You should take its name and use it with the variable mentioned above:
String propName = uriResourceNavigation.getProperty().getName();
EdmEntitySet currEdmEntitySet = (EdmEntitySet) startEdmEntitySet.getRelatedBindingTarget(propName);
Then you should start the next iteration with prevEdmEntitySet=currEdmEntitySet and repeat for all the UriResourceNavigations (just one more time in your example).

Quickbooks Online Rest API Reporting Java ERROR

I have used a tutorial and the Java SDK to pull reports from the new REST reporting API.
https://developer.intuit.com/docs/0025_quickbooksapi/0055_devkits/0201_ipp_java_devkit_3.0/reports
I have used the following code as specified by the tutorial:
String consumerKey = "XXXXXXXXXXXTDF2GEP0tlzdGxxpQRfSb4";
String consumerSecret = "XXXXXXXXXXYuy9CLaWiyAVHTowK0NuGMKN1X";
String accessToken = "XXXXXXXXXXXGPU4SUGAaeyhRJFp05NUg4s8QnbY4eI4U";
String accessTokenSecret = "XXXXXXXXXXXgkz50A8Ho3Z3pgMO8QFh2ZBv3XjI";
OAuthAuthorizer oauth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
String appToken = "011e510ebf68ab4683b8a06b21f6228dfa03";
String companyID = "1067363490";
try {
Context context = new Context(oauth, appToken, ServiceType.QBO, companyID);
ReportService service = new ReportService(context);
service.setStart_date("2014-02-01");
service.setEnd_date("2014-04-20");
service.setAccounting_method("Accrual");
Object report = service.executeReport(ReportName.PROFITANDLOSS.toString());
String name = "ryan";
//System.out.println(report.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Inside service.executeReport it keeps throwing a java.lang.ClassCastException: com.intuit.ipp.data.Report cannot be cast to com.intuit.ipp.core.Response
Has anyone got these reports to work with the Java SDK? Am I doing something wrong?
At present reports support only Json.
Please verify that you are specifying:
Config.setProperty(Config.SERIALIZATION_RESPONSE_FORMAT, "json");
Update Line:
Object report = service.executeReport(ReportName.PROFITANDLOSS.toString());
To:
Report report = service.executeReport(ReportName.PROFITANDLOSS.toString());
As shown here: https://developer.intuit.com/docs/0100_accounting/0500_developer_kits/0201_ipp_java_devkit_3.0/reports

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().

Created pie chart using DynamicJasper API

I am trying to generate a report dynamically with JasperReports and DynamicJasper APIs.
I added pie chart to reports but after drb.addChart(djChart) chat added as null. Here is my code:
private static DynamicReport createPieChart() {
DynamicReportBuilder drb = new DynamicReportBuilder();
DynamicReport dr = new DynamicReport();
try {
AbstractColumn columnName = ColumnBuilder.getNew().setColumnProperty("name", String.class.getName()).setTitle("Name").build();
AbstractColumn columnaId = ColumnBuilder.getNew().setColumnProperty("id", Integer.class.getName()).setTitle("Id").build();
AbstractColumn columnaTotal = ColumnBuilder.getNew().setColumnProperty("total", Long.class.getName()).setTitle("Total").build();
drb.addColumn(columnName);
drb.addColumn(columnaId);
drb.addColumn(columnaTotal);
DJChart djChart = new DJPieChartBuilder().setX(20)
.setY(10)
.setWidth(500)
.setHeight(250)
.setKey((PropertyColumn) columnaId)
.addSerie(columnaTotal).build();
drb.setUseFullPageWidth(true);
drb.addChart(djChart);
dr = drb.build();
} catch (Exception e) {
}
return dr;
}
Please help!
My problem was building report before set its query. Thanks
Please find the sample code here
DJChart djChart = new DJLineChartBuilder()
//chart
.setX(20)
.setY(10)
.setWidth(500)
.setHeight(250)
.setCentered(false)
.setBackColor(Color.LIGHT_GRAY)
.setShowLegend(true)
.setPosition(DJChartOptions.POSITION_FOOTER)
.setTitle(new StringExpression() {
public Object evaluate(Map fields, Map variables, Map parameters) {
return variables.get("group_state_name");
}
})
.setTitleColor(Color.DARK_GRAY)
.setTitleFont(Font.ARIAL_BIG_BOLD)
.setSubtitle("subtitle")
.setSubtitleColor(Color.DARK_GRAY)
.setSubtitleFont(Font.COURIER_NEW_BIG_BOLD)
.setLegendColor(Color.DARK_GRAY)
.setLegendFont(Font.COURIER_NEW_MEDIUM_BOLD)
.setLegendBackgroundColor(Color.WHITE)
.setLegendPosition(DJChartOptions.EDGE_BOTTOM)
.setTitlePosition(DJChartOptions.EDGE_TOP)
.setLineStyle(DJChartOptions.LINE_STYLE_DOTTED)
.setLineWidth(1)
.setLineColor(Color.DARK_GRAY)
.setPadding(5)
//dataset
.setCategory((PropertyColumn) columnBranch)
.addSerie(columnaQuantity, "quant.")
.addSerie(columnAmount)
//plot
.setShowShapes(true)
.setShowLines(true)
.setCategoryAxisFormat(categoryAxisFormat)
.setValueAxisFormat(valueAxisFormat)
.build();
drb.addChart(djChart);
DJHyperLink djlink = new DJHyperLink();
djlink.setExpression(new StringExpression() {
public Object evaluate(Map fields, Map variables, Map parameters) {
return "http://thisIsAURL?count=" + variables.get("REPORT_COUNT");
}
});
djlink.setTooltip(new LiteralExpression("I'm a literal tootltip"));
djChart.setLink(djlink);

Categories

Resources