Start embedded Jetty using WebApplicationInitializer - jetty

I am creating Restful (Jax-RS) services to be deployed to Fuse 6.2.1.
(using Apache CFX, and deploying with OSGi bundles to Karaf)
The server supports only up to Spring 3.2.12.RELEASE.
I am attempting to do everything with next to zero XML configuration.
So far so good, everything is working and I can deploy and run my services.
However, I'd like to be able to test my services locally without having to deploy them. So I'd like to be able to boostrap a webserver and register my servlet, but can't quite figure our how.
I'm configuring the servlet with this (using Spring's WebApplicationInitializer rather than web.xml):
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class CxfServletInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addListener(new ContextLoaderListener(createWebAppContext()));
addApacheCxfServlet(servletContext);
}
private void addApacheCxfServlet(ServletContext servletContext) {
CXFServlet cxfServlet = new CXFServlet();
ServletRegistration.Dynamic appServlet = servletContext.addServlet("CXFServlet", cxfServlet);
appServlet.setLoadOnStartup(1);
Set<String> mappingConflicts = appServlet.addMapping("/*");
}
private WebApplicationContext createWebAppContext() {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(CxfServletConfig.class);
return appContext;
}
}
And my main Spring config looks like this:
import javax.ws.rs.core.Application;
import javax.ws.rs.ext.RuntimeDelegate;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
#Configuration
public class CxfServletConfig {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CxfServletConfig.class);
#Bean(destroyMethod = "shutdown")
public SpringBus cxf() {
return new SpringBus();
}
#Bean
#DependsOn("cxf")
public Server jaxRsServer(ApplicationContext appContext) {
JAXRSServerFactoryBean endpoint = RuntimeDelegate.getInstance().
createEndpoint(jaxRsApiApplication(), JAXRSServerFactoryBean.class);
endpoint.setServiceBeans(Arrays.<Object> asList(testSvc()));
endpoint.setAddress(endpoint.getAddress());
endpoint.setProvider(jsonProvider());
return endpoint.create();
}
#Bean
public Application jaxRsApiApplication() {
return new Application();
}
#Bean
public JacksonJsonProvider jsonProvider() {
return new JacksonJsonProvider();
}
#Bean(name = "testSvc")
public TestService testSvc() {
return new TestService();
}
So just to be clear, the above code is my current, working, deployable configuration. So now I'd like to create a test config that utilizes the same but which also starts Jetty and registers my servlet, and can't quite figure out how. Any help?
Thanks!
EDIT: Turns out I did not need the WebApplicationInitializer at all to get this to work. I ended up creating a Test config for Spring that defines a Jetty server as a bean. Seems to work:
#Configuration
public class TestingSpringConfig {
#Bean (name="jettyServer", destroyMethod = "stop")
public Server jettyServer() throws Exception {
Server server = new Server(0); //start jetty on a random, free port
// Register and map the dispatcher servlet
final ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
final ServletContextHandler context = new ServletContextHandler();
context.setContextPath( "/" );
//fuse uses cxf as base url path for cxf services, so doing so as well here so urls are consistent
context.addServlet( servletHolder, "/mybaseurl/*" );
context.addEventListener( new ContextLoaderListener() );
context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
//this will load the spring config for the CFX servlet
context.setInitParameter( "contextConfigLocation", CxfServletConfig.class.getName() );
server.setHandler( context );
server.start();
//server.join(); if running from a main class instead of bean
return server;
}
#Bean(name = "jettyPort")
#DependsOn("jettyServer")
public Integer jettyPort() throws Exception {
Integer port = jettyServer().getConnectors()[0].getLocalPort();
log.info("Jetty started on port: " + port);
return port;
}
}

Related

how to get Soap action from wsdl and generated java files. as my wsdl imports another wsdl which has #webmethod in it

i have a wsdl which is importing another wsdl in it.
i wanted to call the webservice from java client code, i have configured my java class as follows
package test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
#Configuration
public class WeConfig {
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("test");
return marshaller;
}
#Bean
public WeatherClient1 weatherClient(Jaxb2Marshaller marshaller) {
WeatherClient1 client = new WeatherClient1();
client.setDefaultUri("*******");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
}
I have my acessing method as follows
GetDataResponse response = (GetDataResponse) getWebServiceTemplate()
.marshalSendAndReceive(
"*******",
request,
new SoapActionCallback("*******"));
My webservice would be something like
https://abcde.handling.com/celebrity/Confi?wsdl
Kindly let me know , what i have to input in setdefaultUri in configuration and soapcallbackaction. soap Ui gives me a method "GetData" for request
Thanks in advance..
Please help ..
After a long struggle , the answer for this query will be as follows;
DefaultUri = (Full WSDL) https://abcde.handling.com/celebrity/Confi?wsdl
there was no call back action for my request so:
GetDataResponse response = (GetDataResponse) getWebServiceTemplate()
.marshalSendAndReceive(
"Imported wsdl's URI",
request);

is it possible to deploy different web services of single web application on different ports in WildFly server?

My Problem scenario: I have a single JEE7 web application WAR having RestEasy JAX-RS webservices available (for different type of clients) on two distinctly separate application paths. I am using WildFly-8.2.0.Final for deployment. Everything is fine.
The Problem: I want to deploy the two distinctly separate type of JAX-RS web services on two mutually exclusive ports of single instance of WildFly server, let's say TYPE_A_WEB_SERVICES on port 9555 and TYPE_B_WEB_SEREVICES on port 10888 while the web application being deployed on port 80 (or may on be 8080). I do not want both TYPE_A_WEB_SERVICES & TYPE_B_WEB_SERVICES be available web application's port 80 (or may on be 8080) either. Is this configuration possible on single instance of WildFly?
Yes, it is possible and it includes configuration of WildFly to listen on two http ports and a bit of Java EE programming.
Wildfly configuration
Create socket for alternative port
<socket-binding-group ...>
...
<socket-binding name="http" port="${jboss.http.port:8080}"/>
<!-- add this one -->
<socket-binding name="http-alternative" port="${jboss.http.port:8888}"/>
...
</socket-binding-group>
Define http-listener on alternative port
<subsystem xmlns="urn:jboss:domain:undertow:1.2">
...
<server name="default-server">
<http-listener name="default" socket-binding="http"/>
<!-- add this one -->
<http-listener name="http-alt" socket-binding="http-alternative"/>
...
</server>
</subsystem>
Check ports in JAX-RS
For this I used Java EE #Interceptors. I defined 2 endpoints (Endpoint1, Endpoint2) within one application App. Every invocation of methods of endpoints is intercepted by PortDetectionInterceptor which checks if the endpoint is called from predefined ports.
App.java
package net.stankay.test;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("/rest")
public class App extends Application {}
Endpoint1.java
package net.stankay.test;
import javax.interceptor.Interceptors;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
#Interceptors(PortDetectionInterceptor.class)
#Path("/endpoint1")
public class Endpoint1 {
#GET
public String hi() {
return "hi";
}
}
Endpoint2.java
package net.stankay.test;
import javax.interceptor.Interceptors;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
#Interceptors(PortDetectionInterceptor.class)
#Path("/endpoint2")
public class Endpoint2 {
#GET
public String hello() {
return "hello";
}
}
PortDetectionInterceptor.java
package net.stankay.test;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.servlet.http.HttpServletRequest;
public class PortDetectionInterceptor {
#Inject
private HttpServletRequest httpRequest;
#AroundInvoke
public Object detectPort(InvocationContext ctx) throws Exception {
try {
String restEndpoint = ctx.getTarget().getClass().getName();
int restPort = httpRequest.getLocalPort();
if (restEndpoint.contains("Endpoint1") && restPort != 8080) {
throw new RuntimeException("Please access Endpoint1 only via port 8080");
}
if (restEndpoint.contains("Endpoint2") && restPort != 8888) {
throw new RuntimeException("Please access Endpoint2 only via port 8888");
}
return ctx.proceed();
} catch (Exception e) {
return String.format("{ \"error\" : \"%s\" }", e.getMessage());
}
}
}

Embedded Jetty - Adding Context after starting Jetty Server

Is it right to start a jetty instance with no context specified and no context handler, then keep adding context to it once the server has started. Although I was able to do this using mutable HandlerCollection and the logs says the Server and the Contexts are started and available, I am not able to access it with the URL. Or should we add at least one root context and contexthandler to the server while starting it?
I did something similar to the example suggested in below link.
Jetty 9 (embedded): Adding handlers during runtime
My jetty version is 9.3.7.v20160115
the addition of handlers to a running server is a common pattern but the documentation is not clear at all (all the examples in the "embedding jetty" tutorial start the server after the configuration.) AFAIK people is following these approaches:
1) using the HandlerCollection(boolean mutableWhenRunning) ctor to add/remove handlers
2) add and start the handlers explicitly
I observed that #2 was not needed in Jetty 9.1.4, but it is on Jetty 9.2.14 and afterward (BTW these version numbers were picked by Maven as Jersey dependencies which is totally unrelated to this issue.) For example:
// after server creation ...
ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
jettyServer.setHandler(contextHandlerCollection);
jettyServer.start();
// ...
ServletContextHandler newSCH= new ServletContextHandler(ServletContextHandler.SESSIONS);
newSCH.setResourceBase(System.getProperty("java.io.tmpdir"));
newSCH.setContextPath("/servlets");
ServletHolder newHolder = new SwServletHolder(servlet);
newSCH.addServlet(newHolder, "/*");
contextHandlerCollection.addHandler(newSCH);
try {
newSCH.start(); // needed from about 9.2
} catch (Exception e) {
logger.info("Exception starting ServletContextHandler for Jetty", e);
}
In order to add a SOAP context this is a code that "used to work" on 9.1.4 (on 9.2.14 it reports 404):
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import org.eclipse.jetty.http.spi.JettyHttpServerProvider;
import org.eclipse.jetty.http.spi.HttpSpiContextHandler;
import org.eclipse.jetty.http.spi.JettyHttpContext;
import org.eclipse.jetty.http.spi.JettyHttpServer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import com.sun.net.httpserver.HttpContext;
public class JettyJaxWs {
public static void main(String[] args) throws Exception {
Server server = new Server(7777);
ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
server.setHandler(contextHandlerCollection);
server.start();
HttpContext context = buildOrig(server, "/ws");
MyWebService ws = new MyWebService();
Endpoint endpoint = Endpoint.create(ws);
endpoint.publish(context);
// access wsdl on http://localhost:7777/ws/MyWebService?wsdl
}
#WebService
public static class MyWebService {
public String hello(String s) {
return "hi " + s;
}
}
public static HttpContext buildOrig(Server server, String contextString) throws Exception {
JettyHttpServerProvider.setServer(server);
return new JettyHttpServerProvider().createHttpServer(new InetSocketAddress(7777), 5).createContext(contextString);
}
Later, I had to do this for the last method (not sure if there is a better way):
public static HttpContext buildNew(Server server, String contextString) {
JettyHttpServer jettyHttpServer = new JettyHttpServer(server, true);
JettyHttpContext ctx = (JettyHttpContext) jettyHttpServer.createContext(contextString);
try {
Method method = JettyHttpContext.class.getDeclaredMethod("getJettyContextHandler");
method.setAccessible(true);
HttpSpiContextHandler contextHandler = (HttpSpiContextHandler) method.invoke(ctx);
contextHandler.start();
} catch (Exception e) {
e.printStackTrace();
}
return ctx;
}

How to use Spring Autowired in a custom cxf interceptor?

i seem to run into a small issue when using #Autowired into a custom cxf interceptor.
My use case is that i want to log soap messages and send these using AMQP to another system. This process works for normal services etc.
But whatever i do, the needed properties do not get autowired and stay null.
I checked the Spring DI log and the context is scanned and pickedup, so what am i missing?
Is this even possible in CXF interceptors?
#Component
public class LogInInterceptor extends AbstractSoapInterceptor {
private #Value("#{rabbitMQProperties['rabbitmq.binding.log.soap']}")
String binding;
#Autowired
AmqpTemplate amqpTemplate;
public LogInInterceptor() {
super(Phase.RECEIVE);
}
#Override
public void handleMessage(SoapMessage soapMessage) throws Fault {
logIt(soapMessage);
}
private void logIt(SoapMessage message) throws Fault {
// rest of the code omitted...!!!
amqpTemplate.convertAndSend(binding, buffer.toString());
}
}
You can't mix #InInterceptors (a CXF annotation) and #Component (a Spring annotation). That will create two separate instances of your interceptor: the one whose dependencies are getting injected by Spring, and one created by CXF. (You are providing class names in the #InInterceptors annotation, not a bean ID, so CXF has no way of knowing that you already created an instance in the Spring context.)
Remove the #InInterceptors annotation and, in addition to the component scan:
<context:component-scan base-package="org.example.config"/>
You also need something like this in your application context:
<jaxws:endpoint id="myWebService" address="/MyWebService">
<jaxws:inInterceptors>
<ref bean="myInInterceptor" />
</jaxws:inInterceptors>
</jaxws:endpoint>
I know this is an old question, but Jonathan W's answer helped me and I would like to add to it.
This is how I got custom interceptors and #Autowired to work with Spring Boot 1.3.1:
http://cxf.apache.org/docs/jax-ws-configuration.html
import java.util.Arrays;
import javax.jws.WebService;
import org.apache.cxf.Bus;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
#Configuration
#EnableAutoConfiguration
#ImportResource({ "classpath:META-INF/cxf/cxf.xml" })
public class Application extends SpringBootServletInitializer {
#Autowired
private ApplicationContext applicationContext;
#Autowired
private MyInterceptor myInterceptor;
#Autowired
private HelloWorldImpl helloWorldImpl;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// Replaces the need for web.xml
#Bean
public ServletRegistrationBean servletRegistrationBean(ApplicationContext context) {
return new ServletRegistrationBean(new CXFServlet(), "/api/*");
}
// Replaces cxf-servlet.xml
#Bean
// <jaxws:endpoint id="helloWorld" implementor="demo.spring.service.HelloWorldImpl" address="/HelloWorld"/>
public EndpointImpl helloService() {
Bus bus = (Bus) applicationContext.getBean(Bus.DEFAULT_BUS_ID);
EndpointImpl endpoint = new EndpointImpl(bus, helloWorldImpl);
// Set interceptors here
endpoint.setInInterceptors(Arrays.asList(myInterceptor));
endpoint.publish("/hello");
return endpoint;
}
// Used when deploying to a standalone servlet container, i.e. tomcat
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
// Web service endpoint
#WebService(endpointInterface = "demo.spring.service.HelloWorld")
//#InInterceptors not defined here
public static class HelloWorldImpl {
}
public static class MyInterceptor extends LoggingInInterceptor {
// #Autowired works here
}
}

Build Soap web service client using wsdl documents in Eclipse

I need to create web service client in Java using Eclipse the consumes the onvif wsdl.
I spent several hours without finding a how to do that, this the first time I am using soap, my experience was in REST.
I tried many tutorials like this to create web service client, but when I am trying to choose the wsdl file from my local disk, eclipse shows the an error Could not retrieve the WSDL file ..., the link structure I used for the file was file:/C:/ONVIF/media.wsdl.
I need to use any Java framework that support WS-Notification to implement my client.
Can you please tell me how to implement client web service that consumes the WSDL files.
Do I need web server to implement soap web service client?
If yes, why?
Here is a complete code and guide on how to consume one of ONVIF's wsdl files (devicemgmt.wsdl) and how to use it to connect to a device:
package test;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.Binding;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import org.onvif.ver10.device.wsdl.Device;
import org.onvif.ver10.schema.DateTime;
import org.onvif.ver10.schema.SystemDateTime;
import org.onvif.ver10.schema.Time;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class OnvifTest {
private static TimeZone utc = TimeZone.getTimeZone("UTC");
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
static {
sdf.setTimeZone(utc);
}
private static long serverTime = 0;
private static long clientTime = 0;
private static final String ip = "...";
private static final String user = "...";
private static final String pass = "...";
// Some cameras (e.g. Axis) require that you set the user/pass on the ONVIF section in it's web interface
// If the camera is reset to factory defaults and was never accessed from the web, then
// either no user/pass is needed or the default user/pass can be used
#SuppressWarnings("rawtypes")
public static void main(String[] args) throws IOException {
// The altered wsdl file
URL url = new URL("file://"+System.getProperty("user.home")+"/onvif/devicemgmt.wsdl");
// This file was downloaded from the onvif website and added a mock service in order to make it complete:
// <wsdl:service name="DeviceService">
// <wsdl:port name="DevicePort" binding="tds:DeviceBinding">
// <soap:address location="http://localhost/onvif/device_service"/>
// </wsdl:port>
// </wsdl:service>
// The altered file was then used to generate java classes using $JAVA_HOME/bin/wsimport -Xnocompile -extension devicemgmt.wsdl
QName qname = new QName("http://www.onvif.org/ver10/device/wsdl", "DeviceService");
Service service = Service.create(url, qname);
Device device = service.getPort(Device.class);
BindingProvider bindingProvider = (BindingProvider)device;
// Add a security handler for the credentials
final Binding binding = bindingProvider.getBinding();
List<Handler> handlerList = binding.getHandlerChain();
if (handlerList == null)
handlerList = new ArrayList<Handler>();
handlerList.add(new SecurityHandler());
binding.setHandlerChain(handlerList);
// Set the actual web services address instead of the mock service
Map<String, Object> requestContext = bindingProvider.getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://"+ip+"/onvif/device_service");
// Read the time from the server
SystemDateTime systemDateAndTime = device.getSystemDateAndTime();
// Mark the local time (no need for an actual clock, the monotone counter will do just fine)
clientTime = System.nanoTime()/1000000;
// Generate the server time in msec since epoch
DateTime utcDateTime = systemDateAndTime.getUTCDateTime();
org.onvif.ver10.schema.Date date = utcDateTime.getDate();
Time time = utcDateTime.getTime();
Calendar c = new GregorianCalendar(utc);
c.set(date.getYear(), date.getMonth()-1, date.getDay(), time.getHour(), time.getMinute(), time.getSecond());
System.out.println(sdf.format(c.getTime()));
serverTime = c.getTimeInMillis();
// Now try and read something interesting
Holder<String> manufacturer = new Holder<String>();
Holder<String> model = new Holder<String>();
Holder<String> firmwareVersion = new Holder<String>();
Holder<String> serialNumber = new Holder<String>();
Holder<String> hardwareId = new Holder<String>();
device.getDeviceInformation(manufacturer, model, firmwareVersion, serialNumber, hardwareId);
System.out.println(manufacturer.value);
System.out.println(model.value);
System.out.println(firmwareVersion.value);
System.out.println(serialNumber.value);
System.out.println(hardwareId.value);
}
// Calcualte the password digest from a concatenation of the nonce, the creation time and the password itself
private static String calculatePasswordDigest(byte[] nonceBytes, String created, String password) {
String encoded = null;
try {
MessageDigest md = MessageDigest.getInstance( "SHA1" );
md.reset();
md.update( nonceBytes );
md.update( created.getBytes() );
md.update( password.getBytes() );
byte[] encodedPassword = md.digest();
encoded = Base64.encode(encodedPassword);
} catch (NoSuchAlgorithmException ex) {
}
return encoded;
}
// Calculate what time is it right now on the server
private static String localToGmtTimestamp() {
return sdf.format(new Date(System.nanoTime()/1000000 - clientTime + serverTime));
}
// This handler will add the authentication parameters
private static final class SecurityHandler implements SOAPHandler<SOAPMessageContext> {
#Override
public boolean handleMessage(final SOAPMessageContext msgCtx) {
// Indicator telling us which direction this message is going in
final Boolean outInd = (Boolean) msgCtx.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// Handler must only add security headers to outbound messages
if (outInd.booleanValue() && clientTime!=0 && user!=null && pass!=null) {
try {
// Create the timestamp
String timestamp = localToGmtTimestamp();
// Generate a random nonce
byte[] nonceBytes = new byte[16];
for (int i=0 ; i<16 ; ++i)
nonceBytes[i] = (byte)(Math.random()*256-128);
// Digest
String dig=calculatePasswordDigest(nonceBytes, timestamp, pass);
// Create the xml
SOAPEnvelope envelope = msgCtx.getMessage().getSOAPPart().getEnvelope();
SOAPHeader header = envelope.getHeader();
if (header == null)
header = envelope.addHeader();
SOAPElement security =
header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
SOAPElement usernameToken =
security.addChildElement("UsernameToken", "wsse");
SOAPElement username =
usernameToken.addChildElement("Username", "wsse");
username.addTextNode(user);
SOAPElement password =
usernameToken.addChildElement("Password", "wsse");
password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
password.addTextNode(dig);
SOAPElement nonce =
usernameToken.addChildElement("Nonce", "wsse");
nonce.setAttribute("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
nonce.addTextNode(Base64.encode(nonceBytes));
SOAPElement created = usernameToken.addChildElement("Created", "wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
created.addTextNode(timestamp);
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
return true;
}
// Other required methods on interface need no guts
#Override
public boolean handleFault(SOAPMessageContext context) {
// TODO Auto-generated method stub
return false;
}
#Override
public void close(MessageContext context) {
// TODO Auto-generated method stub
}
#Override
public Set<QName> getHeaders() {
// TODO Auto-generated method stub
return null;
}
}
}
I would recommend using wsimport command to generate the web service client to consume the web services.
The command can be executed from cmd prompt,
wsimport -d D:\WS-Client -extension -keep -XadditionalHeaders http://path-to-your-webserbice-wsdl-file/sampleWSDL?wsdl
After execution of the above command all the generated .class files and .java (source) files will be placed inside D:\WS-Client folder with proper package structure as mentioned in the wsdl file.
just ignore the .class files and copy entire package folder and include it in your consumer project to use it.
It will be like, you have the deployed web services in your source code. Just call the methods from the service classes and ohhla :)
The WSDL you were provided is invalid. Most likely due to the extensive documentation tags that were used in it. You can verify this by trying to load it in SoapUI. Your best bet is to contact the vendor to find out if they have a cleaner version of the WSDL they can provide you.
first you want to deploy your web service project on any server means tomcat or other.
after that use the running server WSDL file URL for create the client.