Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Jersey JAVA REST Client giving Error 500 “BAD Request” for POST request, while POSTMAN is able POST to same SDC REST API

0 down vote favorite I am trying to post form data through a JAVA Jersey REST client but i receive the response code 500 and an according exception:

java.lang.RuntimeException: Failed with HTTP error code : 500 The same request from POSTMAN(Chrome Extention) works successfully.

I am making a POST request to StreamSets Data Collector API.

Below is my Code

public static String testUploadService(String httpURL, File filePath)  throws Exception {

// local variables
ClientConfig clientConfig = null;
Client client = null;
WebTarget webTarget = null;
Invocation.Builder invocationBuilder = null;
Response response = null;
FileDataBodyPart fileDataBodyPart = null;
FormDataMultiPart formDataMultiPart = null;
int responseCode;
String responseMessageFromServer = null;
String responseString = null;
  String name = "*******";
String password = "*******";
String authString = name + ":" + password;
String sdc="sdc";
byte[] encoding = Base64.getEncoder().encode(authString.getBytes());
byte[] encoding2 = Base64.getEncoder().encode(sdc.getBytes());
String USER_PASS = new String(encoding);
String auth2=new String(encoding2);

try{

    ClientConfig cc = new ClientConfig();
    cc.register(MultiPartFeature.class);

    try {
    client = new JerseywithSSL().initClient(cc);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) { 
    e.printStackTrace();
    }
    webTarget = client.target(httpURL);

    // set file upload values
    fileDataBodyPart = new FileDataBodyPart("uploadFile", filePath, MediaType.MULTIPART_FORM_DATA_TYPE);
    formDataMultiPart = new FormDataMultiPart();
    formDataMultiPart.bodyPart(fileDataBodyPart);

    // invoke service
    invocationBuilder = webTarget.request();
              invocationBuilder.header("Authorization", "Basic " + USER_PASS);
              invocationBuilder.header("X-Requested-By","SDC"); //Additional Header requiered by Streamsets RestAPI
             invocationBuilder.header("Content-type", "multipart/form-data");
    response = invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

    // get response code
    responseCode = response.getStatus();
    System.out.println("Response code: " + responseCode);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed with HTTP error code : " + responseCode);
    }

    // get response message
    responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
    System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

    // get response string
    responseString = response.readEntity(String.class);
}
catch(Exception ex) {
    ex.printStackTrace();
}
finally{
    // release resources, if any
    fileDataBodyPart.cleanup();
    formDataMultiPart.cleanup();
    formDataMultiPart.close();
    response.close();
    client.close();
}
return responseString;
}
}

I can't figure out whether its an issue with forming a multipart or is it an issue on the server side and if its the former than where exactly am I going wrong?

Jersey JAVA REST Client giving Error 500 “BAD Request” for POST request, while POSTMAN is able POST to same SDC REST API

0 down vote favorite I am trying to post form data through a JAVA Jersey REST client but i receive the response code 500 and an according exception:

java.lang.RuntimeException: Failed with HTTP error code : 500 The same request from POSTMAN(Chrome Extention) works successfully.

I am making a POST request to StreamSets Data Collector API.

Below is my Code

public static String testUploadService(String httpURL, File filePath)  throws Exception {

// local variables
ClientConfig clientConfig = null;
Client client = null;
WebTarget webTarget = null;
Invocation.Builder invocationBuilder = null;
Response response = null;
FileDataBodyPart fileDataBodyPart = null;
FormDataMultiPart formDataMultiPart = null;
int responseCode;
String responseMessageFromServer = null;
String responseString = null;
  String name = "*******";
String password = "*******";
String authString = name + ":" + password;
String sdc="sdc";
byte[] encoding = Base64.getEncoder().encode(authString.getBytes());
byte[] encoding2 = Base64.getEncoder().encode(sdc.getBytes());
String USER_PASS = new String(encoding);
String auth2=new String(encoding2);

try{

    ClientConfig cc = new ClientConfig();
    cc.register(MultiPartFeature.class);

    try {
    client = new JerseywithSSL().initClient(cc);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) { 
    e.printStackTrace();
    }
    webTarget = client.target(httpURL);

    // set file upload values
    fileDataBodyPart = new FileDataBodyPart("uploadFile", filePath, MediaType.MULTIPART_FORM_DATA_TYPE);
    formDataMultiPart = new FormDataMultiPart();
    formDataMultiPart.bodyPart(fileDataBodyPart);

    // invoke service
    invocationBuilder = webTarget.request();
              invocationBuilder.header("Authorization", "Basic " + USER_PASS);
              invocationBuilder.header("X-Requested-By","SDC"); //Additional Header requiered by Streamsets RestAPI
             invocationBuilder.header("Content-type", "multipart/form-data");
    response = invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

    // get response code
    responseCode = response.getStatus();
    System.out.println("Response code: " + responseCode);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed with HTTP error code : " + responseCode);
    }

    // get response message
    responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
    System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

    // get response string
    responseString = response.readEntity(String.class);
}
catch(Exception ex) {
    ex.printStackTrace();
}
finally{
    // release resources, if any
    fileDataBodyPart.cleanup();
    formDataMultiPart.cleanup();
    formDataMultiPart.close();
    response.close();
    client.close();
}
return responseString;
}
}

I can't figure out whether its an issue with forming a multipart or is it an issue on the server side and if its the former than where exactly am I going wrong?

Jersey JAVA REST Client giving Error 500 “BAD Request” for POST request, while POSTMAN is able POST to same SDC REST API

I am trying to post form data through a JAVA Jersey REST client but i receive the response code 500 and an according exception:

java.lang.RuntimeException: Failed with HTTP error code : 500

The same request from POSTMAN(Chrome Extention) works successfully.

I am making a POST request to StreamSets Data Collector API.

Below is my Code

public static String testUploadService(String httpURL, File filePath)  throws Exception {

// local variables
ClientConfig clientConfig = null;
Client client = null;
WebTarget webTarget = null;
Invocation.Builder invocationBuilder = null;
Response response = null;
FileDataBodyPart fileDataBodyPart = null;
FormDataMultiPart formDataMultiPart = null;
int responseCode;
String responseMessageFromServer = null;
String responseString = null;
  String name = "*******";
String password = "*******";
String authString = name + ":" + password;
String sdc="sdc";
byte[] encoding = Base64.getEncoder().encode(authString.getBytes());
byte[] encoding2 = Base64.getEncoder().encode(sdc.getBytes());
String USER_PASS = new String(encoding);
String auth2=new String(encoding2);

try{

    ClientConfig cc = new ClientConfig();
    cc.register(MultiPartFeature.class);

    try {
    client = new JerseywithSSL().initClient(cc);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) { 
    e.printStackTrace();
    }
    webTarget = client.target(httpURL);

    // set file upload values
    fileDataBodyPart = new FileDataBodyPart("uploadFile", filePath, MediaType.MULTIPART_FORM_DATA_TYPE);
    formDataMultiPart = new FormDataMultiPart();
    formDataMultiPart.bodyPart(fileDataBodyPart);

    // invoke service
    invocationBuilder = webTarget.request();
              invocationBuilder.header("Authorization", "Basic " + USER_PASS);
              invocationBuilder.header("X-Requested-By","SDC"); //Additional Header requiered by Streamsets RestAPI
             invocationBuilder.header("Content-type", "multipart/form-data");
    response = invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

    // get response code
    responseCode = response.getStatus();
    System.out.println("Response code: " + responseCode);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed with HTTP error code : " + responseCode);
    }

    // get response message
    responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
    System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

    // get response string
    responseString = response.readEntity(String.class);
}
catch(Exception ex) {
    ex.printStackTrace();
}
finally{
    // release resources, if any
    fileDataBodyPart.cleanup();
    formDataMultiPart.cleanup();
    formDataMultiPart.close();
    response.close();
    client.close();
}
return responseString;
}
}

I can't figure out whether its an issue with forming a multipart or is it an issue on the server side and if its the former than where exactly am I going wrong?

Jersey JAVA REST Client giving Error 500 “BAD Request” for POST request, while POSTMAN is able POST to same SDC REST API

I am trying to post form data through a JAVA Jersey REST client but i receive the response code 500 and an according exception:

java.lang.RuntimeException: Failed with HTTP error code : 500

The same request from POSTMAN(Chrome Extention) works successfully.

I am making a POST request to StreamSets Data Collector API.

My POM.xml is

   <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
 instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
 4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vijay</groupId>
<artifactId>mavenproject2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
        <jersey.version>2.12</jersey.version>
<jersey.scope>compile</jersey.scope>
<compileSource>1.7</compileSource>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Jersey core Servlet 2.x implementation -->
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>${jersey.version}</version>
    <scope>${jersey.scope}</scope>
</dependency>

<!-- Jersey Multipart entity providers support module -->
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>${jersey.version}</version>
    <scope>${jersey.scope}</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-apache-connector</artifactId>
<version>2.12</version>
<scope>test</scope>

</dependency> </dependencies> </project>

Below is my Code

import java.io.File;
import java.util.Base64;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.client.Client
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;

public static String testUploadService(String httpURL, File filePath)  throws Exception {

// local variables
ClientConfig clientConfig = null;
Client client = null;
WebTarget webTarget = null;
Invocation.Builder invocationBuilder = null;
Response response = null;
FileDataBodyPart fileDataBodyPart = null;
FormDataMultiPart formDataMultiPart = null;
int responseCode;
String responseMessageFromServer = null;
String responseString = null;
  String name = "*******";
String password = "*******";
String authString = name + ":" + password;
String sdc="sdc";
byte[] encoding = Base64.getEncoder().encode(authString.getBytes());
byte[] encoding2 = Base64.getEncoder().encode(sdc.getBytes());
String USER_PASS = new String(encoding);
String auth2=new String(encoding2);

try{

    ClientConfig cc = new ClientConfig();
    cc.register(MultiPartFeature.class);

    try {
    client = new JerseywithSSL().initClient(cc);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) { 
    e.printStackTrace();
    }
    webTarget = client.target(httpURL);

    // set file upload values
    fileDataBodyPart = new FileDataBodyPart("uploadFile", filePath, MediaType.MULTIPART_FORM_DATA_TYPE);
    formDataMultiPart = new FormDataMultiPart();
    formDataMultiPart.bodyPart(fileDataBodyPart);

    // invoke service
    invocationBuilder = webTarget.request();
              invocationBuilder.header("Authorization", "Basic " + USER_PASS);
              invocationBuilder.header("X-Requested-By","SDC"); //Additional Header requiered by Streamsets RestAPI
             invocationBuilder.header("Content-type", "multipart/form-data");
    response = invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

    // get response code
    responseCode = response.getStatus();
    System.out.println("Response code: " + responseCode);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed with HTTP error code : " + responseCode);
    }

    // get response message
    responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
    System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

    // get response string
    responseString = response.readEntity(String.class);
}
catch(Exception ex) {
    ex.printStackTrace();
}
finally{
    // release resources, if any
    fileDataBodyPart.cleanup();
    formDataMultiPart.cleanup();
    formDataMultiPart.close();
    response.close();
    client.close();
}
return responseString;
}
}

I am also calling this class to build my Client(which basically let me connects to it without SSL certificate error)

import javax.net.ssl.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Configuration;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created by Aleksandr Panzin (alex@panz.in)
 */
public class JerseywithSSL {

public Client initClient(Configuration config) throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext ctx = SSLContext.getInstance("SSL");
    ctx.init(null, certs, new SecureRandom());

    return ClientBuilder.newBuilder()
            .withConfig(config)
            .hostnameVerifier(new TrustAllHostNameVerifier())
            .sslContext(ctx)
            .build();
}

TrustManager[] certs = new TrustManager[]{
        new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        }
};

public static class TrustAllHostNameVerifier implements HostnameVerifier {

    public boolean verify(String hostname, SSLSession session) {
        return true;
    }

}

}

After Diging further into it I got following StackTrace

    responseString : {
  "RemoteException" : {
    "message" : "java.lang.NullPointerException: in is null",
    "errorCode" : "CONTAINER_0000",
    "localizedMessage" : "in is null",
    "exception" : "NullPointerException",
    "javaClassName" : "java.lang.NullPointerException",
    "stackTrace" : "java.lang.NullPointerException: in is null\n\tat java.util.zip.ZipInputStream.responseString : {
  "RemoteException" : {
    "message" : "java.lang.NullPointerException: in is null",
    "errorCode" : "CONTAINER_0000",
    "localizedMessage" : "in is null",
    "exception" : "NullPointerException",
    "javaClassName" : "java.lang.NullPointerException",
    "stackTrace" : "java.lang.NullPointerException: in is null\n\tat java.util.zip.ZipInputStream.<init>(ZipInputStream.java:101)\n\tat java.util.zip.ZipInputStream.<init>(ZipInputStream.java:80)\n\tat com.streamsets.datacollector.restapi.PipelineStoreResource.importPipelines(PipelineStoreResource.java:551)\n\tat sun.reflect.GeneratedMethodAccessor573.invoke(Unknown Source)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)\n\tat org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)\n\tat org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)\n\tat org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)\n\tat org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)\n\tat org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)\n\tat org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)\n\tat org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:315)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:297)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:267)\n\tat org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)\n\tat org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)\n\tat org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)\n\tat org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)\n\tat org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)\n\tat org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1634)\n\tat com.streamsets.datacollector.http.GroupsInScopeFilter.lambda$doFilter$0(GroupsInScopeFilter.java:82)\n\tat com.streamsets.datacollector.security.GroupsInScope.execute(GroupsInScope.java:33)\n\tat com.streamsets.datacollector.http.GroupsInScopeFilter.doFilter(GroupsInScopeFilter.java:81)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621)\n\tat org.eclipse.jetty.servlets.CrossOriginFilter.handle(CrossOriginFilter.java:308)\n\tat org.eclipse.jetty.servlets.CrossOriginFilter.doFilter(CrossOriginFilter.java:262)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621)\n\tat com.streamsets.datacollector.http.LocaleDetectorFilter.doFilter(LocaleDetectorFilter.java:39)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621)\n\tat com.streamsets.pipeline.http.MDCFilter.doFilter(MDCFilter.java:47)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621)\n\tat org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:541)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)\n\tat org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:494)\n\tat org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:513)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:190)\n\tat org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1592)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1239)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)\n\tat org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:481)\n\tat org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1561)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1141)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\n\tat org.eclipse.jetty.rewrite.handler.RewriteHandler.handle(RewriteHandler.java:335)\n\tat org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:118)\n\tat org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\n\tat org.eclipse.jetty.server.Server.handle(Server.java:564)\n\tat org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)\n\tat org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)\n\tat org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)\n\tat org.eclipse.jetty.io.ssl.SslConnection.onFillable(SslConnection.java:258)\n\tat org.eclipse.jetty.io.ssl.SslConnection$3.succeeded(SslConnection.java:147)\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)\n\tat org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)\n\tat org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:122)\n\tat org.eclipse.jetty.util.thread.strategy.ExecutingExecutionStrategy.invoke(ExecutingExecutionStrategy.java:58)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:201)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:133)\n\tat org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)\n\tat org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)\n\tat java.lang.Thread.run(Thread.java:748)\n"
  }
}
}

I can't figure out whether its an issue with forming a multipart or is it an issue on the server side and if its the former than where exactly am I going wrong?

Jersey JAVA REST Client giving Error 500 “BAD Request” for POST request, while POSTMAN is able POST to same SDC REST API

I am trying to post form data through a JAVA Jersey REST client but i receive the response code 500 and an according exception:

java.lang.RuntimeException: Failed with HTTP error code : 500

The same request from POSTMAN(Chrome Extention) works successfully.

I am making a POST request to StreamSets Data Collector API.

My POM.xml is

   <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
 instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-
 4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.vijay</groupId>
<artifactId>mavenproject2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
        <jersey.version>2.12</jersey.version>
<jersey.scope>compile</jersey.scope>
<compileSource>1.7</compileSource>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Jersey core Servlet 2.x implementation -->
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet-core</artifactId>
    <version>${jersey.version}</version>
    <scope>${jersey.scope}</scope>
</dependency>

<!-- Jersey Multipart entity providers support module -->
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>${jersey.version}</version>
    <scope>${jersey.scope}</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.connectors</groupId>
<artifactId>jersey-apache-connector</artifactId>
<version>2.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

</dependency> </dependencies> </project>

Below is my Code

import java.io.File;
import java.util.Base64;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.client.Client
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;

public static String testUploadService(String httpURL, File filePath)  throws Exception {

// local variables
ClientConfig clientConfig = null;
Client client = null;
WebTarget webTarget = null;
Invocation.Builder invocationBuilder = null;
Response response = null;
FileDataBodyPart fileDataBodyPart = null;
FormDataMultiPart formDataMultiPart = null;
int responseCode;
String responseMessageFromServer = null;
String responseString = null;
  String name = "*******";
String password = "*******";
String authString = name + ":" + password;
String sdc="sdc";
byte[] encoding = Base64.getEncoder().encode(authString.getBytes());
byte[] encoding2 = Base64.getEncoder().encode(sdc.getBytes());
String USER_PASS = new String(encoding);
String auth2=new String(encoding2);

try{

    ClientConfig cc = new ClientConfig();
    cc.register(MultiPartFeature.class);

    try {
    client = new JerseywithSSL().initClient(cc);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) { 
    e.printStackTrace();
    }
    webTarget = client.target(httpURL);

    // set file upload values
    fileDataBodyPart = new FileDataBodyPart("uploadFile", filePath, MediaType.MULTIPART_FORM_DATA_TYPE);
    formDataMultiPart = new FormDataMultiPart();
    formDataMultiPart.bodyPart(fileDataBodyPart);

    // invoke service
    invocationBuilder = webTarget.request();
              invocationBuilder.header("Authorization", "Basic " + USER_PASS);
              invocationBuilder.header("X-Requested-By","SDC"); //Additional Header requiered by Streamsets RestAPI
             invocationBuilder.header("Content-type", "multipart/form-data");
    response = invocationBuilder.post(Entity.entity(formDataMultiPart, MediaType.MULTIPART_FORM_DATA));

    // get response code
    responseCode = response.getStatus();
    System.out.println("Response code: " + responseCode);

    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed with HTTP error code : " + responseCode);
    }

    // get response message
    responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
    System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);

    // get response string
    responseString = response.readEntity(String.class);
}
catch(Exception ex) {
    ex.printStackTrace();
}
finally{
    // release resources, if any
    fileDataBodyPart.cleanup();
    formDataMultiPart.cleanup();
    formDataMultiPart.close();
    response.close();
    client.close();
}
return responseString;
}
}

I am also calling this class to build my Client(which basically let me connects to it without SSL certificate error)

import javax.net.ssl.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Configuration;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Created by Aleksandr Panzin (alex@panz.in)
 */
public class JerseywithSSL {

public Client initClient(Configuration config) throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext ctx = SSLContext.getInstance("SSL");
    ctx.init(null, certs, new SecureRandom());

    return ClientBuilder.newBuilder()
            .withConfig(config)
            .hostnameVerifier(new TrustAllHostNameVerifier())
            .sslContext(ctx)
            .build();
}

TrustManager[] certs = new TrustManager[]{
        new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        }
};

public static class TrustAllHostNameVerifier implements HostnameVerifier {

    public boolean verify(String hostname, SSLSession session) {
        return true;
    }

}

}

After Diging further into it I got following StackTrace

    responseString : {
  "RemoteException" : {
    "message" : "java.lang.NullPointerException: in is null",
    "errorCode" : "CONTAINER_0000",
    "localizedMessage" : "in is null",
    "exception" : "NullPointerException",
    "javaClassName" : "java.lang.NullPointerException",
    "stackTrace" : "java.lang.NullPointerException: in is null\n\tat java.util.zip.ZipInputStream.responseString : {
  "RemoteException" : {
    "message" : "java.lang.NullPointerException: in is null",
    "errorCode" : "CONTAINER_0000",
    "localizedMessage" : "in is null",
    "exception" : "NullPointerException",
    "javaClassName" : "java.lang.NullPointerException",
    "stackTrace" : "java.lang.NullPointerException: in is null\n\tat java.util.zip.ZipInputStream.<init>(ZipInputStream.java:101)\n\tat java.util.zip.ZipInputStream.<init>(ZipInputStream.java:80)\n\tat com.streamsets.datacollector.restapi.PipelineStoreResource.importPipelines(PipelineStoreResource.java:551)\n\tat sun.reflect.GeneratedMethodAccessor573.invoke(Unknown Source)\n\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n\tat java.lang.reflect.Method.invoke(Method.java:498)\n\tat org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)\n\tat org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)\n\tat org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)\n\tat org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)\n\tat org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)\n\tat org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)\n\tat org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)\n\tat org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)\n\tat org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:315)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:297)\n\tat org.glassfish.jersey.internal.Errors.process(Errors.java:267)\n\tat org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)\n\tat org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)\n\tat org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)\n\tat org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)\n\tat org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)\n\tat org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)\n\tat org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:841)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1634)\n\tat com.streamsets.datacollector.http.GroupsInScopeFilter.lambda$doFilter$0(GroupsInScopeFilter.java:82)\n\tat com.streamsets.datacollector.security.GroupsInScope.execute(GroupsInScope.java:33)\n\tat com.streamsets.datacollector.http.GroupsInScopeFilter.doFilter(GroupsInScopeFilter.java:81)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621)\n\tat org.eclipse.jetty.servlets.CrossOriginFilter.handle(CrossOriginFilter.java:308)\n\tat org.eclipse.jetty.servlets.CrossOriginFilter.doFilter(CrossOriginFilter.java:262)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621)\n\tat com.streamsets.datacollector.http.LocaleDetectorFilter.doFilter(LocaleDetectorFilter.java:39)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621)\n\tat com.streamsets.pipeline.http.MDCFilter.doFilter(MDCFilter.java:47)\n\tat org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1621)\n\tat org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:541)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)\n\tat org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:494)\n\tat org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:513)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:190)\n\tat org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1592)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:188)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1239)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:168)\n\tat org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:481)\n\tat org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1561)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:166)\n\tat org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1141)\n\tat org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\n\tat org.eclipse.jetty.rewrite.handler.RewriteHandler.handle(RewriteHandler.java:335)\n\tat org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:118)\n\tat org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)\n\tat org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)\n\tat org.eclipse.jetty.server.Server.handle(Server.java:564)\n\tat org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)\n\tat org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)\n\tat org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)\n\tat org.eclipse.jetty.io.ssl.SslConnection.onFillable(SslConnection.java:258)\n\tat org.eclipse.jetty.io.ssl.SslConnection$3.succeeded(SslConnection.java:147)\n\tat org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)\n\tat org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)\n\tat org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:122)\n\tat org.eclipse.jetty.util.thread.strategy.ExecutingExecutionStrategy.invoke(ExecutingExecutionStrategy.java:58)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:201)\n\tat org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:133)\n\tat org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)\n\tat org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)\n\tat java.lang.Thread.run(Thread.java:748)\n"
  }
}
}

I can't figure out whether its an issue with forming a multipart or is it an issue on the server side and if its the former than where exactly am I going wrong?