I need to create an Http Client to test a REST web service with JAXRS Client API (lib: javax.ws.rs.client.*) provided by WLP. I'll have to send a String Request (JSON message) using POST method and Receive a String Response (JSON message). I'll be grateful if someone has a similar Java Code (Class) and the necessary imports to do this task.
PS : I started coding the Java Class but I didn't know how to get the response:
Client client = ClientBuilder.newClient();
WebTarget myResource = client.target("http://example.com/webapi");
....
I'm using:
Websphere Liberty profile 16.0.0.2,
jaxrs-2.0 [1.0.0]
jaxrsClient-2.0 [1.0.0]
IDE : RDz
You're almost there. All you need to do is format your request data into an instance of 'Entity' and send it off to your service.
Below is some example code that does this for a very simple JAX-RS service.
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
....
// Set up our client and target our JAX-RS service
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:9081/example.jaxrs/test/SimpleService");
// Build our request JSON into an 'Entity'. Replace 'myData' with your JSON
Entity<String> data = Entity.entity("MyData", MediaType.APPLICATION_JSON_TYPE);
// Then send a post request to the target service
String result = target.request(MediaType.APPLICATION_JSON_TYPE).post(data, String.class);
Try the following,
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.MediaType;
import javax.ws.rs.core.Response;
Client client = ClientBuilder.newClient();
WebTarget myResource = client.target("http://example.com/webapi");
Invocation.Builder invocationBuilder = myResource.request(MediaType.TEXT_PLAIN_TYPE);
Response getResponse = invocationBuilder.get();
if (getResponse != null && getResponse.getStatus() == 200) {
String responseString = getResponse.readEntity(String.class);
}
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;
}
}
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;
}
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 set -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true in my client VM arguments. I am using JAX-WS client. But inspite of that SOAP Message is not getting printed in the console. Any reason?
This is my client code.
package com.helloworld.client;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.helloworld.ws.HelloWorld;
public class HelloWorldClient{
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:9999/ws/hello?wsdl");
//1st argument service URI, refer to wsdl document above
//2nd argument is service name, refer to wsdl document above
QName qname = new QName("http://ws.helloworld.com/", "HelloWorldImplService");
Service service = Service.create(url, qname);
HelloWorld hello = service.getPort(HelloWorld.class);
System.out.println(hello.getHelloWorldAsString("Test String"));
}
}
My server is I published using Endpoint.publish and is running locally.
on Server
com.sun.xml.ws.transport.http.HttpAdapter.dump=true
You can also use #HandlerChain(file = "....") annotation
More about Jax-WS Handlers here and here
This is the correct VM argument -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true. Are you using any IDEA?