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
}
}
Related
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.
#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.
Newbie question...
I'm building my first Spring Boot restful service and want to support a GET call that returns a collection of entities. like:
/api/customers/
However, for certain consumers -like a list page in a web UI - they would only need a subset of the customer entity properties.
I'm thinking that I could add request parameters to my GET call to set the consumers specific field requirements, like
/api/customers/?fields=id,name,address
But what's the best way of implementing this inside the Java restful controller?
Currently in my rest controller the 'GET' is request mapped to a Java method, like
#RequestMapping(value="/", method= RequestMethod.GET)
public Customer[] getList() {
Customer[] anArray = new Customer[];
....
return anArray;
}
Is it possible to somehow intervene with the default Java to Json response body translation so that only the required properties are included?
TIA
Adding fields parameter is a good idea, best practice according to http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#limiting-fields
How to leave fields out?
1) Set them to null, possibly in a dedicated output class annotated with #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
Or
2) Use SimpleBeanPropertyFilter See a good step by step tutorial here 5. Ignore Fields Using Filters
I am about to start my first real project for work (new grad), and I was tasked with creating an internal address book for the company (displaying name, phone extension number, email etc).
My mentor told me that I need to pull the address data from Active Directory.
He also told me that I need to use Angular 2 for the front end, and Spring for the backend. I still need to learn these frameworks, but he realizes this which is precisely why he gave me this task.
However, I am struggling to understand the flow of data between the frameworks.
This is what I am thinking so far http://imgur.com/a/xiH6m.
If someone could please explain what is right/wrong with the diagram and perhaps explain how the data would flow in such a project. I would prefer to bother my mentor with more specific questions.
Just create a REST service with Spring that returns the data as JSON. You can use a simple POJO on the server side, and the converter for Spring should convert it to JSON. Maybe something like
#RestController
public class EmployeesController {
#Autowired
private LdapService service;
#RequestMapping(value = "/employees/{empId}")
public Employee getEmployee(#PathVariable("empId") Long empId) {
Employee emp = ldapService.getEmployee(empId);
return emp;
}
}
With Spring, it should convert the Employee object to JSON on the outbound response (given you have the JSON converter configured).
In Angular, just make a simple Http request to the endpoint, and you will get back JSON, for which you can convert it to an Employee object on the client side. Maybe something like
class Employee {
// employee properties
}
#Injectable()
class EmployeeService {
constructor(private http: Http) {}
getEmployee(empId: number): Observable<Employee> {
return this.http.get(`${empBaseUrl}/${empId}`)
.map(res => res.json() as Employee)
}
}
Here, in the service, you make the Http request to the employee endpoint on the server, and get the result back as JSON, for which you convert it to an object with res.json() and cast it to Employee
That's pretty much it.
Your "Converts to useful format" will not happen on its own. You need a Controller layer there. REST Controller to be precise.
AngularJS 2 is built to work easily with REST. You can use Spring MVC to create REST Controllers which can generate JSON Response.
for Example you can have an Endpoint
GET /contacts/data
which will return
[
{"name":"ABC",
"email":"someone#abc.com",
"telephone":"0101010101"
},
...
]
The following Spring documentation will be a good starting point eventhough it talks about Angularjs 1.
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