Spring: rest client for given resource interface - java

I have api.jar with interfaces annotated with Spring annotations like org.springframework.web.bind.annotation.GetMapping and so on. This api is used as a maven dependency. I would like to generate Rest client basing on given interfaces or use this interface as a source for some kind of proxy object to consume rest endpoints without manual implementation (restTemplate object..)

Related

How does precedence between multiple provider takes place in Google Guice?

I am trying Google Guice as Dependency Injection framework for my new project and shifting from spring.
I have to write multiple providers using #Provides, where instance created from one provider will be used as an input to other providers in the separate modules (sometimes the same module).
For binding the instance generated from the module, I am using Guice's
#BindingAnnotation
to create a custom annotation.
I just wanted to know how does the precedence works in Google Guice?
Like in spring we had a #Dependson annotation for bean creation, is there an alternative in Guice or Guice smart enough to generate a dependency graph by itself?
Does Binding the instances of providers using annotation created from #BindingAnnotation enough?
[is] Guice smart enough to generate a dependency graph by itself?
I'm not familiar with Spring, but my gut-feeling is Yes.
Does Binding the instances of providers using annotation created from
#BindingAnnotation enough?
As long as the provider has been annotated as providing something (using #Provides), Guice will use that annotation as a default, unless otherwise overridden inside a module.
However, using BindingAnnotations does include some code in a Module to bind it together,
https://github.com/google/guice/wiki/BindingAnnotations
bind(CreditCardProcessor.class)
.annotatedWith(PayPal.class)
.to(PayPalCreditCardProcessor.class);
So I suspect that Binding Annotations based annotations have stronger strength then #Provides and as long as you have the counterpart in the module, is more then enough to bind your providers together.

Don't understand how Spring (Boot) Data REST is told to create API endpoints

I have currently have an application that is using Spring Boot and Spring Data. I have my domain objects that were reverse engineered from my database and I have several repositories (classes). Each repository is an interface that extends the CrudRepository.
import org.springframework.data.repository.CrudRepository
interface MyDomainClassRepository extends CrudRepository<MyDomainClass, Integer> {
private MyDomainClass findByName(String name);
}
At this point I would create a service that would implement these items. The service would then be called by a REST controller.
I wanted to be able to have Spring create my REST API automatically if possible and I found the Spring Data REST project. I found this http://spring.io/guides/gs/accessing-data-rest/ and I can follow that guide, but I don't understand what is enabling the "REST APIs" to be created "automatically". I could understand it if the #RepositoryRestResource annotation caused the API to be created but in that guide it explicitly says
RepositoryRestResource is not required for a repository to be exported. It is only used to change the export details, such as using /people instead of the default value of /persons.
Does including in my POM file and rebuilding "automatically" allow Spring Data to create the REST endpoints?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
What keyword, section am I missing that makes it so the API endpoint is created automatically?
Spring Boot is opinionated. It has opinions like using tomcat as your application server or logback as your logging utility. When you pull in
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
It has opinions that when it detects (by classpath scanning) interfaces/classes that extend/implement Repository it will assume that those classes should be served as RESTful resources. RestRepository allows you to customize this behavior by changing the endpoint or not serving the resource at all (exported = false).
Spring-Data-REST does automatically setup the resource to handle GET/POST/PUT/DELETE requests. Are you familiar with REST/HTTP? Those would not be discrete endpoints, GET/PUT/POST/DELETE are http verbs, so there wouldn't be a resource/1/delete endpoint.
Spring Data Rest implements six controllers, in the package org.springframework.data.rest.webmvc:
RepositoryController: handles /
RepositoryEntityController: handles /{repository}
RepositoryPropertyReferenceController: handles /{repository}/{id}/{property} and /{repository}/{id}/{property}/{propertyId}
RepositorySearchController: handles /{repository}/search and /{repository}/search/{repoFunctionName}
ProfileController: handles /profile
RepositorySchemaController: handles /profile/{repository}
They are essentially the same as Spring MVC Controllers, except they are designed to work with Spring Data repositories in a general way
So, if you do GET /foo where foo is the path of your fooRepository, then Spring Data Rest will call RepositoryEntityController.getCollectionResource(), and invoke fooRepository.findAll(...), wrap the result in some HATEOAS objects, then marshal to JSON, using Jackson

Should I use DI for Jersey API Client in Spring 4 application?

I have a java-spring application. I use jersey client for some connections to third-party services. I do not use other jersey features (such as features for restfull-services building etc.)
Do I use dependency injection for creating of com.sun.jersey.api.client.Client? (jersey-spring.jar)
Or should I call
Client client = Client.create();
each time when I need to use it?
Thanks for advice.
UPDATE:
Solution for java-based configuration:
We can define the bean:
#Bean
public Client mailClient() {
return Client.create();
}
Then we can use it:
#Autowired
private Client mailClient;
You can not directly autowire jersey client as it's implementation will not be found on your component scans, nor in my opinion it makes sense as you can always create a wrapper around your client according to your business needs, and autowire that at your other components as required.
If you are actively using spring it generally makes sense for letting spring to manage your bean lifecycles. Using spring container would also enable you to integrate other spring solutions such as spring-aop to your project components as time progresses and business requirements changes.

Dynamically extend Spring MVC powered REST api with access to application jar only

I am in a situation where I have a nascent rest api architecture where each method has tons of ceremony (validation, db connection acquisition/release, authentication), raw request/response objects as the parameters, and hard-coded json strings as the output. I want to use spring mvc to help with at least some of these issues (auth & db stuff i'll need to hold off on). This would render a lot of the current architecture unnecessary. This is pretty easy except for one feature of the current architecture: dynamically adding api calls.
The entry point (servlet) for the architecture reads from an xml file that contains the path for a request and a corresponding class to load. The class must implement an interface that contains an 'execute' method which has the logic for the request. The servlet calls this execute method after loading the class. This allows dynamic extension of the api as follows. The app is packaged as a jar together with the associated config (xml) files and given to a client. The client includes this jar in his project, creates a class that implements the aforementioned interface, and adds a mapping from request url to that class in the included xml file. He then runs the app and gets access to both the original api and his custom api.
Example:
Client is given app.war, interface.jar and custom-mappings.xml. app.war contains the implementation of the core api (rest webservice), and interface.jar exposes the interface BaseController that has the method 'execute' (app.jar also uses this interface in its controller). Client then defines his own class as follows.
package custapi.controllers;
public class ExtendedController implements BaseController {
public void execute(HttpServletRequest request, HttpServletResponse response) {
// LOGIC
}
}
He compiles this class and adds it to app.war. Next, he updates custom-mappings.xml with the following entry.
/custcall/mycall
custapi.controllers.ExtendedController
He then deploys the app. The controller provided with the core api receives the request /custcall/mycall, looks it up in custom-mappings.xml, finds the class is custapi.controllers.ExtendedController, loads that class, and finally runs its 'execute' method. This allows the logic defined by the client to be run.
Ideal:
Current architecture is replaced with spring-mvc. That is, there is no more 'super' controller that parses requests and delegates to the appropriate class and, finally, method. Spring handles this. For the app that uses this new architecture, the client would receive the app.war and the spring mvc deps that expose controller annotations. The client would then create a new spring mvc controller (taking advantage of validation, parameter -> pojo mapping, object -> json conversion), compile it, and add the resulting class file to app.war. His controller would then become an extension to the core api exposed by the app. When the app is deployed, he would be able to make a request /custcall/mycall like before and have it execute the logic he defined. This ideal scenario allows clean code for the core api (which I and others programmed) and an extended api. (A downside to this approach is that the client is tied to spring. In an even more ideal scenario, the client would use framework-agnostic annotations which are mapped to spring annotations by the app. I'm not sure how easy this would be.)
I'm not sure how the above would be realized with a spring-aware controller without sacrificing the benefits of spring. I don't believe the client could simply define another spring-aware controller (correct me if I'm wrong on this). The only solution I can think of is to have a spring-aware controller that has a wildcard path (e.g., /cust_rest/*) which acts exactly the same as the current controller. The client would not get any advantages that spring has to offer, but the core api would be a lot cleaner. I was hoping there was a better solution, however. Ideally the client would get the benefits of spring without having access to the core api source code. Any ideas on this, or is my solution the best that can be hoped for?
Thanks.
(NOTE: For both scenarios, I am only guessing how the client actually gains access to the dependencies/interfaces and deploys. I have only had access to the core api project for one day, and so my understanding of it is not complete.)
Related: Runtime loading of Controllers for Spring MVC and dynamically mapping requests/URLs
The above question looks pretty similar to mine. Replies are sparse (second one is just off topic, I believe).
Provided you setup classpath scanning properly there's no need for interface. Your clients can just annotate classes with #Controller #RequestMapping("/foo/bar"). Even if this class is located in its own jar it will still be scanned. If this is a REST service consider using #RestController instead to avoid having to place #ResponseBody on each handler method.
Use spring security to do declarative authentication & authorization (what you're doing now is programmatic security)

How to expose JAX-RS "DTO"s from entities for REST-Clients?

I have a Java EE 6 web application that offers it's data via a JAX-RS REST web service.
The entities are annotated with the JPA annotations as well as with the javax.xml.bind JAX annotations.
My aim is to assemble a client-jar out of my web-app project that contains the JAX-RS annotated "DTO" classes to be used for JAX unmarshalling in clients of my web-app.
Putting the raw entities in the client jar is not an option because of the JPA annotations, which would lead to bogus dependencies for the client.
Is there a way for doing this without writing the JAX-RS classes twice, for the web-app and the clients?
I thought of annotation processing and killing all JPA annotations in the entities, that's quite techy, but not very handy.
My second idea is to extract an interface of the needed getters/setters of the entities. The question here is how to handle the JAX annotations that are placed at the class members and at the getters.
Both ways seem to work somehow. But is there a general purpose solution for that task?
Hint: yes, i'm aware of the way to expose the JPA-Entities directly via rest and its coupling drawbacks to evolution etc =)
You could supply the JPA metadata via XML (http://java.sun.com/xml/ns/persistence/orm_2_0.xsd) instead of annotations. This would give you the mapping without the class path dependency.
http://java.dzone.com/articles/persisting-entity-classes

Categories