I am trying to communicate with jira using Java but i am facing an exception as shown below
xception in thread "main" java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.impl.nio.conn.DefaultClientAsyncConnectionFactory.createHttpResponseFactory(DefaultClientAsyncConnectionFactory.java:105)
at org.apache.http.impl.nio.conn.DefaultClientAsyncConnectionFactory.<init>(DefaultClientAsyncConnectionFactory.java:74)
at org.apache.http.impl.nio.conn.DefaultClientAsyncConnectionFactory.<clinit>(DefaultClientAsyncConnectionFactory.java:62)
at org.apache.http.impl.nio.conn.PoolingClientAsyncConnectionManager.createClientAsyncConnectionFactory(PoolingClientAsyncConnectionManager.java:96)
at org.apache.http.impl.nio.conn.PoolingClientAsyncConnectionManager.<init>(PoolingClientAsyncConnectionManager.java:72)
at com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClient$2.<init>(DefaultHttpClient.java:117)
at com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClient.<init>(DefaultHttpClient.java:115)
at com.atlassian.jira.rest.client.internal.async.AsynchronousHttpClientFactory.createClient(AsynchronousHttpClientFactory.java:53)
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 jira.JiraCommunicate.main(JiraCommunicate.java:33)
Exception i am facing at this line
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
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.api.domain.Comment;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.SearchResult;
import com.atlassian.jira.rest.client.api.domain.Transition;
import com.atlassian.jira.rest.client.api.domain.User;
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.async.AsynchronousJiraRestClientFactory;
import com.atlassian.util.concurrent.Promise;
public class JiraCommunicate {
private static final String JIRA_URL = "";
private static final String JIRA_ADMIN_USERNAME = "";
private static final String JIRA_ADMIN_PASSWORD = "";
public static void main(String[] args) throws Exception {
// Construct the JRJC client
//System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD));
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_URL);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser("admin");
User user = promise.claim();
for (BasicProject project : client.getProjectClient().getAllProjects().claim()) {
System.out.println(project.getKey() + ": " + project.getName());
}
Promise<SearchResult> searchJqlPromise = client.getSearchClient().searchJql("project = MYPURRJECT AND status in (Closed, Completed, Resolved) ORDER BY assignee, resolutiondate");
for (Issue issue : searchJqlPromise.claim().getIssues()) {
System.out.println(issue.getSummary());
}
// Print the result
System.out.println(String.format("Your admin user's email address is: %s\r\n", user.getEmailAddress()));
// Done
System.out.println("Example complete. Now exiting.");
System.exit(0);
}
}
Blockquote
Please i need your help..I want to communicate Jira to upload or download Story or create bugs..
I am running an application on tomcat server. I am getting following error while callling a specific function :
java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy
My class is :
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
/*import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;*/
//import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.performics.air.business.common.data.HttpParam;
public class SendAndReceiveUtil implements Serializable {
//FIXME: move to suitable package
/**
*
*/
private static final long serialVersionUID = 2649891233958197253L;
private static Logger LOG = Logger.getLogger(SendAndReceiveUtil.class);
public static String httpPostWithTLS(String request,String url,Map<String,String> headerParameterMap){
String responseStr = null;
try{
// FIXME: need to handle supplier timeout and gzip
String contentType="";
String soapAction="";
boolean zipForRequest=false;
boolean acceptEncoding = false;
boolean zipForResponse=false;
if (headerParameterMap!=null){
contentType=headerParameterMap.get(HttpParam.CONTENTTYPE.toString())!=null?headerParameterMap.get(HttpParam.CONTENTTYPE.toString()):"";
zipForRequest=(headerParameterMap.containsKey(HttpParam.ZIPFORREQUEST.toString()))? new Boolean(headerParameterMap.get(HttpParam.ZIPFORREQUEST.toString())):false;
acceptEncoding=(headerParameterMap.containsKey(HttpParam.ACCEPT_ENCODING.toString()))? new Boolean(headerParameterMap.get(HttpParam.ACCEPT_ENCODING.toString())):false;
zipForResponse=(headerParameterMap.containsKey(HttpParam.ZIPFORRESPONSE.toString()))? new Boolean(headerParameterMap.get(HttpParam.ZIPFORRESPONSE.toString())):false;
soapAction=headerParameterMap.get(HttpParam.SOAPACTION.toString())!=null?headerParameterMap.get(HttpParam.SOAPACTION.toString()):"";
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build();
// Allow TLSv1.2 protocol only, use NoopHostnameVerifier to trust self-singed cert
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1.2" }, null, new NoopHostnameVerifier());
//do not set connection manager
HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("SOAPAction", soapAction);
StringEntity mEntity = new StringEntity(request, "UTF-8");
if(StringUtils.isNotBlank(contentType)){
mEntity.setContentType(contentType);
mEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,contentType));
}else{
mEntity.setContentType("text/xml;charset=UTF-8");
mEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,"gzip"));
}
httpPost.addHeader("Content-Encoding", "gzip" );
httpPost.addHeader("Accept-Encoding", "gzip,deflate" );
if(null!=headerParameterMap.get("Cookie")){
httpPost.addHeader("Cookie", headerParameterMap.get("Cookie"));
}
httpPost.setEntity(mEntity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity et=response.getEntity();
ByteArrayOutputStream os = new ByteArrayOutputStream();
et.writeTo(os);
responseStr = new String(os.toByteArray());
}catch(Exception e){
LOG.error(e.getMessage(), e);
}
return responseStr;
}
}
Error comes on calling httpPostWithTLS() function. I searched about it on net and found that class was available at compile but is not available at run time, but i am unable to correct it.
I am using following http jars:
commons-httpclient-3.1.jar
httpclient-4.5.3.jar
httpcore-4.4.6.jar
httpclient-cache-4.5.3.jar
httpclient-win-4.5.3.jar
httpmime-4.5.3.jar
Try to add the httpcore-4.4.6.jar and httpclient-cache-4.5.3.jar to server library and check.
I do face the similar issue after adding these jar file, my problem is resolved.
Thanks,
I am retrieving URL from database and it contains special characters like % - = / ? etc. so while I try to populate that in my page JSON is not able to parse that URL and it is giving me some exception when I was debugging I got like this
(Log4JLogger.java:log:449) [SECURITY FAILURE Anonymous:null#unknown -> /ExampleApplication/IntrusionException] INTRUSION - Mixed encoding (2x) detected
I tried from these link here this my offending URL here
but it is not working he mentioned that bug is solved. but for which version version here I am using is 2.1.0 below is my code
package com.ghn.repufact.review.extractor;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.log4j.Logger;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Encoder;
import org.owasp.esapi.Validator;
import org.owasp.esapi.errors.EncodingException;
import org.owasp.esapi.reference.DefaultValidator;
import org.springframework.stereotype.Component;
#Component
public class ValidateURL {
private static final Logger logger=Logger.getLogger(ValidateResponse.class);
public String parseOrgConsumerLink(String myLink) throws URISyntaxException {
if(myLink==null || "".equalsIgnoreCase(myLink))
return myLink;
Encoder enc=ESAPI.encoder();
URI mixURI=new URI(myLink);
UriBuilder uriBuider=UriBuilder.fromUri(enc.canonicalize(mixURI.getAuthority()+mixURI.getPath()));
uriBuider.path(enc.canonicalize(mixURI.getAuthority() + mixURI.getPath()));
logger.info("Uri after URIbuilder:"+uriBuider.build().toString());
List<NameValuePair> params = URLEncodedUtils.parse(mixURI, "UTF-8");
for (NameValuePair nameValuePair : params)
uriBuider.queryParam(enc.canonicalize(nameValuePair.getName()), enc.canonicalize(nameValuePair.getValue()));
String canonicalizedUrl = uriBuider.build().toString();
logger.info("canonicaliz URI:"+canonicalizedUrl);
return canonicalizedUrl;
}
public boolean isCanonicalizedURI(String myLink) throws EncodingException {
Validator validator=DefaultValidator.getInstance();
//boolean flag=validator.isValidInput("test", myLink, "URI", 200, false);
myLink = ESAPI.encoder().encodeForURL(myLink);
boolean flag = validator.isValidInput("APPNAME", myLink, "URLSTRING", 600, true, false);
logger.info("checking for URI:"+myLink+" isCanonical:"+flag);
return flag;
}
}
please let me know if any work around here. By the way I am using spring MVC
I am facing problem while connecting with WooCommerce API (http://woothemes.github.io/woocommerce-rest-api-docs/#authentication). I am successfully able to generate the signature using java program and also checked the generated signature having same time stamp and nonce on linked in console(as given in the WooCommerce document) for any discrepancy but the generated signature is same on linked in and java output console.
The process of our working is described below :
1. We have generated the signature with the help of signature base string and secret key using java program. Signature base string looks like :
GET&http%3A%2F%2FEndPointURL%2Fwc-api%2Fv2%2Forders&oauth_consumer_key%3D%26oauth_nonce%3D70810941%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1433226349%26oauth_version%3D1.0
2. While we are trying to access the url http://EndPointURL/wc-api/v2/orders, It is showing error given below :
{"errors":[{"code":"woocommerce_api_authentication_error","message":"Invalid Signature - provided signature does not match"}]}
3.We have also generated the signature with the help of Linked in test Console using same value of time stamp and nonce and getting the same signature. But we are not able to access the data.
The java code that I am using is given below :
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class OAuthForWooCommerce {
private static String key = "consumer_Key";
private static String secret = "consumer_Secret";
private static final String HMAC_SHA1 = "HmacSHA1";
private static final String ENC = "UTF-8";
private static Base64 base64 = new Base64();
private static String getSignature(String url, String params)
throws UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeyException {
/**
* base has three parts, they are connected by "&": 1) protocol 2) URL
* (need to be URLEncoded) 3) Parameter List (need to be URLEncoded).
*/
StringBuilder base = new StringBuilder();
base.append("GET&");
base.append(url);
base.append("&");
base.append(params);
System.out.println("String for oauth_signature generation:" + base);
// yea, don't ask me why, it is needed to append a "&" to the end of
// secret key.
byte[] keyBytes = (secret + "&").getBytes(ENC);
SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
// encode it, base64 it, change it to string and return.
return new String(base64.encode(mac.doFinal(base.toString().getBytes(
ENC))), ENC).trim();
}
public static void main(String[] args) throws ClientProtocolException,
IOException, URISyntaxException, InvalidKeyException,
NoSuchAlgorithmException {
System.out.println("*** Welcome to WooCommerce Klipfolio integration Wizard ***");
HttpClient httpclient = new DefaultHttpClient();
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
// These params should ordered in key
//qparams.add(new BasicNameValuePair("oauth_callback", "oob"));
qparams.add(new BasicNameValuePair("oauth_consumer_key", key));
String nonce = RandomStringUtils.randomAlphanumeric(32);
//String nonce2 = URLEncoder.encode(nonce1, "UTF-8");
qparams.add(new BasicNameValuePair("oauth_nonce", nonce));
//qparams.add(new BasicNameValuePair("oauth_nonce", ""+ (int) (Math.random() * 100000000)));
qparams.add(new BasicNameValuePair("oauth_signature_method",
"HMAC-SHA1"));
qparams.add(new BasicNameValuePair("oauth_timestamp", ""
+ (System.currentTimeMillis() / 1000)));
qparams.add(new BasicNameValuePair("oauth_version", "1.0"));
// generate the oauth_signature
String signature = getSignature(URLEncoder.encode(
"http://MY_END_URL/wc-api/v2/orders", ENC),
URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC));
System.out.println("Getting Oauth Signature...");
// add it to params list
qparams.add(new BasicNameValuePair("oauth_signature", signature));
// generate URI which lead to access_token and token_secret.
URI uri = URIUtils.createURI("http", "MY_END _URL", -1,
"wc-api/v2/orders",
URLEncodedUtils.format(qparams, ENC), null);
System.out.println("Connecting to the URL : \n"
+ uri.toString());
HttpGet httpget = new HttpGet(uri);
// output the response content.
System.out.println("Getting Response from the server :");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int len;
byte[] tmp = new byte[2048];
while ((len = instream.read(tmp)) != -1) {
System.out.println(new String(tmp, 0, len, ENC));
}
}
}
}
Please let me know where I am doing wrong.
Thanks,
You must remove the version number from params, according to the documentation. I think also you should remove "&" you added to the secret key when generating signature, since I managed to get 200 response without it.
The require parameters are: oauth_consumer_key, oauth_timestamp, oauth_nonce, oauth_signature, and oauth_signature_method. oauth_version is not required and must be omitted.
You should also sort the parameters in byte order before adding them to the string you used to create the signature.
Also, I suggest you to debug by changing the message line to see the signature you sent to the server and the signature you should have sent.
For instance, you can change it to:
throw new Exception( __( 'Invalid Signature - provided signature does not match Secret:' . $user->woocommerce_api_consumer_secret . ', StringToSign: ' . $string_to_sign . ', TakenSign: ' . $consumer_signature . ', GeneratedSign: ' . $signature, 'woocommerce' ), 401 );
Thanks for your code Archit, this helped me jump through hoops.
I have updated your code and the below works.
package com.woocommerce.experiments;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.net.URLCodec;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class OAuthForWooCommerce {
private static String key = "ck_your_consumer_key";
private static String secret = "cs_your_consumer_secret";
private static final String HMAC_SHA1 = "HmacSHA1";
private static final String ENC = "UTF-8";
private static Base64 base64 = new Base64();
private static String getSignature(String url, String params)
throws UnsupportedEncodingException, NoSuchAlgorithmException,
InvalidKeyException, EncoderException {
/**
* base has three parts, they are connected by "&": 1) protocol 2) URL
* (need to be URLEncoded) 3) Parameter List (need to be URLEncoded).
*/
StringBuilder base = new StringBuilder();
base.append("GET&");
//follow Step 2 and encode
base.append(new URLCodec(Consts.UTF_8.displayName()).encode(url));
base.append("&");
base.append(params);
System.out.println("String for oauth_signature generation: " + base);
byte[] keyBytes = (String.format("%s", secret)).getBytes(ENC);
SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(key);
// encode it, base64 it, change it to string and return.
String signature = new String(base64.encode(mac.doFinal(base.toString().getBytes(ENC))), ENC).trim();
return signature;
}
public static void main(String[] args) throws IOException, URISyntaxException, InvalidKeyException,
NoSuchAlgorithmException, EncoderException {
String nonce = RandomStringUtils.randomAlphanumeric(32);
Map<String, String> paramMap = new TreeMap<>();
paramMap.put("oauth_consumer_key", key);
paramMap.put("oauth_timestamp", "" + (System.currentTimeMillis() / 1000));
paramMap.put("oauth_nonce", nonce);
paramMap.put("oauth_signature_method", "HMAC-SHA1");
List<NameValuePair> qparams = new ArrayList<>();
//uksort( $params, 'strcmp' ) mimic
paramMap.entrySet().stream().forEach(stringStringEntry -> qparams.add(new BasicNameValuePair(stringStringEntry.getKey(), stringStringEntry.getValue())));
//double encode Step 3 (in order to replace '%' with '%25') after sorting (Step 4)
String encodedParams = URLEncoder.encode(URLEncodedUtils.format(qparams, ENC), ENC);
System.out.println("Encoded Params "+ encodedParams);
String signature = getSignature("http://your_end_url/wc-api/v2/orders", encodedParams);
qparams.add(new BasicNameValuePair("oauth_signature", signature));
HttpClient httpclient = HttpClientBuilder.create().build();
System.out.println("Getting Oauth Signature...");
// generate URI which lead to access_token and token_secret.
URI uri = URIUtils.createURI("http", "your_end_url", -1, "wc-api/v2/orders", URLEncodedUtils.format(qparams, ENC), null);
System.out.println("Connecting to the URL : \n" + uri.toString());
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("X-Stream" , "true");
// output the response content.
System.out.println("Getting Response from the server :");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Response Code " + response.getStatusLine().getStatusCode());
if (entity != null) {
System.out.println("Json response" + IOUtils.toString(entity.getContent(), ENC));
}
}
}
I hope this helps you (hopefully not late!) and others. Step by step process for authentication can be found at WooCommerce REST API Documentation
Hello I have a class for doing webdav related operations such as creating a directory, Implementatiion can be seen below (the createDir method). The question is how to test it nicely, perhaps using EasyMock or a similar lib. Any ideas? thanks!
package foobar;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import mypackage.httpdclient.util.URLHandler;
public class WebDavImpl{
private static final String SEPARATOR = " ----- ";
private HttpClient httpClient;
public StorageSpaceClientImpl() {
httpClient = new HttpClient();
}
public String createDir(String dirName) {
String response = null;
String url = URLHandler.getInstance().getDirectoryUrl(dirName);
DavMethod mkcol = new MkColMethod(url);
try {
httpClient.executeMethod(mkcol);
response = mkcol.getStatusCode() + SEPARATOR + mkcol.getStatusText();
} catch (IOException ex) {
} finally {
mkcol.releaseConnection();
}
return response;
}
}