Consuming spring Rest api - java

I want to create a restful webservice with spring mvc. I followed some tutorials and could
work out how to create a webservice with spring. But I am not understanding how to
make it work for my requirement.
My requirement is a company xyz sends an xml file with its usage details to my company abc.
NOw my company has to consume that xml file with spring rest api and store the details in
database.Any help is appreciated.
In spring webservices I have only seen examples like crud opeartion for employees,persons
but how to match it with my requirement.
Thanks in advance.
Here are sample example I looked into:
"https://www.ibm.com/developerworks/webservices/library/wa-spring3webserv/"
"http://spring.io/guides/gs/consuming-rest/"
suppose the following is the xml my rest api is consuming and I want to put those details in a database, how can I do it.
<Usage xmlns="http://www.abc.com/abc/It/schema"
xmlns:id="http://standards.iso.org/iso/19770/-2/2009/schema.xsd">
<timestamp>2010-01-01T12:38:11.123Z</timestamp>
<proxy>
<address>host address</address>
<platforms>xyz</platform>
</proxy>
<as> <label>Label name</label><name>sdff</name>
<id><a_id>34D87XHF72122</a_id><line>sadf</line>
<title>adffdn<title>
<version>3.1</version> <creator>abc Corp.</creator>
<license>abcCorp. </license></id>

If the company xyz is sending an XML file to your server, you would want to use a method similar to this to handle the request and not return any content back:
#RequestMapping(value="/xyz", method = RequestMethod.POST, consumes = {"text/xml"})
#ResponseStatus(HttpStatus.OK)
public void processXML(#RequestBody Object someObject) {
}
EDIT: See the Spring docs on #RequestBody: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestbody

Related

Should I call an API in my Microservice Or call the API in the filter of my API Gateway

Background
Each request will run through an API Gateway, each request will have a JWT with custom claim "x-token". Now, this "x-token" is an id that I will use to get the corresponding data in the DB. The "x-token" will be used in about 2 (out of 3) of my microservices.
Question
Where should this API call should happen?
My current plans are:
1. [API GATEWAY FILTER APPROACH]
Add an API Filter in my Spring Cloud Gateway to modify every (GET/POST) request
-Create a Filter and inside the filter perform an api call to get xTokenObject associated with the "x-token", and then modify to add the xTokenObject in the #RequestBody so that on the Controller part of my microservice I could easily use it.
PROS
API Gateway will be the only one have access to it
I can easily use it on the controller function
Sample Code on the Controller of my Microservice where the 'xTokenObject' was added on the Gateway Filter:
#PostMapping()
public ResponseEntity<SomeObject> someMethod(#RequestBody #Valid XTokenObject xTokenObject){
return ResponseEntity.ok(this.someService.someFunction(xTokenObject));
}
CONS
What if there is already a #RequestBody? How should I add this xTokenObject to that #RequestBody? And how can I access it on the Controller of my microservice?
2. [MICROSERVICE CALL]
Modify the header to add "x-token" in the Gateway Filter and then use it to easily call the API on the #Service of my microservice
PROS
Implementation is easy since adding of custom header is easy on the Gateway Filter than modifying the request body
Sample Code on the Service of my Microservice:
#Service
public class SomeService {
public SomeObject someFunction(String xTokenId) {
// API CALL HERE USING THE xTokenId
return someObject;
}
}
CONS
All of my microservice will have a connection to it
Additional Question and Considerations:
Which one is faster? Or there is another better way? The data on the Token Data Microservice might contain some sensitive data so it will be encrypted. So it will be on the same DB of my auth-server but different table. I will also consider using Redis to cache these data. I included a photo on this question so you guys have an overview.

HTTP Post request handler in java

I hope someone will be able to help me understand how to create an endpoint HTTP server listener. I'm trying to create a POST request handler that can save all post requests made to a text file.
The purpose is for a Game state integration between My application and Counter-Strike. Ive read their documentation (csgo GSI documentation) and the example given in here is almost exactly what I'm looking for. But its written in nodejs and I will need it to work with Java.
I have only been able to create a HTTPServer but can't seem to understand how I can create a POST request handler which records the data sent to "data" request.
How can I create a handler which can record all requests sent to data?
I believe the easiest & fastest way is to grab a SpringBoot app from https://start.spring.io/ (add Web dependency). And then create a Spring #RestController like that:
#RestController
#RequestMapping(value = "/cs")
public class CsController {
#RequestMapping(value = "", method = RequestMethod.POST)
public void processCsData(#RequestBody CsData csData) {
processCsData(csData);
}
}
where CsData is a POJO class that they send to you. processCsData() is your method to do whatever you like with the data.
Now you need to host it somewhere so that it would be reachable from the Internet or you can use https://ngrok.com/ to create a tunnel for test purposes.

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
}
}

RESTful API with Java Jersey and MongoDB

I am newbie with RESTful services, I am trying to make a restful api with the Jersey framework and MongoDB, my question is : How can i search data in the URL.
e.g : "localhost:9999/home/users/find?id=12345", it will return the user with the id = 12345
How can we do that with Jersey ?
Thank's
You want to look into #PathParam and #QueryParam. You can find more about both of them here:
http://docs.oracle.com/cd/E19776-01/820-4867/6nga7f5np/index.html
In short, a path param is the bit between the '/', in your example this is "find". and the query param is id, which has a value of 12345.
You will then need to look this up in a database I assume to get your result to return.
You may want to look at an article I wrote a few years ago. I have a full stack MongoDb, Jersey, Jetty server user admin application at the following github [here](https://github.com/pmkent/angular-bootstrap-java-rest"Angular Bootstrap Java Rest")!
To use a query parameter in Jersey, you'll define it in the jersey Method signature like so:
#GET
#Path("home/users/find")
public Response myMethod(#QueryParam("id") int id) {
// utilizes the id specified in the url parameter "id"
User user = someMongoMethodToFindById(id);
}
Once you harvest the id correctly, you can then query your MongoDB however you'd like based on that passed-by-reference id.
In Jersey, this method is often wrapped in a class in which all related Jersey Resources can be organized. My examples given utilize the Jersey Annotation style.
#Path("home/users")
public class UserResources {
#Path("find")
public Response myMethod(#QueryParam("id")) {
...
}
}

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?

Categories

Resources