Jackson annotations quarkus resteasy client - jackson

I have a client package where I have defined my REST clients, containing the following interface and models:
#Path("/")
#RegisterRestClient(configKey = "some-api")
public interface SomeRestClient {
#POST
#Path("/oauth/token")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
OAuthResult getOAuthToken(OAuthRequest oAuthRequest);
}
and OAuthRequest class:
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
public class OAuthRequest {
private String email;
private String password;
#JsonProperty("grant_type")
private String grantType;
#JsonProperty("client_id")
private String clientId;
#JsonProperty("client_secret")
private String clientSecret;
}
I import this package into my main service package, but quarkus does not seem to pick up the Jackson annotations. The properties of the request are serialized using camel case, when they should be in snake case.
#Inject
#RestClient
private SomeRestClient someRestClient;
OAuthRequest oAuthRequest = new OAuthRequest();
//set fields
OAuthResult oAuthResult = someRestClient.getOAuthToken(oAuthRequest);
EDIT:
I am using the quarkus-rest-client-jackson and the quarkus-rest-client dependencies, no jsonb dependency anywhere.
I have tried to narrow the problem down: I have moved the client / request classes to my main package, and I have removed the lombok annotations and made my fields which have Jackson annotations public. Still the same problem...
Could anyone point me in the right direction of what I am doing wrong?

Reasteasy is used for your reste endpoint not to access a remote REST service.
To access a remote REST service the REST client is used.
The REST client comes with Jackson support of you use the quarkus-rest-client-jackson dependency not the JSON-B one.

Related

Why can't i access JAX-RS api?

I have a task from a company, that send me a virtual machine with everything set up. The task is that i have to create an API to retrieve Person details from the database and display it.
The problem is that when i run the application, the server returns an index.html with hello world text in it. However, when i try to change the index.html, it does not change in the browser, but when i do request through postman, i get the "updated" index.html.
What i also realised that i cannot access the API that i have created, to check if i can access APIs in the first place.
The path where the index.html returns is "http://hocalhost:8080/tutorial-applicans/"
My Service is PersonService.java:
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Stateless
#Path("person")
public class PersonService{
#PersistenceContext(unitName = "de.erknrw_tutorial-applicants_pu")
private EntityManager em;
#GET
#Path("hello")
#Produces(MediaType.TEXT_PLAIN)
public String sayHello(){
return "Hello World!!!"
}
}
I am trying to get "Hello World!!!", but my path is wrong, when i tried "http://hocalhost:8080/tutorial-applicans/person/hello".
Might be worth mentioning that there is also a JAXRSConfiguration.java file:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Applications;
#ApplicationPath(JAXRSConfiguration.RESTROOT)
public class JAXRSConfiguration extends Application{
public static final String RESTROOT = "webresources";
}
How do access the sayHello()? How does the path look like?
Thanks in advance
When deploying on a webapp, the JAX-RS application is configured as a Servlet. So, you have to add the application path prior to the path of the resource.
The endpoint would be:
http://[server]:[port]/[context path]/[application path]/[resource path]/[operation path]
In your case:
http://hocalhost:8080/tutorial-applicans/webresources/person/hello

Using constructor injection with CDI in OpenLiberty

I'm building a small Java EE 8 application that should run on OpenLiberty.
It has a JAX-RS ContainerResponseFilter that looks like this:
package my.package;
import javax.inject.Inject;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
#Provider
public class MyFilter implements ContainerResponseFilter {
private final MyService myService;
#Inject
public DiagnosticsFilter(final MyService myService) {
this.myService = myService;
}
#Override
public void filter(final ContainerRequestContext request, final ContainerResponseContext response) {
// Never mind this
}
}
If I write the filter like this and start my app, the myService argument to the constructor is null.
However, if field is annoted with #Inject and the constructor is omitted, the field is being injected correctly.
The MyService class is annotated with #Stateless, and in beans.xml I have set bean-discovery-mode="all".
Any idea what I'm doing wrong? Is this actually supposed to work? The Weld documentation suggests that it should, but I'm not sure it's in the CDI spec as well...
This is a long story...And some people are working to solve the problem: JAX-RS injection != CDI injection
It shoud be solved in JAX-RS 2.2 ad CDI injection should be used in place of JAX-RS injection and JAX-RS v3.0 will totally remove the JAX-RS injection
Read this on the subject:
https://www.eclipse.org/community/eclipse_newsletter/2019/february/Jakarta_EE_9.php
https://github.com/eclipse-ee4j/jaxrs-api/issues/569
https://github.com/eclipse-ee4j/jaxrs-api/issues/639
https://groups.google.com/forum/#!topic/microprofile/gvj94XBhtvM

Inject EJB into JAX-RS 2.0 subresource when subresource is got via ResourceContext

I am using Jersey 2.8 with Glassfish 4.0.
I have a resource locator class which looks like below
#Path("/")
#ManagedBean
public class MyServiceLocator {
#Context
ResourceContext rc;//javax.ws.rs.container.ResourceContext
#EJB
private MyEJBHome myEJB;
#Inject//javax.inject.Inject
MySubService mss;
#Path("/mysubservice")
public MySubService getMySubService() {
return rc.getResource(MySubService.class);
//also tried return rc.initResource(new MySubService());
}
}
and a sub resource class which is
#ManagedBean
public class MySubService {
#EJB
public MyEJBHome myEJB;
#Context
HttpHeaders heads;
/*#Inject
private myEJBHome myEJB2;*/
#Path("/mypath")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Object doSomething(#Context SecurityContext securityContext) {...}
}
beans.xml file is put to META-INF and WEB-INF.
In MyServiceLocator class private MyEJBHome myEJB is injected successfully. And MySubService mss object is injected successfully and with EJB injected into it.
The problem is that when MySubService is got via ResourceContext the EJB is not injected into it.
Previously i used Glassfish 3 and Jersey 1.17 with proprietary ResourceContext and absolutely the same code worked ok.
I googled a lot and read a lot of similar (but a bit different) questions and as i understood non JAX-RS stuff (EJB in my case) can't be injected when sub resource is got via ResorceContext. Is it true? If yes how can i work it around?
The one possible solution is to inject sub resource objects to the resource locator class but there are too many of them and it seems to be very ugly.
EDIT Injection with #Inject works if to create a binder, bind ejb class to ejb interface and register that binder. But i don't want to describe binding for hundreds of my ejbs. Also as i understand it is specific binding fir HK2 system and i don't want to be linked to it.
Different actions with setting #Named annotations and trying to inject via CDI didn't help. It seems that when getting sub-resource via ResourceContext Jersey uses only HK2 and that's why CDI can't do it's work. Is that correct?
The only appropriate solution i found was to create my own annotation and inject provider.
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface EJBInject {
String beanName();
}
#Provider
public class EjbInjectProvider implements InjectionResolver<EJBInject> {
#Override
public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
try {
String beanName = injectee.getParent().getAnnotation(EJBInject.class).beanName();
return new InitialContext().lookup("java:global/MyApp/" + beanName);
} catch (Exception e) {
return null;
}
}
#Override
public boolean isConstructorParameterIndicator() {
return false;
}
#Override
public boolean isMethodParameterIndicator() {
return false;
}
}
Then ejb can be injected using that annotation like
#EJBInject(beanName="MyBean")
MyBeanEJBHome myBean;
In such case any standard EJB injections which MyBeanEJBHome might need work correctly, too.

EJB Injection failure on deploy

I've got a problem exxh EJB's.
First of all, my setup: I am using GlassFish & JEE6. I have got a REST-Service packaged as a WAR and a bean packaged as an EJB-Jar. They are not inside an EAR.
The EJB should be used from the REST-WAR via #EJB, but when I try to deploy the WAR, GlassFish shows this error:
Error occurred during deployment:
Exception while deploying the app [exx-upload-1.0] : Cannot resolve reference Local ejb-ref name=com.ex.exx.model.FileUpload/ocr,Local 3.x interface =com.ex.exx.api.IOCRService,ejb-link=null,lookup=,mappedName=,jndi-name=,refType=Session. Please see server.log for more details.
(The EJB was deployed before without any erros).
I have no clue why. Here is the EJB Code:
Interface:
#Local
public interface IOCRService {
public String performOCRonImage(BufferedImage input);
}
and Implementation:
#Stateless
#LocalBean
public class OCRScanner implements IOCRService {
private Logger logger = Logger.getLogger(this.getClass().getName());
private final static String NOT_RECOGNIZED = "Can not regocnize text";
/**
* Default constructor.
*/
public OCRScanner() {
logger.log(Level.INFO, "### OCR SCANNER BUILD" + this);
}
public String performOCRonImage(BufferedImage input) {
logger.log(Level.INFO, "### OCR SCANNER CALLED" + this);
}
...
And here is the important part in the WAR:
public class FileUpload {
private final File PROPERTIES_FILE = new File(
"fileUploadProperties.properties");
private final String PARAMETER_NAME = "file";
private final Logger logger = Logger.getLogger(this.getClass().getName());
#EJB
private IOCRService ocr;
public Response uploadFile(...) {
// do some stuff
logger.log(Level.INFO, "### EJB" + ocr.toString())
}
Anny suggestions? I can not find my failure here.
Solved this, by replaceing #Local with #Remote.
This works, however, I am not satisfied as I do not understand why.
Basically, given the specs (eg. explained in the tutorial), an application can only access other application's EJB, if they are decorated with #Remote.
Thus, you have 3 options:
decorate your EJB with #Remote (what you have done),
package both together inside an ear (as they would reside in the
same application then). But if you intent to deploy them in seperate
applications or even seperate servers, use 1.)
use CDI with #Inject, but this will still only discover the EJB if
either in the same application, or decorated as #Remote if not.
HTH,
Alex
You should not use #EJB if the target is not an EJB. I guess this is your case because you are trying to inject into a class in your WAR.
Instead use:
#Inject
private IOCRService ocr;
Basically, #Inject is better in most cases, because:
it is more typesafe,
it supports #Alternatives
it is aware of the scope of the injected object.
Another solution it's to add #Stateless(name=""), this worked form

Dozer DozerBeanMapper Instantiation Startup EJB App Server Glassfish

Dozer's documentation states that you should only have one instance of DozerBeanMapper running in the app on the server. For initial development I ignored this, now I want to update the app to do this.
How can I instantiate the DozerBeanMapper class when the application starts on glassfish, and how would I access its "map" method in another class once the application has started or been newly deployed?
This is for EJBs so I can't use any servlet to do this.
OK, so I've finally had time to refactor this code. With the pointer from #Mikko Maunu, I am editing my question to provide the code that I have working for me for anyone who might find it useful in the future.
package com.xyz.utilities.singleton;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import org.dozer.DozerBeanMapper;
#Startup
#Singleton
public class DozerInstantiator {
private DozerBeanMapper mapper = null;
#PostConstruct
void init() {
mapper = new DozerBeanMapper();
}
public DozerBeanMapper getMapper() {
return mapper;
}
}
And here is a straight forward usecase:
Inject an EJB member variable to your client class:
#EJB
DozerInstantiator di;
Within a method somewhere in the client class you can invoke the dozer mapper like so:
Credentials credentials = di.getMapper().map(credentialsDTO, Credentials.class);
// or
Credentials credentials = new Credentials();
di.getMapper().map(credentialsDTO, credentials);
If this is wrong or off base, someone please leave a comment. Until then, this seems to work so I'll use this solution I've developed with Mikko's input.
If you are using GlassFish 3.x, then you can use EJB 3.1 Singleton Session Bean:
#Startup //initialization in application startup
#Singleton //only one instance
public class DozerInitializer {
private String status;
#PostConstruct //executed once and only once when sole instance is created
void init {
//do steps needed to instantiate DozerBeanMapper
//here
}
}