I have a webservice that I'm trying to invoke with the following client-side code:
import com.test.wsdl.CxfAdd;
import com.test.wsdl.CxfAddService;
import java.util.Map;
import javax.xml.ws.BindingProvider;
import org.apache.cxf.ws.addressing.AddressingProperties;
import org.apache.cxf.ws.addressing.AttributedURIType;
import org.apache.cxf.ws.addressing.EndpointReferenceType;
import org.apache.cxf.ws.addressing.JAXWSAConstants;
public class Main {
public static void main(String[] args) {
CxfAddService service = new CxfAddService();
CxfAdd client = service.getCxfAddPort();
Map<String, Object> requestContext = ((BindingProvider)client).getRequestContext();
AddressingProperties maps = new AddressingProperties();
EndpointReferenceType ref = new EndpointReferenceType();
AttributedURIType add = new AttributedURIType();
add.setValue("http://www.w3.org/2005/08/addressing/anonymous");
ref.setAddress(add);
maps.setReplyTo(ref);
maps.setFaultTo(ref);
requestContext.put(JAXWSAConstants.CLIENT_ADDRESSING_PROPERTIES, maps);
client.myMethodOneWay("Input message");
}
}
On the server-side (Tomcat), the webservice is implemented as the following:
CxfAdd.java:
package com.test.ws;
import javax.jws.Oneway;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.soap.Addressing;
#WebService(targetNamespace = "http://test.com/wsdl")
#Addressing(enabled = true, required = true)
public interface CxfAdd {
#WebResult(name = "response")
public abstract String myMethod(String message);
#WebResult(name="response")
#Oneway
public void myMethodOneWay(String message);
}
CxfAddImpl.java:
package com.test.ws;
import javax.annotation.Resource;
import javax.jws.Oneway;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.soap.Addressing;
#WebService
#Addressing
public class CxfAddImpl implements CxfAdd {
#Resource
WebServiceContext webServiceContext;
public String myMethod(String message) {
System.out.println("Invoking sayHello in " + getClass());
return "Hello " + message;
}
#Oneway
public void myMethodOneWay(String message) {
// TODO Auto-generated method stub
}
}
However, when I run the client-side code, at the server-side I get the following error:
INFO: Inbound Message
----------------------------
ID: 46
Address: http://localhost:8080/CxfAddressingServer/services/cxfadd
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml; charset=UTF-8
Headers: {Accept=[*/*], cache-control=[no-cache], connection=[keep-alive], Content-Length=[211], content-type=[text/xml; charset=UTF-8], host=[localhost:8080], pragma=[no-cache], SOAPAction=[""], user-agent=[Apache CXF 3.1.3]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:myMethodOneWay xmlns:ns2="http://test.com/wsdl"><arg0>Input message</arg0></ns2:myMethodOneWay></soap:Body></soap:Envelope>
--------------------------------------
Out 30, 2015 7:18:56 PM org.apache.cxf.ws.addressing.ContextUtils retrieveMAPs
WARNING: WS-Addressing - failed to retrieve Message Addressing Properties from context
It seems that I'm not sending the ws-addressing attributes, can anyone help me figure out what's wrong or missing in my code? Thank you.
In the client-side code, I've replaced the following:
CxfAdd client = service.getCxfAddPort();
With the following:
CxfAdd client = service.getCxfAddPort(
new org.apache.cxf.ws.addressing.WSAddressingFeature());
And it works now.
Solution was provided by someone else here:
http://www.coderanch.com/t/657413/Web-Services/java/CXF-Client-WS-Addressing-attributes
Related
I have a sample backend response coming as below:
When I try to map this response into the java object, I am getting following error.
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of com.mc.membersphere.model.MemberSummaryLabel[] out of START_OBJECT token
Seems like the issue with the body tag coming from API. Which has array of objects. I need help, how to handle this body tag arrays value in Java mapping?
Backend API Response:
{
"body": [{
"pcp": "KASSAM, Far",
"er12M": "0",
"ipAdmits12M": "0",
"ipReAdmits12M": "0",
"rx12M": "0",
"pastMedicalHistory": " ",
"erCost12M": "0.0"
}
]
}
Java Program to get the Rest data into the Java objects is as below.
import java.util.Collections;
import java.util.Properties;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.mc.membersphere.model.MemberSummaryLabel;
import com.mc.membersphere.utility.PropertyUtil;
public class TestRestclient implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(TestApi.class, args); }
private static Properties prop = PropertyUtil.getProperties();
#Override
public void run(String... args) throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
String getMVPSummaryUrl = prop.getProperty("getmvpmembersummary.url");
String url = getMVPSummaryUrl+"/"+"CA";
ResponseEntity<MemberSummaryLabel[]> response = restTemplate.exchange(url, HttpMethod.GET,entity, MemberSummaryLabel[].class);
if(response.getStatusCode()== HttpStatus.OK) {
for(MemberSummaryLabel memberSummaryLabel : response.getBody())
{
System.out.println(memberSummaryLabel.pcp);
}
//System.out.println("Print response" + response);
}
else {
System.out.println("Error");
}
}
}
MemberSummaryLabel is as below.
import com.fasterxml.jackson.annotation.JsonProperty;
public class MemberSummaryLabel {
#JsonProperty("pcp")
public String pcp;
#JsonProperty("er12M")
public Integer er12M;
#JsonProperty("ipAdmits12M")
public Integer ipAdmits12M;
#JsonProperty("ipReAdmits12M")
public Integer ipReAdmits12M;
#JsonProperty("rx12M")
public Integer rx12M;
#JsonProperty("pastMedicalHistory")
public String pastMedicalHistory;
#JsonProperty("erCost12M")
public Double erCost12M;
}
I see, its an issue with your mapping. Your response is in "body" and body contains list of MemberSummaryLabel. So, you need to have one more class as mentioned below,
public class Body{
#JsonProperty("body")
public List<MemberSummaryLabel> memberSummaryLabelList;
}
And your exchange method should return NewClass.
ResponseEntity<Body> response = restTemplate.exchange(url, HttpMethod.GET,entity, Body.class);
And for, iteration use,
for(MemberSummaryLabel memberSummaryLabel : response.getBody().getMemberSummaryLabelList()){
}
Edit:
I tried to implement the suggestions of #Durgpal Singh and #Nikhil. I changed the code so it looks like this.
Client:
Client client = ClientBuilder.newClient();
WebTarget target = client
.target("http://localhost:8087/api/ls3algorithm/" + petrinets + "/" + Integer.toString(k) + "/" + Float.toString(theta));
Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
Map<String, List<Map>> result_ = response.readEntity(new GenericType<Map<String, List<Map>>>() { });
result = (ArrayList<Map>) result_.get("data");
Server:
ArrayList<Map> result;
result = new Ls3Algorithm().execute(new File("petrinetze").getAbsolutePath(), k, theta);
Map<String, List<Map>> map = new HashMap<>();
map.put("data", result);
return Response.ok(map).build();
Unfortunately this leads to Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=interface java.util.Map, genericType=java.util.Map<java.lang.String, java.util.List<java.util.Map>>.
Where do I go wrong?
-------------------------------
I'm pretty new to RESTful web services and currently writing a microservice which provides a calculating algorithm. I'm testing the service as posted below.
Workflow:
Client saves some data in a MongoDB database and sends the names of the relevant files via #PathParam as part of the GET request. The server then retrieves the files from the MongoDB, processes its algorithm and sends back the result as List<Map> packed in a Response object.
Goal:
Transfer the result (List<Map>) as JSON and print it out on the client console.
Client:
package ls3test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
public class Ls3TransmissionTest {
final static String petrinets = "eins, zwei, drei, vier";
final static int k = 3;
final static float theta = 0.9f;
public static void main(String[] args) throws IOException {
[... save all the relevant files in the MongoDB ...]
ArrayList<Map> result = new ArrayList<Map>();
Client client = ClientBuilder.newClient();
WebTarget target = client
.target("http://localhost:8087/api/ls3algorithm/" + petrinets + "/" + Integer.toString(k) + "/" + Float.toString(theta));
Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
result = response.readEntity(new GenericType<ArrayList<Map>>() {
});
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(result);
}
}
Server:
package service;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
#SuppressWarnings("deprecation")
#Path("/ls3algorithm")
public class Resource {
// SLF4J is provided with Dropwizard
Logger log = LoggerFactory.getLogger(Resource.class);
#SuppressWarnings("rawtypes")
#GET
#Path("/{petrinets}/{k}/{theta}")
#Produces(MediaType.APPLICATION_JSON)
public Response ls3execute(#PathParam("petrinets") String petrinetNames, #PathParam("k") int k,
#PathParam("theta") float theta) {
[... get all the relevant files from the MongoDB ...]
List<Map> result;
Ls3Algorithm ls3Algorithm = new Ls3Algorithm();
result = ls3Algorithm.execute(new File("petrinetze").getAbsolutePath(), k, theta);
GenericEntity<List<Map>> entity = new GenericEntity<List<Map>>(result) {};
Response response = Response.ok(entity).build();
return response;
}
}
This is not working, the exception I get is posted below:
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=class java.util.ArrayList, genericType=java.util.ArrayList<java.util.Map>.
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:231)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:155)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1085)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:368)
at org.glassfish.jersey.client.InboundJaxrsResponse$2.call(InboundJaxrsResponse.java:126)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:419)
at org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:267)
at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:123)
at ls3test.Ls3TransmissionTest.main(Ls3TransmissionTest.java:89)
Ls3TransmissionTest.java:89 is ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
I spent plenty of time now doing research on this problem, but I cannot find an example that really fits it. What do I miss? Any help or hint is highly appreciated!
You can send a map. Like this
Map<String, Object> map = new HashMap<>();
map.put("data", entity);
Response.ok(map).build();
return Response;
Cannot see why do you need to wrap the List with GenericEntity. Something as simple as below will work:-
#SuppressWarnings("rawtypes")
#GET
#Path("/{petrinets}/{k}/{theta}")
#Produces(MediaType.APPLICATION_JSON)
public Response ls3execute(#PathParam("petrinets") String petrinetNames, #PathParam("k") int k,
#PathParam("theta") float theta) {
//[... get all the relevant files from the MongoDB ...]
List<Map> result;
Ls3Algorithm ls3Algorithm = new Ls3Algorithm();
result = ls3Algorithm.execute(new File("petrinetze").getAbsolutePath(), k, theta);
Response response = Response.ok(result).build();
return response;
}
And in the client side,
String result = response.readEntity(String.class);
return result;
I'm writing a RESTEasy client to connect with a RESTful service. The RESTful service looks as follows:
#Path("locations")
public class LocationService {
#POST
#Path("/myObjects")
#Produces({MediaType.APPLICATION_XML})
#Consumes({MediaType.APPLICATION_XML})
public List<MyObjects> CreateObjects( List<MyObjects> objList ) {
...
}
}
The MyObjects class include the proper XML annotations:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "my-objects")
public class MyObjects {
...
}
In my client, I have a list of MyObjects that I'm attempting to post to the service, like so:
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
public static voice main(String[] args){
List<MyObjects> objectList = new ArrayList<>();
objectList.add(...)
...
Client client = ClientBuilder.newClient();
WebTarget target = client.target(RESTFUL_URL).path("locations/myObjects");
Invocation.Builder builder = target.request(MediaType.APPLICATION_XML_TYPE);
Entity< List<MyObjects> > request = Entity.entity( objectList , MediaType.APPLICATION_XML_TYPE );
Response resp = builder.post(request);
if( Status.Family.Success == resp.getStatusInfo().getFamily() ) {
...
}
}
When the builder.post(request) line executes, I get the following exception:
javax.ws.rs.ProcessingException: could not find writer for content-type application/xml type: java.util.ArrayList
at org.jboss.resteasy.core.interception.ClientWriterInterceptorContext.throwWriterNotFoundException(ClientWriterInterceptorContext.java:40)
at org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.getWriter(AbstractWriterInterceptorContext.java:138)
at org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:117)
at org.jboss.resteasy.plugins.interceptors.encoding.GZIPEncodingInterceptor.aroundWriteTo(GZIPEncodingInterceptor.java:100)
at org.jboss.resteasy.core.interception.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:122)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.writeRequestBody(ClientInvocation.java:341)
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.writeRequestBodyToOutputStream(ApacheHttpClient4Engine.java:558)
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.buildEntity(ApacheHttpClient4Engine.java:524)
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.loadHttpMethod(ApacheHttpClient4Engine.java:423)
at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:281)
... 11 more
I'm not sure what I'm doing wrong here. Has anyone run into this sort of issue before? Any help with this is greatly appreciated!
Currently working on server sent events of html5 now. I made a servlet and set the
response.setContentType("text/event-stream");
as this. Now I get the update from this servlet on my client side and my client side code is as follows:
<script >
if(typeof(EventSource)!=="undefined")
{
var url = 'http://localhost:8080/KnockOut/DateFeed.jsp';
eventSource = new EventSource(url);
eventSource.onmessage = function (event) {
var theParagraph = document.createElement('p');
theParagraph.innerHTML = event.data.toString();
document.body.appendChild(theParagraph);
}
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support server-sent events...";
}
</script>
But when I change the url to call a rest full webservice written in java, it shows some error and I am note able to get the updated output.
The REST webservice code is:
#GET
public String getXml(#Context HttpHeaders header, #Context HttpServletResponse response) {
response.setHeader("cache-control", "no-cache");
response.setContentType("text/event-stream");
return "dataas: " + (new java.util.Date()).toString() + "x\n\n";
}
please help me.
Here i got the answer
import java.io.PrintWriter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.enterprise.context.RequestScoped;
import org.glassfish.jersey.media.sse.EventOutput;
import org.glassfish.jersey.media.sse.OutboundEvent;
import org.glassfish.jersey.media.sse.SseFeature;
/**
* REST Web Service
*
* #author Irshad kk
*/
#Path("WS")
#RequestScoped
public class SSEResource {
#Context
private UriInfo context;
/**
* Creates a new instance of SSEResource
*/
public SSEResource() {
}
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
public String getServerSentEvents() {
System.out.println("haii" + System.currentTimeMillis());
return "data: " + "irshad" + System.currentTimeMillis() + "\n\n";
}
}
I'm trying to access a third party web service that requires me to create a security header passing in time information, user name, and password. I've scoured the web for working examples and have tried numerous ways. I'm trying to do this with just what's built into Java 6. I'm not sure what I'm doing wrong. After generating my web service client classes from the WSDL, I created the Handler below.
import java.util.Set;
import java.util.TimeZone;
import javax.xml.namespace.QName;
import javax.xml.soap.Node;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.Text;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class MyHeaderHandler implements SOAPHandler<SOAPMessageContext>
{
public boolean handleMessage(SOAPMessageContext context)
{
String prefixUri = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-";
String uri = prefixUri + "wssecurity-secext-1.0.xsd";
String uta = prefixUri + "wssecurity-utility-1.0.xsd";
String ta = prefixUri + "username-token-profile-1.0#PasswordText";
Boolean isRequest = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if(isRequest)
{
try
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:dd.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
java.util.Date created = new java.util.Date();
java.util.Date expires = new java.util.Date(created.getTime() + (5l * 60l * 1000l));
SOAPMessage soapMsg = context.getMessage();
SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader();
if (soapHeader == null)
soapHeader = soapEnv.addHeader();
SOAPFactory factory = SOAPFactory.newInstance();
SOAPElement securityElem = factory.createElement("Security", "o", uri);
securityElem.addAttribute(QName.valueOf("s:mustUnderstand"), "0");
SOAPElement timestampElem = factory.createElement("Timestamp", "u", uta);
timestampElem.addAttribute(QName.valueOf("xmlns:u"), uta);
timestampElem.addAttribute(QName.valueOf("Id"), "_0");
SOAPElement elem = factory.createElement("Created", "u", uta);
elem.addTextNode(formatter.format(created));
timestampElem.addChildElement(elem);
elem = factory.createElement("Expires", "u", uta);
elem.addTextNode(formatter.format(expires));
timestampElem.addChildElement(elem);
securityElem.addChildElement(timestampElem);
SOAPElement usernameElem = factory.createElement("UsernameToken", "o", uri);
elem = factory.createElement("Username", "o", uri);
elem.addTextNode("xxxxx");
usernameElem.addChildElement(elem);
elem = factory.createElement("Password", "o", uri);
elem.addTextNode("xxxxx");
elem.addAttribute(QName.valueOf("Type"), ta);
usernameElem.addChildElement(elem);
securityElem.addChildElement(usernameElem);
soapHeader.addChildElement(securityElem);
}
catch(Exception e)
{
System.out.println("Handler error!!!! - " + e);
}
}
return true;
}
public boolean handleFault(SOAPMessageContext context)
{
return true;
}
public void close(MessageContext context)
{
}
public Set<QName> getHeaders()
{
return null;
}
}
Next, I coded my test program to attach the handler and try calling the web service.
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
import org.tempuri.ServiceName;
import org.tempuri.IServiceName;
public class test
{
public static void main(String[] args)
throws Exception
{
ServiceName service = new ServiceName(new URL("https://url.to.service/services/ServiceName.svc?wsdl"), new QName("http://org.tempuri/", "ServiceName"));
service.setHandlerResolver(new HandlerResolver()
{
public List<Handler> getHandlerChain(PortInfo portInfo)
{
List<Handler> handlerList = new ArrayList<Handler>();
handlerList.add(new MyHeaderHandler());
return handlerList;
}
});
IServiceName binding = service.getBasicHttpBindingIServiceName();
ArrayLiist results = binding.getMyData("my parm");
System.out.println("Size: " + results.size());
}
}
When I run this, I get the following error at the line where i do binding.getMyData():
Exception in thread "main" java.lang.ClassCastException: com.sun.xml.ws.message.saaj.SAAJHeader cannot be cast to com.sun.xml.ws.security.opt.impl.outgoing.SecurityHeader
at com.sun.xml.ws.security.opt.impl.JAXBFilterProcessingContext.setJAXWSMessage(JAXBFilterProcessingContext.java:140)
at com.sun.xml.wss.jaxws.impl.SecurityPipeBase.secureOutboundMessage(SecurityPipeBase.java:389)
at com.sun.xml.wss.jaxws.impl.SecurityClientPipe.process(SecurityClientPipe.java:196)
at com.sun.xml.ws.api.pipe.helper.PipeAdapter.processRequest(PipeAdapter.java:115)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:595)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:554)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:539)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:436)
at com.sun.xml.ws.client.Stub.process(Stub.java:248)
at com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:135)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:109)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:89)
at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:118)
at $Proxy40.getM(Unknown Source)
at test.main(test.java:30)
Every approach I try ends up at the same point. How do I get around this? I can't figure out how to create the SecurityHeader to place into the header. Any help would be greatly appreciated. A working example would be great.
Thanks!
When I was solving similar issue, this thread really helped me.
The problem is when you have Metro (Oracle's WS stack) libraries on classpath, they are autodetected and included in the WS processing. One functionality is transparent authentication / security handling, when endpoint policy is present in WSDL. Unfortunatelly this security handling is not
I was not able to change the WSDL. The solution for me was removing the unwanted JAR (wsit-rt) from the classpath.
Old question, but I had currently the same problem.
The solution was to remove additional security headers I had included manually.
So if you run into this problem, check if you have any handlers (SOAPHandler) writing any headers into your soap message <Security> header part.