I know this question and that on however they were not answered and asked 4 years ago. Further, non of the answers worked for me.
I am unable to add a crossOriginFilter to my embedded jetty server.
My pom
<!-- Jetty -->
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.11.v20150529</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.11.v20150529</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>9.2.11.v20150529</version>
</dependency>
My code - unfortunatly I do not get any Header field in the responses!
ServletContextHandler dynamicResourceContext = new ServletContextHandler();
dynamicResourceContext.setContextPath("/rest");
FilterHolder holder = new FilterHolder(CrossOriginFilter.class);
holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
holder.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD");
holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin");
dynamicResourceContext.addFilter(holder, "/*", EnumSet.of(DispatcherType.REQUEST));
ServletContextHandler staticResourceContext = new ServletContextHandler();
staticResourceContext.setContextPath("/resources");
DefaultServlet defaultServlet = new DefaultServlet();
ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
holderPwd.setInitParameter("resourceBase", "./src/webapp/");
staticResourceContext.addServlet(holderPwd, "/*");
HandlerList handlers = new HandlerList();
handlers.addHandler(dynamicResourceContext);
handlers.addHandler(staticResourceContext);
server = new Server(port);
server.setHandler(handlers);
// set logging to console
StdErrLog logger = new StdErrLog();
logger.setDebugEnabled(webserverLogging);
Log.setLog(logger);
ServletHolder jerseyServlet = dynamicResourceContext
.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
// Tells the Jersey Servlet which REST service/class to load.
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", getMyClasses());
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
// server.destroy();
}
What do I wrong? I do not get any error message!
EDIT
Also the following tutorial is not working. Neither with Postman nor with chrome I see an additional response head entry.
The response looks like the following:
HTTP/1.1 200 OK
Date: Tue, 26 Mar 2019 19:41:36 GMT
Content-Length: 0
Server: Jetty(9.4.15.v20190215)
EDIT
I was able to create the header fields using a Resource Configuration but I am still unable to create them with the CrossOriginFilter.
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(9998);
jettyServer.setHandler(context);
ResourceConfig webapiResourceConfig = new ResourceConfig();
webapiResourceConfig.register(CorsFilter.class);
ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(webapiResourceConfig));
context.addServlet(jerseyServlet, "/*");
//context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter( "jersey.config.server.provider.classnames",MyServerConfig.class.getCanonicalName());
You shouldn't see the headers in Postman, as Postman doesn't require CORS support. And in Chrome (or any browser), you should only see them if you are actually making a cross origin request. If the filter is implemented correctly, it should only spit out CORS response headers if there is an Origin request header. And that should only happen on cross origin requests made from a browser.
The reason your Jersey filter worked is probably because it is not implemented correctly, according to the CORS protocol; it is probably just a lazy version where headers are added for all requests. In this answer, I originally also implemented the same "lazy" CORS support, but if you look at the UPDATE, I explain how it should be implemented. If you want to learn more about CORS, that UPDATE is a good read.
Related
Is it possible to configure the ErrorPageErrorHandler in way that it redirects to a static Page if no content/service is found?
Here is my Code:
server = new Server(port);
Resource webRoot = Resource.newResource(webContent);
if (!webRoot.exists()) {
logger.warn("Unable to find root resource:" + webRoot.getName());
} else {
logger.info("Root resource is " + webRoot.getName());
}
ResourceHandler res = new ResourceHandler();
res.setBaseResource(webRoot);
res.setDirAllowed(false);
//servlet handler
ServletContextHandler servletCtx = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletCtx.setContextPath("/service");
servletCtx.addServlet(new ServletHolder("sample", new MyServletSample()), "/sample");
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "index.html");
servletCtx.setErrorHandler(errorHandler);
// static file handler
ContextHandler staticCtx = new ContextHandler("/");
staticCtx.setBaseResource(webRoot);
staticCtx.setHandler(res);
// add handlers
HandlerList handlerList = new HandlerList();
handlerList.addHandler(servletCtx);
handlerList.addHandler(staticCtx);
// add handerList to server
server.setHandler(handlerList);
This code show me index.html on localhost:8080 and I can access the sample service http://localhost:8080/service/sample. However, I want to show a static error page (i.e. documentation) to show up if an error like "404 Not Found" occured.
With this code, the Error handler logs:
"WARN o.e.j.server.handler.ErrorHandler - No error page found
index.html"
. What is correct way/syntax to define the URI?
Thanks in advance!
This was answered before at https://stackoverflow.com/a/32383973/775715
Don't mix ResourceHandler and ServletContextHandler unless you REALLY know what you are doing, and fully understand the nature of javax.servlet.ServletContext and all of the rules it brings to the table.
See also:
What is difference between ServletContextHandler.setResourceBase and ResourceHandler.setResourceBase when using Jetty embedded container?
Serving static files from alternate path in embedded Jetty
Here's an example of your setup working with NO ResourceHandler, 1 ServletContextHandler, and a DefaultServlet providing the static file serving.
// servlet handler
ServletContextHandler servletCtx = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletCtx.setContextPath("/");
servletCtx.setBaseResource(webRoot); // what static content to serve
servletCtx.setWelcomeFiles(new String[] { "index.html" });
servletCtx.addServlet(new ServletHolder("sample", new MyServletSample()), "/service/sample");
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "/index.html");
servletCtx.setErrorHandler(errorHandler);
// static file serving, and context based error handling
ServletHolder defaultServ = new ServletHolder("default", DefaultServlet.class);
defaultServ.setInitParameter("dirAllowed","false");
servletCtx.addServlet(defaultServ,"/");
// add handlers
HandlerList handlerList = new HandlerList();
handlerList.addHandler(servletCtx);
handlerList.addHandler(new DefaultHandler()); // non-context error handling
I'm trying to get a CrossOriginFilter working with a couple of embedded Jetty servers, both running on our internal network. Both are running servlets, but I need server A's web page to be able to post to server B's servlets. I think I need to add ACCESS_CONTROL_ALLOW_ORIGIN to a CrossOriginFilter but finding out how to do this with an embedded Jetty instance with no web.xml isn't proving to be easy. I get the following error message in the browser when trying to access server b's serlvets
No 'Access-Control-Allow-Origin' header is present on the requested resource
Im using angularjs to post to the other server's servlets in a controller.
And here is the code for one of the servers (both are pretty much the same)
Server server = new Server(httpPort);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "index.html" });
resource_handler.setResourceBase("./http/");
ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(ServerPageRoot.class, "/servlet/*");
FilterHolder holder = new FilterHolder(CrossOriginFilter.class);
holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
holder.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD");
holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin");
handler.addFilter(holder );
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, handler,new DefaultHandler() });
server.setHandler(handlers);
server.start();
A few points:
Don't use ServletHandler naked like that. The ServletHandler is an internal class that ServletContextHandler uses.
The ServletContextHandler is what provides the needed ServletContext object and state for the various servlets and filters you are using.
The ServletContextHandler also provides a place for the overall Context Path declaration
The ServletContextHandler is also the place for Welcome Files declaration.
Don't use ResourceHandler, when you have DefaultServlet available, its far more capable and feature rich.
Example:
Server server = new Server(httpPort);
// Setup the context for servlets
ServletContextHandler context = new ServletContextHandler();
// Set the context for all filters and servlets
// Required for the internal servlet & filter ServletContext to be sane
context.setContextPath("/");
// The servlet context is what holds the welcome list
// (not the ResourceHandler or DefaultServlet)
context.setWelcomeFiles(new String[] { "index.html" });
// Add a servlet
context.addServlet(ServerPageRoot.class,"/servlet/*");
// Add the filter, and then use the provided FilterHolder to configure it
FilterHolder cors = context.addFilter(CrossOriginFilter.class,"/*",EnumSet.of(DispatcherType.REQUEST));
cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD");
cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin");
// Use a DefaultServlet to serve static files.
// Alternate Holder technique, prepare then add.
// DefaultServlet should be named 'default'
ServletHolder def = new ServletHolder("default", DefaultServlet.class);
def.setInitParameter("resourceBase","./http/");
def.setInitParameter("dirAllowed","false");
context.addServlet(def,"/");
// Create the server level handler list.
HandlerList handlers = new HandlerList();
// Make sure DefaultHandler is last (for error handling reasons)
handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
server.setHandler(handlers);
server.start();
managed to get it working by doing
FilterHolder holder = new FilterHolder(CrossOriginFilter.class);
holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
holder.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD");
holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin");
holder.setName("cross-origin");
FilterMapping fm = new FilterMapping();
fm.setFilterName("cross-origin");
fm.setPathSpec("*");
handler.addFilter(holder, fm );
Maybe this will help someone even though it is not a good answer to the original question. I realized that you can easaly enable cross origin request sharing in an embedded jetty instance by manipulating the headers directly in your handler. The response object below is an instance of HttpServletResponse (which is passed to the handler).
Example:
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Methods", "POST, GET");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
I tried all the way of above answers and other similar ones. But always, I came across same error message.
Finally I reach a correct answer for my situation. I use Jersey with Jetty and I am not using web.xml. If you try all methods and you don't enable the CORS support, maybe you can try this solution below.
First, define a filter (you can define another one which directly implements Filter class)
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;
public class CorsFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static boolean isPreflightRequest(ContainerRequestContext request) {
return request.getHeaderString("Origin") != null && request.getMethod().equalsIgnoreCase("OPTIONS");
}
#Override
public void filter(ContainerRequestContext request) throws IOException {
// If it's a preflight request, we abort the request
if (isPreflightRequest(request)) {
request.abortWith(Response.ok().build());
return;
}
}
#Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
// if there is no Origin header, we don't do anything.
if (request.getHeaderString("Origin") == null) {
return;
}
// If it is a preflight request, then we add all
// the CORS headers here.
if (isPreflightRequest(request)) {
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.getHeaders().add("Access-Control-Allow-Headers",
// Whatever other non-standard/safe headers (see list above)
// you want the client to be able to send to the server,
// put it in this list. And remove the ones you don't want.
"X-Requested-With,Content-Type,Content-Length,Authorization,"
+ "Accept,Origin,Cache-Control,Accept-Encoding,Access-Control-Request-Headers,"
+ "Access-Control-Request-Method,Referer,x-csrftoken,ClientKey");
}
response.getHeaders().add("Access-Control-Allow-Origin", "*");
}
}
Register this filter to resource config
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
public class AppServer {
public static void main(String[] args) throws Exception {
Server jettyServer = new Server();
// Add port
ServerConnector jettyServerConnector = new ServerConnector(jettyServer);
jettyServerConnector.setPort(Integer.parseInt("9090"));
jettyServer.addConnector(jettyServerConnector);
// Define main servlet context handler
ServletContextHandler jettyServletContextHandler = new ServletContextHandler();
jettyServletContextHandler.setContextPath("/service");
// Define main resource (webapi package) support
ResourceConfig webapiResourceConfig = new ResourceConfig();
webapiResourceConfig.packages("com.example.service");
ServletContainer webapiServletContainer = new ServletContainer(webapiResourceConfig);
ServletHolder webapiServletHolder = new ServletHolder(webapiServletContainer);
jettyServletContextHandler.addServlet(webapiServletHolder, "/webapi/*");
// Add Cors Filter
webapiResourceConfig.register(CorsFilter.class, 1);
try {
jettyServer.start();
jettyServer.dump(System.err);
jettyServer.join();
} catch (Throwable t) {
t.printStackTrace(System.err);
} finally {
jettyServer.destroy();
}
}
}
That's it. This solution solved my problem. Maybe it can be useful for others.
I am trying to get java.util.List as response from cxf rest web service.
I have tried with WebClient class's method postObjectGetCollection method but no luck.
I am getting - org.apache.cxf.jaxrs.client.ClientWebApplicationException: .No message body reader has been found for class : interface java.util.Collection, ContentType : application/json.
Below are my client code-
String mediaType = "application/json";
if (url != null) {
List<DataTypeDTO> resultdtos = new ArrayList<DataTypeDTO>();
WebClient client = WebClient.create(url);
client = client.accept(mediaType).type(mediaType).path(uri);
resultdtos = (List<DataTypeDTO>)client.getCollection(DataTypeDTO.class);
System.out.println(resultdtos);
}
Please help me out if i am missing any configuration or other things.
You need to provide the provider list while creating the webClient object in your rest client.
You can use the below code to resolve your issue:
final String url = "http://localhost:10227/someService";
final String uri = "/manageXyz/fetchAllDataTypes";
final String mediaType = "application/json";
Object response = null;
List<Object> providers = new ArrayList<Object>();
providers.add( new JacksonJaxbJsonProvider() );
WebClient client = WebClient.create(url, providers);
client = client.accept(mediaType).type(mediaType).path(uri);
response = (List<Object>)client.post(oemUser, List.class);
If you are using maven, you also need to provide below required jars to resolve maven dependency in your project:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
<version>1.9.13</version>
</dependency>
I am using Jersey client to hit a PHP web service for image uploading functionality. I am getting the following exception:
Caused by: com.sun.jersey.api.client.ClientHandlerException:
A message body writer for Java type, class
com.sun.jersey.multipart.FormDataMultiPart, and MIME media type,
multipart/form-data, was not found
at com.sun.jersey.api.client.RequestWriter.writeRequestEntity(RequestWriter.java:288)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:204)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:147)
... 63 more
This is the code I am using:
WebResource webResource = Client.create().resource(HTTP_REST_URI);
JSONObject jSONObj = webResource.queryParams(queryParams)
.type(MediaType.MULTIPART_FORM_DATA)
.post(JSONObject.class, formDataMultiPart);
How can this exception be resolved?
Register the MultiPartWriter provider when creating the Client:
ClientConfig cc = new DefaultClientConfig();
Client client;
cc.getClasses().add(MultiPartWriter.class);
client = Client.create(cc);
If using Maven, these are the dependencies you need in your pom.xml:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.17.1</version>
</dependency>
Jersey (server or client) has providers that support the conversion of a Java type to a stream and vice versa.
Your code returns (or receives) a Java object and based on the type of the object and the content type you are using,
Jersey looks for an appropriate provider to do the marshalling (or unmarshalling).
The providers implement the MessageBodyReader or MessageBodyWriter interfaces and for every Java type and content type
combination your application uses you must have a provider that knows how to handle the combination.
The messages you are getting is telling you that Jersey can't find a provider that knows how to marshal a FormDataMultiPart object with a multipart/form-data mime type. You need to provide one, and if I'm not mistaken the default implementation is found in the jersey-multipart.jar and mimepull.jar files.
I faced the same issue. It got solved by changing maven dependency for jersey-multipart jar from 1.0.2 to 1.8 version (Used the same dependency in client side as well as provider side.
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.8</version>
</dependency>
Here's the complete piece of code I'm using
File file = new File("E:/Goodies/tmp/sparrow.jpg");
byte[] logo = FileUtils.readFileToByteArray(file);
MultiPart multiPart = new MultiPart().bodyPart(new BodyPart(logo, MediaType.APPLICATION_OCTET_STREAM_TYPE));
// POST the request
try{
ClientResponse response = service.type("multipart/mixed").post(ClientResponse.class, multiPart);
System.out.println("Response Status : " + response.getEntity(String.class));
}catch(Exception e){
e.printStackTrace();
}
and in the webservice:
#POST
#Consumes("multipart/mixed")
#Path("/upload")
public Response post(MultiPart multiPart) {
BodyPartEntity bpe = (BodyPartEntity) multiPart.getBodyParts().get(0)
.getEntity();
boolean isProcessed = false;
String message = null;
try {
InputStream source = bpe.getInputStream();
BufferedImage bi = ImageIO.read(source);
File file = new File("E:/Goodies/tmp" + "123.jpg");
// storing the image to file system.
if (file.isDirectory()) {
ImageIO.write(bi, "jpg", file);
} else {
file.mkdirs();
ImageIO.write(bi, "jpg", file);
}
isProcessed = true;
} catch (Exception e) {
message = e.getMessage();
}
there are few things you need to check
add mimepull.jar to your lib or with Maven
`<dependency>
<groupId>org.jvnet.mimepull</groupId>
<artifactId>mimepull</artifactId>
<version>1.9.5</version>
</dependency>`
And if you are working with file, make sure you send at the header the content-length content-type accept-encoding
I added this in web.xml. Problem solved.
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
Here's my work around:
WebResource webResource =
jerseyClient.resource("www.api.com");
WebResource.Builder requestBuilder = webResource.getRequestBuilder();
requestBuilder.header("content-type", "application/json");
ClientResponse response = requestBuilder
.post(ClientResponse.class, mObjectMapper.writeValueAsString(new RequestObject(longUrl)));
String text = response.getEntity(String.class);
ResponseObject outcome = mObjectMapper.readValue(text, ResponseObject.class);
I have used Jackson ObjectMapper to serialize the request payload and likewise deserialized the outcome into a ResponseObject instance using ObjectMapper.
So I have mapped a WSO2 DSS service through WSO2 ESB. I have generated a jax-ws client and I am using it successfully to get some data.
The problem is that sometimes when I call the client it throws a
Exception in thread "main" java.lang.NullPointerException
at com.sirmaitt.egov.codelist.client.Client.main(Client.java:77)
At that line of the source code I am trying to print the response data in the console.
Here's the code I'm using to call the service
// Initialize service
Codelists_Service service = new Codelists_Service();
// Adds custom handler so we can add custom SOAP security header.
service.setHandlerResolver(new HandlerResolver() {
#SuppressWarnings("rawtypes")
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlers = new ArrayList<Handler>();
handlers.add(new SecuritySOAPHandler());
return handlers;
}
});
CodelistsPortType port = service.getCodelistsHttpsSoap11Endpoint();
Codelists codelists = null;
try {
codelists = port.getcodelists();
} catch (DataServiceFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Prints the response.
for (Codelist cList : codelists.getCodelist()) {
}
Rest of the project are mainly jax-ws generated classes and one custom SOAPHandler, which I use to add a security header.
The issue is that this same client actually starts working when I log in the WSO2 ESB and click on the service I've mapped there. And it throws exception when I don't use the service for some time.
This issue really puzzles me. What can be the cause of it?
EDIT: Clarification, the code on line 77 is the for loop. It seems the codelists object is null.
EDIT: Here's the method that adds the security header to the request.
public boolean handleMessage(SOAPMessageContext messageContext) {
Boolean isOutboundMessage = (Boolean) messageContext
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (isOutboundMessage) {
SOAPPart messageSoapPart = messageContext.getMessage()
.getSOAPPart();
WSSecHeader securityHeader = new WSSecHeader();
securityHeader.insertSecurityHeader(messageSoapPart);
WSSecUsernameToken usernameToken = new WSSecUsernameToken();
usernameToken.setPasswordType(WSConstants.PASSWORD_TEXT);
usernameToken.setUserInfo(USER_NAME, PASSWORD);
WSSecTimestamp timestamp = new WSSecTimestamp();
usernameToken.build(messageSoapPart, securityHeader);
timestamp.build(messageSoapPart, securityHeader);
}
return true;
}
And here is what the request looks like (taken from console)
---[HTTP request]---
SOAPAction: "urn:_getcodelists"
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml;charset="utf-8"
<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" S:mustUnderstand="1"><wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Timestamp-11800260"><wsu:Created>2012-09-18T13:17:56.707Z</wsu:Created><wsu:Expires>2012-09-18T13:22:56.707Z</wsu:Expires></wsu:Timestamp><wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-9299042"><wsse:Username>admin</wsse:Username><wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">admin</wsse:Password></wsse:UsernameToken></wsse:Security></S:Header><S:Body></S:Body></S:Envelope>--------------------
---[HTTP response 202]---
Transfer-encoding: chunked
null: HTTP/1.1 202 Accepted
Connection: keep-alive
Server: Synapse-HttpComponents-NIO
Date: Tue, 18 Sep 2012 13:19:57 GMT
I think it is because your session timed out and you needed to log in again to authenticate the service.