Can I get Swagger json from a swaggerui url, using Springfox? - java

So, I have a spring boot Rest API running (A).
I want to create a separate app(B) which shows the swagger document of A. In order to achieve that I guess I'd have to be able to capture the Swagger json of A, perhaps in a SwaggerResource
springfox.documentation.swagger.web.SwaggerResource
but I don't know how to construct a SwaggerResource object (or similar) from a URL (e.g."http://localhost:9091/swagger-ui.html"). I would have thought this was a trivial enough task, but it has me beat. I'm trying to avoid using eureka.

Related

Spring Boot creating an XML endpoint

I have been learning spring-boot for a while and building learning projects step by step. I am currently doing a project, what i am trying to achieve is building a web endpoint which receives an XML data/list as an input and write it to DB.
To make my point clear:
I have a JMS Queue and a working program that reads the Queue, parse it to defined xml format and publish it to an endpoint.
My new project is supposed to listen for XML data, parse it based on a predefined class matching the XML structure (i am thinking of defining the structure with a class) and using JPA to persist an instance of the class(parsed XML) to the database.
Previously i have some experience with basic RESTful web-service projects with GET,POST,DELETE methods.
What i am asking is :
Is my above outline feasible
I can not find a way to implement parsing of an XML to an Object
In the controller class (that's what i've been using for REST) what method do i use as an entry point.
Thank you.
You can use a put or post method in a REST controller that Consumes XML data.
#RestController
#RequestMapping(value = "/myRestPath", consumes = "application/xml")
public class MyXmlController{
#PutMapping
public void putXmlObject(MyXmlObject myXmlObject){
// do somthing
}
}

Do we need to stub the other micro service in Spring cloud contract

#marcin
I am doing a pilot on implementing the spring cloud contract for Micro services which has around 50+ services talking to each other. I have few questions which I haven't found the answer precisely in your document.
The service which I am building has controller which processes and transforms my input payload to the desired output in json format. This json is used to build desired structure that should match the response in groovy (Our contract). However the controller, is sending json to another services with some URL as shown below.
request_url=http://localhost:8090/services/rest/transact/v2/pay/validate/0000118228/new response_body=null
Basically it is expecting the Response back from the other service by making use of this json and now response_body=null
My question is do I need to create a stub or mock the service? to make use of this response as an input to produce expected output from the response. Basically the microservice is expecting a ServiceResponse.
Another question is do we need to load in-memory data while doing the contract testing or do we need to just test the controller itself?
I don't really follow your description... "The service which I am building has controller which transforms my input payload sent from groovy and giving the desired output in json format" . Sent from which groovy? Groovy application? Can you explain that in more depth?
But I guess I can try to answer the question anyways...
My question is do I need to create a stub or mock the service? to make use of this response as input to produce expected output from the response. It is expecting a ServiceResponse.
If I understand correctly - service you mean a class not an application? If that's the case then, yes, in the controller I would inject a stubbed service.
Another question is do we need to load in-memory data while doing the contract testing or do we need to just test the controller itself?
That's connected with the previous answer. Your controller doesn't delegate work to any real implementation of a service, so no access to the DB takes place. If you check out the samples (https://github.com/spring-cloud-samples/spring-cloud-contract-samples/blob/master/producer/src/test/java/com/example/BeerRestBase.java) you'll see that the base class has mocks injected to it and no real integration takes place
EDIT:
"The service which I am building has controller which transforms my input payload sent from groovy and giving the desired output in json format" is actually the description of what is done via the Spring Cloud Contract generated test. The next sentence was
However the controller, is sending json to another services with some URL as shown below.
In Contract testing, I don't care what your controller further on does. If it's in the controller where you send the request to some other application then you should wrap it in a service class. Then such a service you would mock out in your contract tests. What we care about in the Contract tests is whether we can communicate. Not whether the whole end to end functionality is working correctly.

Vertx model binding for my Rest API layer

I'm using Vertx 3, and I'm trying to find a good decoupled module that knows to turn query-string, headers and both content-type and body into a bean?
I know spring does that and various other frameworks as well, but I don't want to introduce a new framework i just want a super fast model binder that will either know to auto bind to a certain method or at least auto bind a certain class so i can invoke my rest method that currently accept one parameter, which is the model.
public ResponseBase query(QueryRequest model){ ... }
I don't mind adding annotations to the parameters etc.
Thanks!
Current my team use vertx Json.decodeValue to turn body (json string) to java class.
MyClass body = Json.decodeValue(rc.getBodyAsString(), MyClass.class);
to config Json to handle unknown properties, I setting
Json.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
for your query string, I think it is easy to write a class to convert it to a json string :)
I also catch DecodeException on Json.decodeValue to re throw a 400 Bad Request error.

POST request using Spring RestTemplate with XML body as String

I need to make a rest call to share a post in Linkedin and I am using Spring Social Linkedin module for that. Unfortunately I cannot simply use
org.springframework.social.linkedin.api.NetworkUpdateOperations.share(NewShare share)
method, I am working on a project that provides the raw rest template to the users, and users can make any rest call to any url using it. I am using Spring Social's Linkedin module just for the authentication part (and it works as it should).
So, I provide to users the rest template behind the Linkedin Spring Social Linkedin module. And they should be able to post a share to Linkedin with a given url and data in runtime. The request body should contain something like this (taken from here):
<share>
<comment>Check out the LinkedIn Share API!</comment>
<content>
<title>LinkedIn Developers Documentation On Using the Share API</title>
<description>Leverage the Share API to maximize engagement on user-generated content on LinkedIn</description>
<submitted-url>https://developer.linkedin.com/documents/share-api</submitted-url>
<submitted-image-url>http://m3.licdn.com/media/p/3/000/124/1a6/089a29a.png</submitted-image-url>
</content>
<visibility>
<code>anyone</code>
</visibility>
</share>
To share, I create a String with that xml and use the command postForObject. Like this:
String toShare = "<share><comment>Check out..." // the string of xml
Object result = linkedinRestTemplate.postForObject("https://api.linkedin.com/v1/people/~/shares", toShare, Object.class);
But this call fails with a response 400 Bad Request. It seems like rest template handling this xml string and not as an object, so it is not serialized and put to the request body properly.
Spring Social Linkedin does the same thing but only with a difference: It has a serializable class called NewShare which have the same structure of that xml. But when an instance of the NewShare is given as body to the request, it is successful. Like this:
NewShare share = new NewShare();
share.set... // set its properties, sub-classes, content etc.
Object result = linkedinRestTemplate.postForObject("https://api.linkedin.com/v1/people/~/shares", newShare, Object.class);
This call is successful.
But I cannot deserialize my String into NewShare because I am providing an API so I assume I have absolutely no information about the request body.
So how can I manage to make spring handle the string xml body correctly and make a proper service call?

REST API invocation in Java

Suppose I need to write a Java client, which calls a REST API (with HTTP GET). I know it returns the data in JSON by default and I do not need to supply any headers.
Now I can use either Apache HttpClient to invoke the API or read the URL directly (get a stream from the URL with url.openStream and read the data). The second approach seems to me much simpler. Which one would you suggest and why ?
All the REST clients provide a wrapper over basic java URL based APIs. These clients are easy to use and provide all the necessary functionality. Your code will be much cleaner in case you use Apache HttpClient. And Apache's API are quite reliable.
I would use special libraries for that, like Jersey client or Apache CXF client.
https://jersey.java.net/documentation/latest/client.html
http://cxf.apache.org/docs/jax-rs.html
These ones are part of Java EE standard, a well defined specification which is widely used.
For JSON, consider https://github.com/FasterXML/jackson. Depending on what client you use, you will find information about how to make it work.
If you are not a big fan of JavaEE, and you look for neat and elegant API, and you are interested in working with a language on top of Java, Groovy HTTPBuilder is such a library that works like a charm!
twitter = new RESTClient( 'https://twitter.com/statuses/' )
resp = twitter.post( path : 'update.xml',
body : [ status:msg, source:'httpbuilder' ],
requestContentType : URLENC )
assert resp.status == 200
assert resp.data.user.screen_name == userName
You can use spring-data-rest and Spring's RestTemplate. No need to write a webapp as you can bootstrap Spring easily into a standalone java application putting AnnotationConfigApplicationContext in the Main(). It's quite simple.
For example, suppose you have a Restful URL, http://localhost:8080/croot/books/ that returns a list of books (deserialized into objects of type Book).
Using Spring's RestTemplate you can do the following:
public Resource<List<Resource<Book>>> findAll() {
return restTemplate
.exchange(
"http://localhost:8080/croot/books/",
HttpMethod.GET,
null,
new ParameterizedTypeReference<Resource<List<Resource<Book>>>>() {
}).getBody();
}
You can also process this using spring-data-hateoas allowing you to further decouple the client from the server and helps process what to do next, say in pagination.
This is a very simplified/contrived example but the REST support in Spring 3 combined with the spring-data framework is quite elegant.
Using Spring you also get the advantage of Jackson for JSON processing as the RestTemplate will have one of the flavors of Jackson's message converters (provided through MappingJackson2HttpMessageConverter for example) in it's list of default converters used for processing.

Categories

Resources