Using JIRA Java API to post an attachment to existing issue - api

I am trying to post an attachment to an existing issue in JIRA using API, but it is giving me weird errors:
public class JiraRest {
public static void main(String[] args) throws ClientProtocolException, IOException
{
String pathname= "C:/Users/skalbur/Videos/eclipse-jee-mars-R-win32-x86_64/Mars workspace/Desert.jpg";
File fileUpload = new File(pathname);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("https://rallytojira.atlassian.net/rest/api/2/issue/FP-1389/attachments");
postRequest.setHeader("X-Atlassian-Token","nocheck");
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addPart("file", new FileBody(fileUpload));
postRequest.setEntity((HttpEntity) entity);
HttpResponse response = httpClient.execute(postRequest);
}
}
I'm getting the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/config/Lookup
at JiraRest.main(JiraRest.java:33)
Caused by: java.lang.ClassNotFoundException: org.apache.http.config.Lookup
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
I have used following JARs for my program:
apache-httpcomponents-httpcore.jar, json-simple-1.1.1.jar, httpmime-4.3.jar, jcommander.jar, httpclient-4.3-beta1.jar

THIS CODE WORKS:
public class JiraRest {
public static void main(String[] args) throws ClientProtocolException, IOException
{
String pathname= "<Full path name of the attachment file>";
File fileUpload = new File(pathname);
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("URL+Post REST API");
BASE64Encoder base=new BASE64Encoder();
String encoding = base.encode ("username:password".getBytes());
postRequest.setHeader("Authorization", "Basic " + encoding);
postRequest.setHeader("X-Atlassian-Token","nocheck");
MultipartEntityBuilder entity=MultipartEntityBuilder.create();
entity.addPart("file", new FileBody(fileUpload));
postRequest.setEntity( entity.build());
HttpResponse response = httpClient.execute(postRequest);
}
}
Required JARs:
All JARs in lib folder of httpcomponents-client-4.5-bin and sun.misc.BASE64Decoder.jar

Related

Spring amqp throwing Listener not registered when publish confirm is enabled on second call

i have been trying to get a Spring RabbitMQ publisher with publisher confirms turned on . The first calls goes through fine and confirm callback is returned. from second call onwards it fails with following error message
javax.servlet.ServletException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.amqp.UncategorizedAmqpException: java.lang.IllegalArgumentException: Listener not registered: org.springframework.amqp.rabbit.core.RabbitTemplate#42802df2 []
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:146)
at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:169)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:199)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.amqp.UncategorizedAmqpException: java.lang.IllegalArgumentException: Listener not registered: org.springframework.amqp.rabbit.core.RabbitTemplate#42802df2 []
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:535)
at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1253)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:473)
at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1155)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:126)
... 15 common frames omitted
Caused by: org.springframework.amqp.UncategorizedAmqpException: java.lang.IllegalArgumentException: Listener not registered: org.springframework.amqp.rabbit.core.RabbitTemplate#42802df2 []
at org.springframework.amqp.rabbit.support.RabbitExceptionTranslator.convertRabbitAccessException(RabbitExceptionTranslator.java:83)
at org.springframework.amqp.rabbit.core.RabbitTemplate.doSendAndReceiveWithDirect(RabbitTemplate.java:1650)
at org.springframework.amqp.rabbit.core.RabbitTemplate.doSendAndReceive(RabbitTemplate.java:1531)
at org.springframework.amqp.rabbit.core.RabbitTemplate.sendAndReceive(RabbitTemplate.java:1320)
at com.example.messagequeueintegration.impl.RabbitMQFacade.sendMessage(RabbitMQFacade.java:83)
at com.example.messagequeueintegration.impl.RabbitMQFacade.sendMessage(RabbitMQFacade.java:68)
at com.example.messagequeueintegration.impl.RabbitMQFacade.sendPaymentMessage(RabbitMQFacade.java:51)
at com.example.messagequeueintegration.server.rest.controllers.SendMessageController.sendPaymentMessage(SendMessageController.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 29 common frames omitted
Caused by: java.lang.IllegalArgumentException: Listener not registered: org.springframework.amqp.rabbit.core.RabbitTemplate#42802df2 []
at org.springframework.util.Assert.notNull(Assert.java:134)
at org.springframework.amqp.rabbit.support.PublisherCallbackChannelImpl.addPendingConfirm(PublisherCallbackChannelImpl.java:937)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.amqp.rabbit.connection.CachingConnectionFactory$CachedChannelInvocationHandler.invoke(CachingConnectionFactory.java:981)
at com.sun.proxy.$Proxy47.addPendingConfirm(Unknown Source)
at org.springframework.amqp.rabbit.core.RabbitTemplate.setupConfirm(RabbitTemplate.java:2007)
at org.springframework.amqp.rabbit.core.RabbitTemplate.doSend(RabbitTemplate.java:1979)
at org.springframework.amqp.rabbit.core.RabbitTemplate.exchangeMessages(RabbitTemplate.java:1732)
at org.springframework.amqp.rabbit.core.RabbitTemplate.doSendAndReceiveAsListener(RabbitTemplate.java:1683)
at org.springframework.amqp.rabbit.core.RabbitTemplate.doSendAndReceiveWithDirect(RabbitTemplate.java:1645)
... 48 common frames omitted
This is how my configuration looks like
#Configuration
public class RabbitMQConfig {
#Autowired
private Environment env;
#Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(
env.getRequiredProperty(QUEUE_HOST),
env.getRequiredProperty(QUEUE_PORT, Integer.class));
cachingConnectionFactory.setPublisherConfirms(true);
cachingConnectionFactory.setPublisherReturns(true);
return cachingConnectionFactory;
}
#Bean
public AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
#Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
return rabbitTemplate;
}
#Bean
public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
return new RabbitAdmin(connectionFactory);
}
#Bean
public MessageUtil messageUtil(
#Qualifier("messagequeueintegration") ObjectMapper objectMapper) {
return new MessageUtil(objectMapper);
}
#Bean
public BrokerFacade brokerFacade(
#Qualifier("messagequeueintegration") ObjectMapper objectMapper,
Environment environment,
MessageUtil messageUtil) {
return new RabbitMQFacade(objectMapper, environment, messageUtil);
}
#Bean
public TopicExchange topicExchange() {
return new TopicExchange(TOPIC_EXCHANGE_KEY);
}
#Bean
Binding queue2Binding(#Qualifier("queue2") Queue queue2, TopicExchange topicExchange) {
return BindingBuilder.bind(queue2).to(topicExchange)
.with(env.getRequiredProperty("queue2name"));
}
#Bean
Binding queue1Binding(#Qualifier("queue1") Queue queue1, TopicExchange topicExchange) {
return BindingBuilder.bind(queueq).to(topicExchange)
.with(env.getRequiredProperty("queue1name"));
}
#Bean
public Queue queue1() {
return new Queue(
env.getRequiredProperty("queue1name"),
true,
false,
true;
}
#Bean
public Queue queue2() {
return new Queue(
env.getRequiredProperty("queue2name"),
true,
false,
true);
}
i autowire the rabbittemplate and call it with publisher confirm call backs like given below
Message amqpMessage = new Message(message.getBytes(), new MessageProperties());
rabbitTemplate.setConfirmCallback((cdata, ack, cause) -> {
System.out.println("Confirm callback"+ ack +" for "+cdata.toString());
});
rabbitTemplate.setReturnCallback((msg,replyCode,replyText,
exchange, routingKey)->{
System.out.println("call back returned for "+ routingKey);
});
rabbitTemplate.setMandatory(true);
rabbitTemplate
.sendAndReceive(TOPIC_EXCHANGE_KEY,environment.getProperty(correlationData.getMessageType().getQueueName()),
amqpMessage, createCorrelationData(correlationData));
After a lot of debugging i found out that it is failing because the template is not getting registered as a listener in the new instances of PublisherCallbackChannelImpl which are created by the subsequent calls after the first one . I am kind of lost as to whether this is a configuration issue or an issue with publisher confirm logic . Any insights to this will be really helpful. Thanks
Edit
I am using spring-amqp version 2.0.3-RELEASE and spring-messaging version 5.0.6-RELEASE
Edit2 : Debug logs for first and second calls
https://gist.github.com/jissjanardhanan/cbad51ba77fad3eda484d7c33c0b1517
rabbitTemplate.setUseDirectReplyToContainer(false);
#see https://github.com/spring-projects/spring-amqp/issues/846#issuecomment-439072434

NPE when trying to use Jetty async HTTP client

When trying to use Firebase Cloud Messaging by Google with the help of non-blocking Jetty HTTP client in a simple test case that I have prepared at GitHub -
private static final HttpClient sHttpClient = new HttpClient();
private static final Response.ContentListener sFcmListener = new Response.ContentListener() {
#Override
public void onContent(Response response, ByteBuffer content) {
if (response.getStatus() != 200) {
return;
}
String body = StandardCharsets.UTF_8.decode(content).toString();
System.out.printf("onContent: %s\n", body);
Map<String, Object> resp = (Map<String, Object>) JSON.parse(body);
try {
Object[] results = (Object[]) resp.get(FCM_RESULTS);
Map result = (Map) results[0];
String error = (String) result.get(FCM_ERROR);
if (FCM_NOT_REGISTERED.equals(error)) {
// TODO delete invalid FCM token from the database
}
} catch (Exception ignore) {
}
}
};
public static void main(String[] args) throws Exception {
sHttpClient.start();
sHttpClient.POST(FCM_URL)
.header(HttpHeader.AUTHORIZATION, FCM_KEY)
.header(HttpHeader.CONTENT_TYPE, "application/json")
.content(new StringContentProvider(JSON.toString(REQUEST)))
.onResponseContent(sFcmListener)
.send();
}
but unfortunately the execution fails immediately with NPE:
2017-06-30 10:46:41.312:INFO::main: Logging initialized #168ms to org.eclipse.jetty.util.log.StdErrLog
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.NullPointerException
at org.eclipse.jetty.client.util.FutureResponseListener.getResult(FutureResponseListener.java:118)
at org.eclipse.jetty.client.util.FutureResponseListener.get(FutureResponseListener.java:101)
at org.eclipse.jetty.client.HttpRequest.send(HttpRequest.java:682)
at de.afarber.fcmnotregistered.Main.main(Main.java:68)
Caused by: java.lang.NullPointerException
at org.eclipse.jetty.io.ssl.SslClientConnectionFactory.newConnection(SslClientConnectionFactory.java:59)
at org.eclipse.jetty.client.AbstractHttpClientTransport$ClientSelectorManager.newConnection(AbstractHttpClientTransport.java:191)
at org.eclipse.jetty.io.ManagedSelector.createEndPoint(ManagedSelector.java:420)
at org.eclipse.jetty.io.ManagedSelector.access$1600(ManagedSelector.java:61)
at org.eclipse.jetty.io.ManagedSelector$CreateEndPoint.run(ManagedSelector.java:599)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:199)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)
at java.lang.Thread.run(Thread.java:745)
Why does it happen please?
UPDATE:
I have switched to using BufferingResponseListener and the NPE is gone, but now the program prints java.net.NoRouteToHostException: No route to host even though the Google FCM endpoint is a well-known host:
private static final HttpClient sHttpClient = new HttpClient();
private static final BufferingResponseListener sFcmListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
System.err.println(result.getFailure()); // No route to host
return;
}
String body = getContentAsString(StandardCharsets.UTF_8);
System.out.printf("onContent: %s\n", body);
Map<String, Object> resp = (Map<String, Object>) JSON.parse(body);
try {
Object[] results = (Object[]) resp.get(FCM_RESULTS);
Map map = (Map) results[0];
String error = (String) map.get(FCM_ERROR);
if (FCM_NOT_REGISTERED.equals(error)) {
// TODO delete invalid FCM token from the database
}
} catch (Exception ex) {
System.err.println(ex);
}
}
};
public static void main(String[] args) throws Exception {
sHttpClient.start();
sHttpClient.POST(FCM_URL)
.header(HttpHeader.AUTHORIZATION, FCM_KEY)
.header(HttpHeader.CONTENT_TYPE, "application/json")
.content(new StringContentProvider(JSON.toString(REQUEST)))
.send(sFcmListener);
}
I get the No route to host for any FCM_URL value I try, why?
Adding SslContextFactory has helped me:
private static final SslContextFactory sFactory = new SslContextFactory();
private static final HttpClient sHttpClient = new HttpClient(sFactory);
private static final BufferingResponseListener sFcmListener = new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
if (!result.isSucceeded()) {
System.err.println(result.getFailure());
return;
}
String body = getContentAsString(StandardCharsets.UTF_8);
System.out.printf("onComplete: %s\n", body);
try {
Map<String, Object> resp = (Map<String, Object>) JSON.parse(body);
Object[] results = (Object[]) resp.get(FCM_RESULTS);
Map map = (Map) results[0];
String error = (String) map.get(FCM_ERROR);
System.out.printf("error: %s\n", error);
if (FCM_NOT_REGISTERED.equals(error) ||
FCM_MISSING_REGISTRATION.equals(error) ||
FCM_INVALID_REGISTRATION.equals(error)) {
// TODO delete invalid FCM token from the database
}
} catch (Exception ex) {
System.err.println(ex);
}
}
};
public static void main(String[] args) throws Exception {
sHttpClient.start();
sHttpClient.POST(FCM_URL)
.header(HttpHeader.AUTHORIZATION, FCM_KEY)
.header(HttpHeader.CONTENT_TYPE, "application/json")
.content(new StringContentProvider(JSON.toString(REQUEST)))
.send(sFcmListener);
}
The still open question I have is how to retrieve the invalid FCM token that I have used in the Jetty HTTP client request, so that I can delete it from my database on the response...

Debugging NullPointerException in OpenJDK code (inside Sun Classes)

In one of my clients logs I've seen an exception from Sun classes. The client uses OpenJDK 1.8.0_91.
I've tried to reproduce it without any luck.
From our logs, it seems like I'm getting the exception during Shutdown of the JVM (in ShutdownHook).
The issue is that this code works during the lifetime of the program and sends all the data as expected, however during shutdown, from time to time, we are getting this NPE.
Any ideas on how to solve? I've tried to have a look at the source code but for some reason I couldn't find it.
Here's the stack trace:
2016-07-08 11:07:58,426 ERROR [Thread-0] [HttpClient] Failed to send 'POST' request to 'https://prod-x-gw.mycompany.co/api/v2/testDoMagic/'. Error: java.lang.NullPointerException
java.lang.NullPointerException: null
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1158) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:999) ~[na:1.8.0_91]
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1283) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1258) ~[na:1.8.0_91]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250) ~[na:1.8.0_91]
at com.my.company.HttpClient.writeRequestBodyToOutputStream(HttpClient.java:152) ~[na:na]
at com.my.company.HttpClient.sendRequest(HttpClient.java:52) ~[na:na]
at com.my.company.JsonClient.sendHttpRequest(JsonClient.java:187) [na:na]
at com.my.company.JsonClient.postRequest(JsonClient.java:92) [na:na]
at com.my.company.JsonClient.postRequest(JsonClient.java:86) [na:na]
at com.my.company.DoMagicServiceProxy.sendRequest(DoMagicServiceProxy.java:59) [na:na]
at com.my.company.DoMagicServiceProxy.submitDoMagic(DoMagicServiceProxy.java:48) [na:na]
at com.my.company.DoMagicQueueSender$2.process(DoMagicQueueSender.java:108) [na:na]
at com.mycompany..commons.ChunksProcessor.processAsChunks(ChunksProcessor.java:35) [na:na]
at com.my.company.DoMagicQueueSender$1.execute(DoMagicQueueSender.java:89) [na:na]
at com.my.company.DoMagicQueueSender.shutdown(DoMagicQueueSender.java:46) [na:na]
at com.mycompany.DoMagicManager.shutDown(DoMagicManager.java:77) [na:na]
at com.mycompany.AM.shutdown(AM.java:145) [na:na]
at com.mycompany.AM.access$000(AM.java:17) [na:na]
at com.mycompany.AM$1.run(AM.java:157) [na:na]
2016-07-08 11:07:58,437 ERROR [Thread-0] [DoMagicServiceProxy] Failed while trying to submit DoMagic. Error:
java.lang.RuntimeException: Failed to send 'POST' request to 'https://prod-x-gw.mycompany.co/api/v2/testDoMagic/'. Error: java.lang.NullPointerException
at com.my.company.HttpClient.sendRequest(HttpClient.java:70) ~[na:na]
at com.my.company.JsonClient.sendHttpRequest(JsonClient.java:187) ~[na:na]
at com.my.company.JsonClient.postRequest(JsonClient.java:92) ~[na:na]
at com.my.company.JsonClient.postRequest(JsonClient.java:86) ~[na:na]
at com.my.company.DoMagicServiceProxy.sendRequest(DoMagicServiceProxy.java:59) ~[na:na]
at com.my.company.DoMagicServiceProxy.submitDoMagic(DoMagicServiceProxy.java:48) ~[na:na]
at com.my.company.DoMagicQueueSender$2.process(DoMagicQueueSender.java:108) [na:na]
at com.mycompany.commons.ChunksProcessor.processAsChunks(ChunksProcessor.java:35) [na:na]
at com.my.company.DoMagicQueueSender$1.execute(DoMagicQueueSender.java:89) [na:na]
at com.my.company.DoMagicQueueSender.shutdown(DoMagicQueueSender.java:46) [na:na]
at com.mycompany.DoMagicManager.shutDown(DoMagicManager.java:77) [na:na]
at com.mycompany.AM.shutdown(AM.java:145) [na:na]
at com.mycompany.AM.access$000(AM.java:17) [na:na]
at com.mycompany.AM$1.run(AM.java:157) [na:na]
Caused by: java.lang.NullPointerException: null
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1158) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:999) ~[na:1.8.0_91]
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1283) ~[na:1.8.0_91]
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1258) ~[na:1.8.0_91]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250) ~[na:1.8.0_91]
at com.my.company.HttpClient.writeRequestBodyToOutputStream(HttpClient.java:152) ~[na:na]
at com.my.company.HttpClient.sendRequest(HttpClient.java:52) ~[na:na]
... 13 common frames omitted
If that's helps, I'm my HttpClient implementation:
public class HttpClient {
private int readTimeoutInMS;
private int connectTimeoutInMS;
private String charset;
private final int SECOND = 1000;
private ILogFactory logFactory;
private ILogger log;
public HttpClient(){
//By default, max timeout will be 130 seconds - 10 seconds to connect, and 120 seconds to read the final byte.
connectTimeoutInMS = 10 * SECOND;
readTimeoutInMS = 120 * SECOND;
charset = "utf-8";
}
public void init() {
if (log == null) {
log = getLogger();
}
}
public HttpResponse sendRequest(HttpRequest request)
{
log.info("sendRequest was called. Remote url:'" + request.getUrl() + "'.");
HttpRequestMethods requestMethod = request.getRequestMethod();
HttpURLConnection connection = null;
boolean originalFollowRedirects = HttpURLConnection.getFollowRedirects();
try{
URL targetUrl = new URL(request.getUrl());
connection = (HttpURLConnection) targetUrl.openConnection();
setupConnectionObject(request, requestMethod, connection);
if (requestMethod == HttpRequestMethods.POST){
writeRequestBodyToOutputStream(request, connection);
}
HttpResponse response = new HttpResponse();
response.setStatusCode(connection.getResponseCode());
if (response.getStatusCode() >= 400) {
response.setResponseStream(connection.getErrorStream());
}
else {
response.setResponseStream(connection.getInputStream());
}
return response;
}catch (Exception e)
{
String msg = String.format("Failed to send '%s' request to '%s'. Error: %s", requestMethod, request.getUrl(), e);
log.error(msg,e);
throw new RuntimeException(msg, e);
}
finally {
HttpURLConnection.setFollowRedirects(originalFollowRedirects);
}
}
public int getReadTimeoutInMS() {
return readTimeoutInMS;
}
public void setReadTimeoutInMS(int readTimeoutInMS) {
this.readTimeoutInMS = readTimeoutInMS;
}
public int getConnectTimeoutInMS() {
return connectTimeoutInMS;
}
public void setConnectTimeoutInMS(int connectTimeoutInMS) {
this.connectTimeoutInMS = connectTimeoutInMS;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public ILogFactory getLogFactory() {
return logFactory;
}
public void setLogFactory(ILogFactory logFactory) {
this.logFactory = logFactory;
}
private void setupConnectionObject(HttpRequest request, HttpRequestMethods requestMethod, HttpURLConnection connection)throws ProtocolException {
connection.setRequestMethod(requestMethod.toString());
if (requestMethod == HttpRequestMethods.POST){
//Mark the HttpMethod as post.
connection.setDoOutput(true); // Allows to send message body on the output stream.
} else if (requestMethod == HttpRequestMethods.HEAD)
{
HttpURLConnection.setFollowRedirects(false);
connection.setRequestMethod("HEAD");
}
int connectTimeout = request.getConnectTimeout() != null? request.getConnectTimeout() : this.connectTimeoutInMS;
if (connectTimeout >= 0)
{
connection.setConnectTimeout(connectTimeout);
}
int readTimeout = request.getReadTimeout() != null? request.getReadTimeout() : this.readTimeoutInMS;
if (connectTimeout >= 0)
{
connection.setReadTimeout(readTimeout);
}
//Add HttpHeader
if (request.getHttpHeaders() != null)
{
for (Entry<String, String> httpHeader : request.getHttpHeaders().entrySet()) {
connection.setRequestProperty(httpHeader.getKey(), httpHeader.getValue());
}
}
if (request.getCompressRequestBody() && connection.getDoOutput()){ //only turn on for request with output
connection.setRequestProperty("Content-Encoding","gzip");
}
}
private void writeRequestBodyToOutputStream(HttpRequest request,
HttpURLConnection connection) throws IOException,
UnsupportedEncodingException {
DataOutputStream dataOutputSteam = null;
try{
dataOutputSteam = new DataOutputStream(connection.getOutputStream());
String requestBody = request.getRequestBody() != null ? request.getRequestBody() : "";
String bodyCharset = request.getCharset() != null ? request.getCharset() : this.charset;
byte[] requestBodyAsBytes = requestBody.getBytes(bodyCharset);
if (request.getCompressRequestBody()) {
//http://stackoverflow.com/questions/7153484/gzip-post-request-with-httpclient-in-java
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
gzos.write(requestBodyAsBytes);
}
byte[] gzippedBytes = baos.toByteArray();
requestBodyAsBytes = gzippedBytes;
}
dataOutputSteam.write(requestBodyAsBytes);
}
finally{
if (dataOutputSteam != null)
{
dataOutputSteam.close();
}
}
}
private ILogger getLogger() {
ILogger logger;
if (logFactory != null)
{
logger = logFactory.getLogger("HttpClient");
}
else
{
logger = NullLogger.INSTANCE;
}
return logger;
}
}
My guess is that you disconnect from that url when the connection is actually still in use during the final cleanup before exiting (maybe it's the result of some finalizer doing its job), the fact that it happens only from time to time implies that you are using that HttpURLConnection concurrently without proper synchronization.
Check the source here, in this version of HttpURLConnection.plainConnect0() that line should be 1156 instead of 1158.
Try to put a breakpoint on HttpURLConnection.disconnect() (only for that url?).

(400)Bad Request in PayPalAPISoapBindingStub.transactionSearch

After having a SSLHandshakeException using the paypal SOAP API (TransactionSearch), I have updated paypal_base.jar to the version indicated by paypal in the following link:
https://github.com/paypal/TLS-update
I have fixed that problem, however I have the following one:
mar 31, 2016 6:56:26 PM com.paypal.sdk.core.soap.SOAPAPICaller call
INFORMACIÓN: transactionSearch sent
mar 31, 2016 6:56:28 PM com.paypal.sdk.exceptions.TransactionException <init>
GRAVE: (400)Bad Request
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.paypal.sdk.core.soap.SOAPAPICaller.callSOAP(SOAPAPICaller.java:462)
at com.paypal.sdk.core.soap.SOAPAPICaller.call(SOAPAPICaller.java:382)
at com.paypal.sdk.services.CallerServices.call(CallerServices.java:125)
at t.main(t.java:42)
Caused by: (400)Bad Request
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:744)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.paypal.soap.api.PayPalAPISoapBindingStub.transactionSearch(Unknown Source)
... 8 more
Any clue about this problem?
UPDATE:
This is the request:
TransactionSearchRequestType request = new TransactionSearchRequestType();
request.setStartDate(new GregorianCalendar());
CallerServices caller = new CallerServices();
try {
APIProfile profile = ProfileFactory.createSignatureAPIProfile();
profile.setAPIUsername("*********");
profile.setAPIPassword("*************");
profile.setSignature("*******************************************");
profile.setEnvironment("sandbox");
caller.setAPIProfile(profile);
TransactionSearchResponseType response = (TransactionSearchResponseType) caller.call("TransactionSearch", request);
} catch (PayPalException e) {
System.out.println("PaypalCaller: Error calling Paypal webservice " + e);
} catch (Exception e) {
System.out.println(e.getMessage() + e);
} catch (Throwable e) {
System.out.println(e.getMessage() + e);
}
I was able to solve the problem. I have used another paypal library that can be used to do the same:
https://github.com/paypal/merchant-sdk-java
Code:
TransactionSearchReq txnreq = new TransactionSearchReq();
TransactionSearchRequestType requestType = new TransactionSearchRequestType();
requestType.setStartDate("2016-03-28T00:00:00.000Z");
txnreq.setTransactionSearchRequest(requestType);
PayPalAPIInterfaceServiceService service;
try {
Map<String, String> sdkConfig = new HashMap<String, String>();
sdkConfig.put("mode", "sandbox");
sdkConfig.put("acct1.UserName", "***********");
sdkConfig.put("acct1.Password", "***************");
sdkConfig.put("acct1.Signature","*****************************");
service = new PayPalAPIInterfaceServiceService(sdkConfig);
TransactionSearchResponseType response = service.transactionSearch(txnreq);
} catch (Exception e) {
e.printStackTrace();
}

Solr 4 with basic authentication

I am trying to connect to solr using solrj. My solr instance runs in jetty and is protected with basic authentication. I found these links that contain relevant information.
http://grokbase.com/t/lucene/solr-user/1288xjjbwx/http-basic-authentication-with-httpsolrserver
Preemptive Basic authentication with Apache HttpClient 4
However, I still get the following exception:
Caused by: org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:822)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at org.apache.solr.client.solrj.impl.HttpSolrServer.request(HttpSolrServer.java:352)
... 5 more
Caused by: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity.
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:625)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:464)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
... 8 more
I have also attached a snippet of the code I am using.
public static void main(String[] args) throws SolrServerException, IOException {
HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
DefaultHttpClient m_client =(DefaultHttpClient)server.getHttpClient();
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
m_client.addRequestInterceptor(new PreemptiveAuthInterceptor(),0);
(((DefaultHttpClient)m_client).getCredentialsProvider()).setCredentials(new AuthScope("localhost",8983), credentials);
SolrInputDocument document = new SolrInputDocument();
document.addField("id",123213);
server.add(document);
server.commit();
}
}
class PreemptiveAuthInterceptor implements HttpRequestInterceptor {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
// If no auth scheme avaialble yet, try to initialize it
// preemptively
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authScheme != null) {
Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.setAuthScheme(authScheme);
authState.setCredentials(creds);
}
}
}
Can anyone point me in the right direction? Thanks !!
i had the same problem when implementing partial documents update. i solved the problem by implementing PreemptiveAuthInterceptor. see below code
PoolingClientConnectionManager cxMgr = new PoolingClientConnectionManager(
SchemeRegistryFactory.createDefault());
cxMgr.setMaxTotal(100);
cxMgr.setDefaultMaxPerRoute(20);
DefaultHttpClient httpclient = new DefaultHttpClient(cxMgr);
httpclient.addRequestInterceptor(
new PreemptiveAuthInterceptor(), 0);
httpclient.getCredentialsProvider().setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(solrDto.getUsername(),
solrDto.getPassword()));
HttpSolrServer solrServerInstance = new HttpSolrServer(solrDto.getUrl(),
httpclient);
solrServerInstance.setRequestWriter(new BinaryRequestWriter());
solrServerInstance.setAllowCompression(true);
You also need:
private class PreemptiveAuthInterceptor implements HttpRequestInterceptor {
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
// If no auth scheme avaialble yet, try to initialize it
// preemptively
if (authState.getAuthScheme() == null) {
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
Credentials creds = credsProvider.getCredentials(new AuthScope(
targetHost.getHostName(), targetHost.getPort()));
if (creds == null)
throw new HttpException(
"No credentials for preemptive authentication");
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
According to the Solr Security - SolrJ section on Solr Wiki you should be able to do the following:
public static void main(String[] args) throws SolrServerException, IOException {
HttpSolrServer server = new HttpSolrServer("http://localhost:8983/solr/");
HttpClientUtil.setBasicAuth(server.getHttpClient(), USERNAME, PASSWORD);
SolrInputDocument document = new SolrInputDocument();
document.addField("id",123213);
server.add(document);
server.commit();
}
You need to add the JAR solr-solrj-4.0.0.jar for HttpClientUtil.
Then use the below code:
HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/"+url);
HttpClientUtil.setBasicAuth((DefaultHttpClient) solrServer.getHttpClient(), "USERNAME", "PASSWORD");
That worked for me on Jdk 1.6 and tomcat 6