RESTful services HTTP Status 500 Servlet.init() error - web-services

Here's my code for java class named as Person.java:
package forage;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Person {
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Person() {
id = -1;
firstName = "";
lastName = "";
email = "";
}
public Person(long id, String firstName, String lastName, String email) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
private long id;
private String firstName;
private String lastName;
private String email;
}
Here's the code for resources that i created Personresources.java:
package forageresource;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Request;
import forage.Person;
#Path("/person")
public class PersonResource {
private final static String FIRST_NAME = "firstName";
private final static String LAST_NAME = "lastName";
private final static String EMAIL = "email";
private Person person = new Person(1, "Sample", "Person", "sample_person#jerseyrest.com");
// The #Context annotation allows us to have certain contextual objects
// injected into this class.
// UriInfo object allows us to get URI information (no kidding).
#Context
UriInfo uriInfo;
// Another "injected" object. This allows us to use the information that's
// part of any incoming request.
// We could, for example, get header information, or the requestor's address.
#Context
Request request;
// Basic "is the service running" test
#GET
#Produces(MediaType.TEXT_PLAIN)
public String respondAsReady() {
return "Demo service is ready!";
}
#GET
#Path("sample")
#Produces(MediaType.APPLICATION_JSON)
public Person getSamplePerson() {
System.out.println("Returning sample person: " + person.getFirstName() + " " + person.getLastName());
return person;
}
// Use data from the client source to create a new Person object, returned in JSON format.
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.APPLICATION_JSON)
public Person postPerson(
MultivaluedMap<String, String> personParams
) {
String firstName = personParams.getFirst(FIRST_NAME);
String lastName = personParams.getFirst(LAST_NAME);
String email = personParams.getFirst(EMAIL);
System.out.println("Storing posted " + firstName + " " + lastName + " " + email);
person.setFirstName(firstName);
person.setLastName(lastName);
person.setEmail(email);
System.out.println("person info: " + person.getFirstName() + " " + person.getLastName() + " " + person.getEmail());
return person;
}
}
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID"
version="3.0">
<display-name>JerseyRESTServer</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>Person</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
And finally the error:
HTTP Status 500 - Servlet.init() for servlet Jersey REST Service threw exception
type Exception report
message Servlet.init() for servlet Jersey REST Service threw exception
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet Jersey REST Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
root cause
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1359)
com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:180)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:799)
com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:795)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:509)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:339)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
note The full stack trace of the root cause is available in the Apache Tomcat/8.0.15 logs.
Apache Tomcat/8.0.15
I am new with REST services i don't know what is going wrong. Please guide me
I am using Apache Tomcat 8.0, Eclipse mars and i am referring from this site:
http://avilyne.com/?p=105

Related

Getting null values in REST web service PUT command

I am writing a PUT request REST web service. I have a POJO User.java having String name. Below is my POJO:
#XmlRootElement(name = "User")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String Name;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public User() {
}
public User(String Name) {
this.Name = Name;
}
}
My Web service is as below:
#Path("/user")
public class UserService {
#Path("/xml")
#PUT
#Produces({MediaType.APPLICATION_XML})
#Consumes({MediaType.APPLICATION_XML})
public User putUsers(User user){
System.out.println("***** Received User XML *****");
System.out.println("Name :: "+user.getName());
return user;
}
}
From Postman, i am sending below in Request body:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><User>
<Name>abcd</Name></User>
and PUT URL executed:
http://localhost:8080/rest/users/xml
But i am getting null as output:
***** Received User XML *****
Name :: null
Why am i not getting abcd as output?
Ok.. i found the answer..
1) I just added #XmlElement(name = "Name") above the getter getName().
2) Changed it to small n in the variable declaration Name as 'name'.
This fixed it.

javax.servlet.ServletException: Servlet.init() for servlet resteasy-servlet threw exception

type Exception report
message
description The server encountered an internal error () that prevented it from >fulfilling this request.
>exception
>javax.servlet.ServletException: Servlet.init() for servlet resteasy-servlet >threw exception
org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
java.lang.Thread.run(Thread.java:745)
root cause
>java.lang.RuntimeException: Failed to construct public com.ph.restful.main.StringServiceApplication()
org.jboss.resteasy.core.ConstructorInjectorImpl.construct(ConstructorInjectorImpl.java:144)
org.jboss.resteasy.spi.ResteasyDeployment.createFromInjectorFactory(ResteasyDeployment.java:282)
org.jboss.resteasy.spi.ResteasyDeployment.createApplication(ResteasyDeployment.java:259)
org.jboss.resteasy.spi.ResteasyDeployment.start(ResteasyDeployment.java:220)
org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.init(ServletContainerDispatcher.java:67)
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.init(HttpServletDispatcher.java:36)
org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
java.lang.Thread.run(Thread.java:745)
root cause
>java.lang.StackOverflowError
java.util.HashMap.init(HashMap.java:330)
java.util.HashMap.<init>(HashMap.java:262)
java.util.HashMap.<init>(HashMap.java:281)
java.util.HashSet.<init>(HashSet.java:103)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:12)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:15)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:15)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:15)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:15)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:15)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:15)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:15)
com.ph.restful.main.StringServiceApplication.<init>(StringServiceApplication.java:15)
getting an error when I use my browser as http://localhost:8080/sample/rest/app/test that will return a json data type..
Product class
private String productname;
private String description;
private Integer price;
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
StringService class
#Path("/app")
public class StringService {
#GET
#Path("/test")
#Produces("application/json")
public Product printSample2(){
Product prod = new Product();
prod.setProductname("Alaska Milk");
prod.setDescription("Milk for all");
prod.setPrice(300);
return prod;
}
}
StringServiceApplication
public class StringServiceApplication extends Application{
private Set<Object> singletons = new HashSet<Object>();
public StringServiceApplication(){
singletons.add(new StringServiceApplication());
}
#Override
public Set<Object> getSingletons(){
return singletons;
}
}
my web.xml
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/rest</param-value>
</context-param>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.ph.restful.main.StringServiceApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
my jboss-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
<context-root>sample</context-root>
</jboss-web>
my libraries on build path
-javassist-3.12.1.GA
-json-simple-1.1.1
-resteasy-jaxb-provider-2.2.1.ga
-resteasy-jaxrs-2.2.1.GA
-resteasy-jettison-provider
-scannotation-1.0.3
java.lang.StackOverflowError
public class StringServiceApplication extends Application{
public StringServiceApplication(){
singletons.add(new StringServiceApplication());
}
}
You're getting stack overflow because you are trying to instantiate the same class in its own constructor.
I think you mean to instantiate the StringService instead
public StringServiceApplication(){
singletons.add(new StringService());
}

Jackson not consuming the JSON root element

I'm using JAX-RS + Jersey to consume the web-service request and Jackson to translate JSON data:
#Path("/")
public class JAXRSRestController {
#Path("/jsonRequest")
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response submitJsonRequest(SampleObject sampleObject, #Context HttpHeaders headers)
{
Ack ack = new Ack();
ack.setUniqueId(sampleObject.getId());
ack.setType(sampleObject.getName());
return Response.ok().entity(ack).build();
}
}
Here if the request is in the below format, it would not be consumed:
{
"sampleObject": {
"id": "12345",
"name": "somename"
}
}
But if the request is in the below format, it will be consumed:
{
"id": "12345",
"name": "somename"
}
How can I make the controller consume the Json root element as well?
SampleObject class:
import org.codehaus.jackson.map.annotate.JsonRootName;
#XmlRootElement(name = "sampleObject")
#JsonRootName(value = "sampleObject")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "SampleObject", propOrder = {
"id",
"name"
})
public class SampleObject
{
protected String id;
protected String name;
public SampleObject(){}
public SampleObject(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
web.xml:
<?xml version="1.0" encoding= "UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<display-name>Wed Application</display-name>
<servlet>
<servlet-name>Jersey RESTFul WebSerivce</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.jaxrs.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTFul WebSerivce</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
There are two approaches I can think of. If this is a common occurrence in your application, I would recommend enabling unwrapping on your ObjectMapper. If this is a one-off situation, a wrapper object is not a bad option.
A. Enable Unwrapping
#JsonRootName will only apply if unwrapping is enabled on the ObjectMapper. You can accomplish this with a deserialization feature. Note that this will unwrap all requests:
public CustomObjectMapper() {
super();
enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
}
If you do not already have a custom ObjectMapper registered then you will need to add a provider to register your custom config with Jersey. This answer explains how do accomplish that.
B. Create a Wrapper
If you do not want to unwrap globally, you can create a simple wrapper object and omit the #JsonRootName annotation:
public class SampleObjectWrapper {
public SampleObject sampleObject;
}
Then update your resource method signature to accept the wrapper:
public Response submitJsonRequest(SampleObjectWrapper sampleObjectWrapper, #Context HttpHeaders headers)

getting an error with webservices

Im doing restfull webservices with soap using websphere and RAD. After generating my javaclient classes when I run the test class I get the following error. Ive been searching the web but not finding the correct solution. PLEASE HELP!
ERROR:
Check method call
org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
at org.apache.xerces.dom.CoreDocumentImpl.insertBefore(Unknown Source)
at org.apache.xerces.dom.NodeImpl.appendChild(Unknown Source)
at com.ibm.ws.webservices.engine.xmlsoap.SOAPPart.appendChild(SOAPPart.java:282)
at com.sun.xml.internal.bind.marshaller.SAX2DOMEx.startElement(SAX2DOMEx.java:177)
at com.sun.xml.internal.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:159)
at com.sun.xml.internal.ws.message.AbstractMessageImpl.readAsSOAPMessage(AbstractMessageImpl.java:194)
at com.sun.xml.internal.ws.handler.SOAPMessageContextImpl.getMessage(SOAPMessageContextImpl.java:80)
at test.CustomSoapHandler.handleMessage(CustomSoapHandler.java:37)
at test.CustomSoapHandler.handleMessage(CustomSoapHandler.java:1)
at com.sun.xml.internal.ws.handler.HandlerProcessor.callHandleMessage(HandlerProcessor.java:293)
at com.sun.xml.internal.ws.handler.HandlerProcessor.callHandlersRequest(HandlerProcessor.java:134)
at com.sun.xml.internal.ws.handler.ClientSOAPHandlerTube.callHandlersOnRequest(ClientSOAPHandlerTube.java:139)
at com.sun.xml.internal.ws.handler.HandlerTube.processRequest(HandlerTube.java:117)
at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Fiber.java:599)
at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Fiber.java:558)
at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Fiber.java:543)
at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Fiber.java:440)
at com.sun.xml.internal.ws.client.Stub.process(Stub.java:223)
at com.sun.xml.internal.ws.client.sei.SEIStub.doProcess(SEIStub.java:136)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:110)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:90)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:119)
at $Proxy33.getHistory(Unknown Source)
at test.ServiceTest.historyTest(ServiceTest.java:64)
at test.ServiceTest.main(ServiceTest.java:100)
Exception in thread "main" java.lang.ExceptionInInitializerError
at java.lang.J9VMInternals.initialize(J9VMInternals.java:227)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:90)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:119)
at $Proxy33.getHistory(Unknown Source)
at test.ServiceTest.historyTest(ServiceTest.java:64)
at test.ServiceTest.main(ServiceTest.java:100)
Caused by: java.lang.ClassCastException: com.ibm.xml.xlxp2.jaxb.JAXBContextImpl incompatible with com.sun.xml.internal.bind.api.JAXBRIContext
at java.lang.ClassCastException.<init>(ClassCastException.java:58)
at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.<clinit>(SOAPFaultBuilder.java:545)
at java.lang.J9VMInternals.initializeImpl(Native Method)
at java.lang.J9VMInternals.initialize(J9VMInternals.java:205)
... 6 more
Test Class:
package test;
import be.ipc.css.ws.GcssWebServiceService;
import be.ipc.css.ws.IGcssWebService;
import be.ipc.css.ws.InvalidItemIdStructureFault_Exception;
import be.ipc.css.ws.ProductNotAllowedFault_Exception;
import be.ipc.css.ws.common.Product;
import be.ipc.css.ws.history.GetHistoryInput;
import be.ipc.css.ws.history_output.GetHistoryOutput;
import be.ipc.css.ws.history_output.HistoryItem;
import be.ipc.css.ws.history_output.Type;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* <strong>Project: TODO: project name</strong><br/>
* <b>Url:</b> TODO: url<br/>
* <b>Date:</b> 15.05.14<br/>
* <b>Time:</b> 23:42 <br/>
* Copyright(C) 2014 IT Service Plus <br/>
* <b>Description:</b><br/>
* TODO: description
*/
public class ServiceTest {
private static Service webService;
private static IGcssWebService servicePort;
public void initService() throws MalformedURLException {
URL url = new URL("http://cs-demo.ipc.be/CSS_UA2/services/gcssWebService/1.0");
QName qname = new QName("http://ws.css.ipc.be/", "GcssWebServiceService");
/*java.util.Properties props = System.getProperties();
props.setProperty("http.proxyHost", "proxy.test.com");
props.setProperty("http.proxyPort", "8080");*/
webService = GcssWebServiceService.create(url, qname);
servicePort = webService.getPort(IGcssWebService.class);
try {
CustomSoapHandler sh = new CustomSoapHandler("user_us", "*******");
List<Handler> new_handlerChain = new ArrayList<Handler>();
new_handlerChain.add(sh);
((BindingProvider)servicePort).getBinding().setHandlerChain(new_handlerChain);
} catch (Throwable e) {
e.printStackTrace();
}
//((BindingProvider)servicePort).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "user_us");
//((BindingProvider)servicePort).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "*******");
}
public void historyTest() throws ProductNotAllowedFault_Exception, InvalidItemIdStructureFault_Exception {
GetHistoryInput input = new GetHistoryInput();
input.setItemId("CC027607063NL");
input.setProduct(Product.EPG);
System.out.println("Check method call");
GetHistoryOutput output = servicePort.getHistory(input);
System.out.println("Check result");
//Assert.assertNotNull(output);
//Assert.assertNotNull(output.getHistory());
//Assert.assertNotNull(output.getHistory().getHistoryItem());
System.out.println("Received: " + output.getHistory().getHistoryItem().size() + "elements:");
System.out.println("-----------------------");
for(int i=0;i<output.getHistory().getHistoryItem().size();i++) {
HistoryItem it = output.getHistory().getHistoryItem().get(i);
System.out.println("#" + i + ": id=" + it.getId() + ", type=" + it.getType().value());
}
System.out.println("Check 3 history items");
//Assert.assertEquals(3, output.getHistory().getHistoryItem().size());
HistoryItem it1 = output.getHistory().getHistoryItem().get(0);
HistoryItem it2 = output.getHistory().getHistoryItem().get(1);
HistoryItem it3 = output.getHistory().getHistoryItem().get(2);
/*Assert.assertEquals(Type.QUMQ, it1.getType());
Assert.assertEquals(161L, it1.getId());
Assert.assertEquals(Type.SUM, it2.getType());
Assert.assertEquals(652L, it2.getId());
Assert.assertEquals(Type.L_1_Q, it3.getType());
Assert.assertEquals(13742L, it3.getId());*/
}
public static void main(String[] args) {
ServiceTest test = new ServiceTest();
try {
test.initService();
test.historyTest();
} catch(Exception e ){
e.printStackTrace();
}
}
}
Soap Handler:
package test;
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.Set;
/**
* <strong>Project: TODO: project name</strong><br/>
* <b>Url:</b> TODO: url<br/>
* <b>Date:</b> 16.05.14<br/>
* <b>Time:</b> 0:48 <br/>
* Copyright(C) 2014 IT Service Plus <br/>
* <b>Description:</b><br/>
* TODO: description
*/
public class CustomSoapHandler implements SOAPHandler<SOAPMessageContext> {
private static final String AUTH_PREFIX = "wsse";
private static final String AUTH_NS =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
private String username;
private String password;
public CustomSoapHandler(String username, String password) {
this.username = username;
this.password = password;
}
public boolean handleMessage(SOAPMessageContext context) {
try {
SOAPEnvelope envelope =
context.getMessage().getSOAPPart().getEnvelope();
SOAPFactory soapFactory = SOAPFactory.newInstance();
SOAPElement wsSecHeaderElm =
soapFactory.createElement("Security", AUTH_PREFIX, AUTH_NS);
Name wsSecHdrMustUnderstandAttr =
soapFactory.createName("mustUnderstand", "S",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
wsSecHeaderElm.addAttribute(wsSecHdrMustUnderstandAttr, "1");
SOAPElement userNameTokenElm =
soapFactory.createElement("UsernameToken", AUTH_PREFIX,
AUTH_NS);
Name userNameTokenIdName =
soapFactory.createName("id", "wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
userNameTokenElm.addAttribute(userNameTokenIdName,
"UsernameToken-ORbTEPzNsEMDfzrI9sscVA22");
SOAPElement userNameElm =
soapFactory.createElement("Username", AUTH_PREFIX, AUTH_NS);
userNameElm.addTextNode(username);
SOAPElement passwdElm =
soapFactory.createElement("Password", AUTH_PREFIX, AUTH_NS);
Name passwdTypeAttr = soapFactory.createName("Type");
passwdElm.addAttribute(passwdTypeAttr,
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
passwdElm.addTextNode(password);
userNameTokenElm.addChildElement(userNameElm);
userNameTokenElm.addChildElement(passwdElm);
wsSecHeaderElm.addChildElement(userNameTokenElm);
if (envelope.getHeader() == null) {
SOAPHeader sh = envelope.addHeader();
sh.addChildElement(wsSecHeaderElm);
} else {
SOAPHeader sh = envelope.getHeader();
sh.addChildElement(wsSecHeaderElm);
}
} catch (Throwable e) {
e.printStackTrace();
}
return true;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void close(MessageContext context) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public Set<QName> getHeaders() {
return null;
}
}
The main reason for your error is incompatible JAXB implementation classes:
aused by: java.lang.ClassCastException: com.ibm.xml.xlxp2.jaxb.JAXBContextImpl incompatible with com.sun.xml.internal.bind.api.JAXBRIContext
Probably the best way to fix this is packaging your own version of JAXB within your application(inside the lib folder) and than change the class loader from WebSphere to be Parent Last.
After that, restart and try it again. If still doesn't work you can try adding your JAXB implementation libraries directly to the Application Server classloader. You can do that creating a directory under $WEBSPHERE_HOME/AppServer/classes and placing your JAXB implementation classes there. Be aware that this approach adds the dropped jars to all WebSphere instances running using this binary codebase.
You can learn more about WebSphere classloaders.
Hope this helps.

Web service soap header authentication

I have a web service, i want to authenticate the user from the soap header. That is, i want to check a token id (random number) in soap header and validate it against a value in my database and if the number matches i allow the request to go through otherwise i dont want to allow execution of my web method.
Is there any clean way of doing it using SOAP headers?
Thanks,
Mrinal Jaiswal
Have you looked into WS-Security? Assuming you're not already using it for something else, you could carry your token in the Username element, etc.
<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-1">
<wsse:Username>yourusername</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">yourpassword</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<yourbodygoeshere>
</soapenv:Body>
</soapenv:Envelope>
I created a web service using JDK API, and do a simple authentication by soap header.
This simple project provide two services:
login
get message from server
Client posts username and password in the soap body to server, if login successfully, the server will return a token in the soap header.
Clients calls getMessage service by including this token in the soap header, server check the token, if it is a logged in user, then return a success message, otherwise return a failed message.
The following is the code:
package com.aug.ws;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.WebParam.Mode;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.xml.ws.Holder;
//Service Endpoint Interface
#WebService
#SOAPBinding(style = Style.RPC)
public interface HelloWorld {
#WebMethod
void login(String userName, String password, #WebParam(header = true, mode = Mode.OUT, name = "token") Holder<String> token);
String getMessage(String message);
}
package com.aug.ws;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebParam.Mode;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.ws.Holder;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import com.sun.xml.internal.ws.api.message.Header;
import com.sun.xml.internal.ws.api.message.HeaderList;
import com.sun.xml.internal.ws.developer.JAXWSProperties;
#WebService(endpointInterface = "com.aug.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
private Map<String, String> authorizedUsers = new HashMap<String, String>();
#Resource
WebServiceContext wsctx;
#Override
#WebMethod
public void login(String userName, String password, #WebParam(header = true, mode = Mode.OUT, name = "token") Holder<String> token) {
if (("user1".equals(userName) && "pwd1".equals(password)) || ("user2".equals(userName) && "pwd2".equals(password))) {
String tokenValue = "authorizeduser1234" + userName;
token.value = tokenValue;
authorizedUsers.put(tokenValue, userName);
System.out.println("---------------- token: " + tokenValue);
}
}
#Override
#WebMethod
public String getMessage(String message) {
if (isLoggedInUser()) {
return "JAX-WS message: " + message;
}
return "Invalid access!";
}
/**
* Check token from SOAP Header
* #return
*/
private boolean isLoggedInUser() {
System.out.println("wsctx: " + wsctx);
MessageContext mctx = wsctx.getMessageContext();
HeaderList headerList = (HeaderList) mctx.get(JAXWSProperties.INBOUND_HEADER_LIST_PROPERTY);
String nameSpace = "http://ws.aug.com/";
QName token = new QName(nameSpace, "token");
try {
Header tokenHeader = headerList.get(token, true);
if (tokenHeader != null) {
String user = authorizedUsers.get(tokenHeader.getStringContent());
if (user != null) {
System.out.println(user + " has logged in.");
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
package com.aug.endpoint;
import javax.xml.ws.Endpoint;
import com.aug.ws.HelloWorldImpl;
public class HelloWorldPublisher {
/**
* #param args
*/
public static void main(String[] args) {
Endpoint.publish("http://localhost:9000/ws/hello", new HelloWorldImpl());
System.out.println("\nWeb service published # http://localhost:9000/ws/hello");
System.out.println("You may call the web service now");
}
}
package com.aug.client;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.aug.ws.HelloWorld;
import com.sun.xml.internal.ws.api.message.HeaderList;
import com.sun.xml.internal.ws.api.message.Headers;
import com.sun.xml.internal.ws.developer.JAXWSProperties;
import com.sun.xml.internal.ws.developer.WSBindingProvider;
public class HelloWorldClient {
private static final String WS_URL = "http://localhost:9000/ws/hello?wsdl";
private static final String NAME_SPACE = "http://ws.aug.com/";
public static String login() throws Exception {
URL url = new URL(WS_URL);
QName qname = new QName(NAME_SPACE, "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
hello.login("user1", "pwd1", null);
WSBindingProvider bp = (WSBindingProvider) hello;
HeaderList headerList = (HeaderList) bp.getResponseContext().get(JAXWSProperties.INBOUND_HEADER_LIST_PROPERTY);
bp.close();
return headerList.get(new QName(NAME_SPACE, "token"), true).getStringContent();
}
public static void getMessage() throws Exception {
String token = login();
System.out.println("token: " + token);
URL url = new URL(WS_URL);
QName qname = new QName(NAME_SPACE, "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
WSBindingProvider bp = (WSBindingProvider) hello;
bp.setOutboundHeaders(
Headers.create(new QName(NAME_SPACE, "token"), token)
);
System.out.println(hello.getMessage("hello world"));
bp.close();
}
public static void main(String[] args) throws Exception {
getMessage();
}
}