HttpClient vs Spring Rest Template? - java

What's the best way to make a REST call?
Should I use Apache Http Client or Should I use Spring Rest Template.
On what basis I can decide which one I should go for?
I need to make a call to this url-
http://localhost:8080/service/Service/v1/get/USERID=10000/profile.ACCOUNT.SERVICE"
And after getting the response back, I just need to see whether that response contains any particular string or not.

Spring RestTemplate follows the pattern for all the *Template classes within the core Spring framework and the various sub-frameworks: JdbcTemplate, HibernateTemplate, WebServiceTemplate etc etc.
The idea of all of these Template classes is to reduce the boilerplate code (exception handling, repetitive stuff and concentrate on your business logic). I would definitely use it over the simple HttpClient.
To get the class you'll need the spring-web dependency.

Related

Workflow mechanism for exception and error handling scenarios in Spring Boot or Spring

I am working on design where the requirement is as follows
The application would be built using spring boot
As part of the requirement we would have to build some orchestration where we would end up calling multiple SOAP and REST services and we would perform aggregation, transformation etc.
When an exception/error occurs during the orchestration, we need to capture and persist the state and retry it from the same point where the error occurred.
For example, Lets say there is a Java method in which we have multiple calls to external components say 1 soap call and 2 rest calls i.e.
String doOrchestration(InputObject obj){
Line 1: Object obj = soap call[ input is XML format];
Line 2: Object obj1 = rest1 call [the input is obj in JSON format]
Line 3: Object obj3 = rest2 call[the input is obj1 in JOSN format]
//do something
return str
}
The error occurred on Line 2. We need to capture/persist the state and continue the execution from the Line 2 later.
Is there any workflow library, orchestration patterns and/or framework that we can integrate with spring/Spring-boot
Thanks,
well, one tecnology that i use to handle this kind of problems is apache camel, whith camel you can set routes,for instance in your requirement, you can build the main route who will orchest other routes such as yours endpoints, if one endpoint has an exception you can call the route who will persist that and call again the route of the endpoint, or something like that.
http://camel.apache.org/getting-started.html
edit: camel has a lot of potencial transforming messages such as json, xml, objects.
i have a very simple project on github with spring boot and camel if you want to check it.
https://github.com/chill-hub/spring_boot_camel_base_archetype
The Apache Camel version spring like is spring-integration at
https://spring.io/projects/spring-integration
Apache Camel and Spring Integration implements enterprise integration pattern called EIP. Please look at https://www.enterpriseintegrationpatterns.com/ first.
It is basically design patterns for workflow and orchestration !
You have an integration (starter) with spring boot made by spring named spring-boot-starter-integration.
You should probably look at Java Spring Config dsl reference at https://github.com/spring-projects/spring-integration-java-dsl/wiki/spring-integration-java-dsl-reference
which will show you a nice overview, with the more modern approach (xml, and annotation starts to disapear).
With what you need to do you will probably need https://docs.spring.io/spring-integration/reference/html/ws.html which is the web extension for spring integration.
Be careful it is a very elegant solution but with lot of abstraction and can be difficult at the beginning. Keep in mind EIP defines building block and vocabulary to build workflows, Apache Camel and Spring Integration are frameworks that implements these building blocks and offer a threading model abstraction (also queue persistant abstraction), and both have several extensions to adapt easily these building blocks to real word (web, ldap, databases, ...)
Both frameworks are good with pros and cons, but you will probably prefer spring integration in a spring ecosysteme team, same conventions than other spring modules !
Again theses framework are really elegant but abstraction has always a cost!
Disclaimer : I was a trainer for spring integration course - Official

Spring Test MockMvc perform request on external URL

I'm trying to perform a POST request on URL outside the current context, and it looks like Spring cannot understand it.
Test code:
String content = mvc
.perform(post("http://some-external-url.com:8080/somepath)
.header("Authorization", authorization)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("username", username)
.param("password", password)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
Works like a charm on current context. But remote service cannot be reached at all. It seems like "http://some-external-url.com:8080" part is ignored.
Mock creation code:
mvc = MockMvcBuilders.webAppContextSetup(context).build();
Is there any way to make it work? Because using standard Java HttpUrlConnection class is a huge pain.
No. There is no way to make the Spring MVC Test Framework work with external servers (or any actual server for that matter).
As stated in the Spring Reference Manual,
The Spring MVC Test framework provides first class support for testing
Spring MVC code using a fluent API that can be used with JUnit,
TestNG, or any other testing framework. It’s built on the Servlet API
mock objects from the spring-test module and hence does not use a
running Servlet container.
The last sentence spells it out: Spring MVC Test does not use a running Servlet container. In fact, it cannot be used with a running Servlet container or any kind of actual server (local or remote).
As an alternative, if you must test against an external server, you could then consider using REST Assured instead of Spring MVC Test for those special cases.
You can use new RestTemplate().getForObject("http://some-external-url.com:8080/somepath", String.class)

Transaction like logic while using web services

There are several update staments that can be done by web service calls. Those staments should be transactional; they must be done if and only if all can be done.
I cannot change the web services. what I can do is try to change all of them, if one of them fails I change back the previous ones. This plain sloution is pretty ugly.
Is there a more elegant approach to this problem ?
note: I am using JavaEE, SOAP, Spring MVC.
we have a #TransactionAttribute for different targets(method and class).
If you apply this annotation to a class with appropriate TransactionAttributeType(Constants) then that transaction strategy will apply to all the methods inside that class i.e You can keep all calls to your update statements in this class and inject this class where you are having your web services, so if even one update call fails it will rollback
You can write a Transactional class which uses Apache HTTP utils to call these web services one by one. ( This class should have a #Transactional annotation)

Restlet Client using JAX-RS annotated resources

I am writing a restlet client that will invoke some Resteasy coded rest services (cannot change the server code, hence cannot use the Restlet way of annotating resources).
Resource Interface is using JAX-RS annotations and have more than one #POST method (one of the biggest problems of Restlet when dealing with this).
I was trying to do my implementaion this way:
IAppLoginResource resource = JaxRsClientResource.createJaxRsClient("http://localhost:9090/rest", IAppLoginResource.class);
final GetLoginAppInfoResponse response = resource.getLoginAppInfo( getLoginAppInfoRequest );
The problem is that the request by default is GET, I didn't find a way to specify the request method like when using ClientResource (which I can't use because I need to deal with JaxbRepresentation and Jaxb problems).
Any sample/snippet of code that implement a Restlet client using JAX-RS annotated resources?
Any ideas?
Thanks,
I've entered an issue for this topic:
https://github.com/restlet/restlet-framework-java/issues/1081
I've tested a sample application based on your code, and it works properly using the current 2.3 branch (future 2.3.3). I wonder if the fix for this issue https://github.com/restlet/restlet-framework-java/issues/1072 helps.
Regarding the documentation, I 'll complete the current page (http://restlet.com/technical-resources/restlet-framework/guide/2.3/extensions/jaxrs), cf this issue: https://github.com/restlet/restlet-framework-java/issues/1084.
You can also have a look at the org.restlet.test project, especially in this package https://github.com/restlet/restlet-framework-java/tree/2.3/modules/org.restlet.test/src/org/restlet/test/ext/jaxrs.

springframework controller from standalone java code

We have Spring MVC application. One module requires to call the Spring Controller from standalone java app.
Can I do that?
Dead easy:
new java.net.URL("http://localhost:8080/path/to/your/controller").openStream();
Just like you would do it in the browser. If you want to call the Java code directly, do not publish your controllers. Instead, extract business logic and provide it as a library.
Yes.
It's a POJO, especially if you use Spring 3.x. The newest versions don't even extend an interface or base class.
I'd call it through its http interface as it's a Spring controller. You could use a clientside http request and use the response. I'm guessing the method you wish to call does not resolve to a view, if that's the case then just use something like the RestTemplate class that comes with Spring 3.
Not sure if it would be a good idea to call it directly as Spring MVC projects are usually hidden away inside servlet wars.

Categories

Resources