How to write a REST client, based on CXF, in TomEE? - rest

I would like to use my REST client, developed with CXF, with TomEE/TomEE+ 1.0, but I have a little problem with JAXB JSON marshalling/unmarshalling (with the Jackson library).
I tried both Jersey Client 1.1.13 and CXF WebClient (the version included with Tomee+ 1.0), but, I have the same error at deploy time:
org.apache.openejb.OpenEJBException: No provider available for resource-ref 'null' of type 'javax.ws.rs.ext.Providers' for 'localhost/mywebapp.Comp'
I tried also to copy the 'jackson-jaxrs-json-provieder-2.0.4.jar' jar to the TomEE lib directory, but the error is the same.
I also tried to set the system property 'openejb.cxf.jax-rs.providers' to 'com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider,com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider', but nothing changed.
Here is a sample of the code I use to make a REST call with CXF:
final List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJaxbJsonProvider());
WebClient wc = WebClient.create(url, providers);
Anyway this code it's never executed, because the error is at deploy time.
My webapp (the version developed with Jersey Client) works on Glassfish 3.1.2.
Where is the problem?
Thank you,
bye,
Demis

Found and fixed this bug:
https://issues.apache.org/jira/browse/TOMEE-339
Try the latest TomEE snapshot.
I use jacskon (yes jars needs to be added and the provider to be set) and it works.

I found a good temporary solution to use the CXF rest client and the Jackson JSON marshalling with TomEE+ 1.0.0.
I moved these libraries from the webapp lib to the TomEE lib directory:
jackson-annotations-2.0.4.jar
jackson-jaxrs-json-provider-2.0.4.jar
jackson-module-jaxb-annotations-2.0.4.jar
jackson-core-2.0.4.jar
jackson-databind-2.0.4.jar
And this is my code to make a rest call:
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
final JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(objectMapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
provider.setAnnotationsToUse(JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
provider.setMapper(objectMapper);
final List<Object> providers = new ArrayList<Object>();
providers.add(provider);
WebClient wc = WebClient.create(_request.getUrl(), providers);
wc = wc.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
try {
res = (ElasticResponse) wc.invoke(_request.getHttpVerb(), _request.getMessage(), _request.getElasticResponseClass());
} catch (final ServerWebApplicationException _e) {
this._log.log(Level.FINE, "http response code > 400", _e);
}
I hope that with the next release of TomEE I do not need to add the Jackson's libraries to the container but only to the webapp.

Related

Jax rs rest client - timeout configuration [duplicate]

I have written simple REST web service client class which uses the JAX-RS 2.0 client API to make REST requests. I am trying to figure out how to set a request timeout for each invocation. Here is the code for a request:
Client client = ClientBuilder.newBuilder().build();
WebTarget resourceTarget = client.target(restServiceUrl)
.path("{regsysID}/{appointmentID}/")
.resolveTemplate("regsysID", regSysId)
.resolveTemplate("appointmentID", apptId);
Invocation invocation = resourceTarget.request(MediaType.APPLICATION_JSON).buildPut(null);
String createSessionJson = invocation.invoke(String.class);
Note: this is a new method available on JAX-RS 2.1
This is a very old post but the below code will work for both jersey and resteasy.
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
clientBuilder.readTimeout(12, TimeUnit.SECONDS);
Client client = clientBuilder.build();
You can do this by creating a ClientConfig first and providing it as an argument when creating the new client.
import org.glassfish.jersey.client.ClientProperties;
ClientConfig configuration = new ClientConfig();
configuration.property(ClientProperties.CONNECT_TIMEOUT, 1000);
configuration.property(ClientProperties.READ_TIMEOUT, 1000);
Client client = ClientBuilder.newClient(configuration);
With Resteasy this can be accomplished by building your Client as such.
Client client = new ResteasyClientBuilder()
.establishConnectionTimeout(2, TimeUnit.SECONDS)
.socketTimeout(2, TimeUnit.SECONDS)
.build();
I have not seen a list of standard configuration properties you could set via ClientBuilder.newClient(Configuration configuration) which would be needed to make this portable.
First, you have to add relevant dependencies (here is for the WildFly 10.1):
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>3.0.14.Final</version>
<scope>provided</scope>
</dependency>
Next - create a normal Apache HttpClient and push it the RestEasy Enginge with overriding one method, which causes the problem:
// create here a normal Apache HttpClient with all parameters, that you need
HttpClient httpClient = createHttpClient(connectTimeout,
socketTimeout,
connectionRequestTimeout,
maxTotalHTTPConnections);
// Deprecated Apache classes cleanup https://issues.jboss.org/browse/RESTEASY-1357
// Client Framework not honoring connection timeouts Apache Client 4.3 https://issues.jboss.org/browse/RESTEASY-975
ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient) {
#Override
protected void loadHttpMethod(ClientInvocation request, HttpRequestBase httpMethod) throws Exception {
super.loadHttpMethod(request, httpMethod);
httpMethod.setParams(new BasicHttpParams());
}
};
return new ResteasyClientBuilder().httpEngine(engine).build();
Have a look at https://issues.jboss.org/browse/RESTEASY-975 Seems, that the problem was just resolved in the version 3.1.0.Final.
For people stuck with older JAX-RS 2.0 API and old Resteasy implementation, you may use this method:
Client client = new ResteasyClientBuilder()
.establishConnectionTimeout(3, TimeUnit.SECONDS)
.socketTimeout(5, TimeUnit.SECONDS).build();
Despite the name, socketTimeout stands for "read timeout", since by the docs, it stands for "The timeout for waiting for data".
If you are using Jersey 2.x Here it is the simple solution it's work for me
import com.jclient.JClient;
Client c = Client.create();
WebResource webResource = c.resource("requestUrl");
c.setConnectTimeout(yourMins*60*1000);

Swagger + jaxrs + embedded jetty + no web.xml

I have maven project with embedded jetty server.
I have already created apis using JAX-RS, which are working properly. Now I want to create swagger documentation for my apis.
To start with swagger I have added servlet configuration as describe below :
#WebServlet(name = "SwaggerConfig")
public class SwaggerServlet extends HttpServlet {
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
System.out.println("init SwaggerServlet");
BeanConfig beanConfig = new BeanConfig();
beanConfig.setVersion("1.0.0");
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8082");
beanConfig.setBasePath("/api");
beanConfig.setResourcePackage("com.myCompany.myApisResourcePackage");
beanConfig.setScan(true);
}
}
Also, in main method,
along with my jersey configuration I have added following code :
//swagger
ServletHolder swaggerServletHolder = new ServletHolder(SwaggerServlet.class);
swaggerServletHolder.setInitOrder(1);
swaggerServletHolder.setInitParameter("swagger.api.basepath", "http://localhost:8082");
context.addServlet(swaggerServletHolder, "/api/*");
//swagger end
So, the problem is, I am not able to find where swagger.json will be created.
In this case, swagger scans packages as server log says it, but swagger.json still not getting created.
Note: I am currently not adding swagger-ui as I think it is not mandatory for creating swagger.json
I got swagger json by hitting url "localhost:8082/swagger.json". I used same configuration as posted in my question.

HelloWorld using Drools Workbench & KIE Server

Have KIE Drools Workbench 6.2.0 Final installed inside a JBoss 7 Application Server local instance and Kie Server 6.2.0 Final inside a local Tomcat 7 instance.
Using the web based KIE Workbench strictly for evaluation purposes (am using it to code generate Java based Maven projects and am not using a particular IDE such as Eclipse or IntelliJ IDEA):
Created a new repository called testRepo
Created a new project called HelloWorld
Created a new Data Object called HelloWorld with a String property called message:
package demo;
/**
* This class was automatically generated by the data modeler tool.
*/
public class HelloWorld implements java.io.Serializable {
static final long serialVersionUID = 1L;
private java.lang.String message;
public HelloWorld()
{
}
public java.lang.String getMessage()
{
return this.message;
}
public void setMessage(java.lang.String message)
{
this.message = message;
}
public HelloWorld(java.lang.String message)
{
this.message = message;
}
}
Created a new DRL containing the following contents:
package demo;
import demo.HelloWorld;
rule "hello"
when
HelloWorld(message == "Joe");
then
System.out.println("Hello Joe!");
end
When I deploy it to my Kie Server under this URL:
http://localhost:8080/kie-server-6.2.0.Final-webc/services/rest/server/containers/helloworld
I get the following response when I copy and paste the above URL in Google Chrome:
<response type="SUCCESS" msg="Info for container hello">
<kie-container container-id="hello" status="STARTED">
<release-id>
<artifact-id>Hello</artifact-id>
<group-id>demo</group-id>
<version>1.0</version>
</release-id>
<resolved-release-id>
<artifact-id>Hello</artifact-id>
<group-id>demo</group-id>
<version>1.0</version>
</resolved-release-id>
<scanner status="DISPOSED"/>
</kie-container>
</response>
When I try to do a POST using the following payload (using Postman or SoapUI):
<batch-execution lookup="defaultKieSession">
<insert out-identifier="message" return-object="true" entrypoint="DEFAULT">
<demo.HelloWorld>
<message>Joe</message>
<demo.HelloWorld>
</insert>
Received the following:
HTTP Status 415 - Cannot consume content type
type Status report
message Cannot consume content type
description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
What am I possibly doing wrong? I went to Deploy -> Rule Deployments and registered my kie-server along with creating a container called helloworld and as one can see from Step # 5, it worked. Perhaps I am not deploying it correctly?
Btw, I used the following Stack Overflow post as a basis (prior to asking this question)...
Most of the search results from Google just explain how to programmatically create Drools projects by setting up Maven based projects. Am evaluating KIE Drools Workbench to see how easily a non-technical person can use KIE Drools Workbench to generate Drools based rules and execute them.
Am I missing a step? Under Tomcat 7, it only contains the following directories under apache-tomcat-7.0.64/webapps/kie-server-6.2.0.Final-webc:
META-INF
WEB-INF
Thanks for taking the time to read this...
What content type are you using in your POST request header?
As far as I remember, that error message happened if you didn't provide a content-type: application/xml in your request's header.
Hope it helps,
are you ok?
The response of Esteban is right, but, you should add a another header, the header that you need to add is "Authorization", and the value of Authorization is the user that you registered to you application realm to your kie-server converted in base64. e.g.:
kieserver:system*01
converted to base64:
a2llc2VydmVyOnN5c3RlbSowMQ==
Anyway, the complete header of my request is like this:
Authorization : Basic a2llc2VydmVyOnN5c3RlbSowMQ==
Content-Type : application/xml
I hope it was helpful.
Sorry for my english! :)
I got it working with using Postman (Chrome app / plugin) with the Authorization tab selected to No Auth. Really cool response!
<response type="SUCCESS" msg="Container helloworld successfully called.">
<results>
<![CDATA[<execution-results>
<result identifier="message">
<demo.HelloWorld>
<message>Joe</message>
</demo.HelloWorld>
</result>
<fact-handle identifier="message" external-form="0:4:1864164041:1864164041:4:DEFAULT:NON_TRAIT"/>
</execution-results>]]>
</results>
</response>

Injecting EJB within JAX-RS resource in JBoss 5

Although there already are quite some StackOverflow questions, blog entries, etc. on the web, I still cannot figure out a solution to the problem stated below.
Similar to this question (Injecting EJB within JAX-RS resource on JBoss7) I'd like to inject a EJB instance into a JAX-RS class. I tried with JBoss 5, JBoss 7, and WildFly 8. I either get no injection at all (field is null), or the server does not deploy (as soon as I try to combine all sorts of annotations).
Adding #Stateless to the JAX-RS makes the application server know both classes as beans. However, no injection takes place.
Is there a way to inject EJBs into a REST application? What kind of information (in addition to that contained in the question linked to above) could I provide to help?
EDIT: I created a Github project showing code that works (with Glassfish 4.0) and does not work (with JBoss 5).
https://github.com/C-Otto/beantest
Commit 4bf2f3d23f49d106a435f068ed9b30701bbedc9d works using Glassfish
4.0.
Commit 50d137674e55e1ceb512fe0029b9555ff7c2ec21 uses Jersey 1.8, which does not work.
Commit 86004b7fb6263d66bda7dd302f2d2a714ff3b939
uses Jersey 2.6, which also does not work.
EDIT2:
Running the Code which I tried on JBoss 5 on Glassfish 4.0 gives:
Exception while loading the app : CDI deployment failure:WELD-001408 Unsatisfied dependencies for type [Ref<ContainerRequest>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.server.internal.routing.UriRoutingContext(Ref<ContainerRequest>, ProcessingProviders)]
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type [Ref<ContainerRequest>] with qualifiers [#Default] at injection point [[BackedAnnotatedParameter] Parameter 1 of [BackedAnnotatedConstructor] #Inject org.glassfish.jersey.server.internal.routing.UriRoutingContext(Ref<ContainerRequest>, ProcessingProviders)]
at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:403)
EDIT3: The crucial information might be that I'd like a solution that works on JBoss 5
If you don't want to make your JAX-RS resource an EJB too (#Stateless) and then use #EJB or #Resource to inject it, you can always go with JNDI lookup (I tend to write a "ServiceLocator" class that gets a service via its class.
A nice resource to read about the topic:
https://docs.jboss.org/author/display/AS71/Remote+EJB+invocations+via+JNDI+-+EJB+client+API+or+remote-naming+project
A sample code:
try {
// 1. Retreive the Home Interface using a JNDI Lookup
// Retrieve the initial context for JNDI. // No properties needed when local
Context context = new InitialContext();
// Retrieve the home interface using a JNDI lookup using
// the java:comp/env bean environment variable // specified in web.xml
helloHome = (HelloLocalHome) context.lookup("java:comp/env/ejb/HelloBean");
//2. Narrow the returned object to be an HelloHome object. // Since the client is local, cast it to the correct object type.
//3. Create the local Hello bean instance, return the reference
hello = (HelloLocal)helloHome.create();
} catch(NamingException e) {
} catch(CreateException e) {
}
This is not "injecting" per-se, but you don't use "new" as-well, and you let the application server give you an instance which is managed.
I hope this was useful and I'm not telling you something you already know!
EDIT:
This is an excellent example: https://docs.jboss.org/author/display/AS72/EJB+invocations+from+a+remote+client+using+JNDI
EDIT 2:
As you stated in your comment, you'd like to inject it via annotations.
If the JNDI lookup is currently working for you without problems, and
If you're using Java EE 6+ (which I'm guessing you are), you can do the following:
#EJB(lookup = "jndi-lookup-string-here")
private RemoteInterface bean;

Shorten path of REST service in JBoss Seam application

I'm pretty new to JBoss and Seam. My project has a REST service of the style
#Path("/media")
#Name("mediaService")
public class MediaService {
#GET()
#Path("/test")
public Response getTest() throws Exception {
String result = "this works";
ResponseBuilder builder = Response.ok(result);
return builder.build();
}
}
I can reach this at http://localhost:8080/application/resource/rest/media/test. However, I don't like this URL at all and would prefer something much shorter like http://localhost:8080/application/test.
Can you please point me in the right direction on how to configure the application correctly? (Developing using Eclipse)
web.xml will contain seam resource servlet mapping , this should be modified to /*, and if you have more configuration to the path it will be in components.xml ,if it is resteasy seam is configured to use, it will look like the following
<resteasy:application resource-path-prefix="/rest"/>