Flow of data between Angular 2 and Spring - java

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.

Related

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

Design Pattern: Domain class and Http Response Class

I have a request that creates a payment. A payment has a form of payment that can be credit card or ticket.
When I return the HTTP response I would like to not have to verify what form of payment was used. The way I did this was by having my model class know how to create the form of payment response.
My question is: Is code smells considered the domain class know how to create the response class of an HTTP request? If yes, what's the best way to handle with this situation?
Example for a better understanding of the question:
class Payment {
private BigDecimal value;
private PaymentMethod method;
}
abstract class PaymentMethod {
public abstract String getResponse();
}
class Card extends PaymentMethod {
//attributes
public Response getResponse() {
return new CardResponse();
}
}
class Ticket extends PaymentMethod {
//attributes
public Response getResponse() {
return new TicketResponse();
}
}
Is code smells considered the domain class know how to create the response class of an HTTP request?
Probably yes. It will be harder to test as your unit tests will now need to be aware of HTTP. It also limits the usability of your domain class. If you end up needing to use another endpoint technology other than HTTP (SOAP, web sockets, etc.) you will have a problem. If you end up returning a redirect response then it spreads your URL mapping throughout your application making it harder to keep a handle on that.
Now, if I were to inherit your code base I wouldn't necessarily jump in and change it right away. I wouldn't say it is a fatal flaw but it isn't something I would do in a new project.
If yes, what's the best way to handle with this situation?
This question is probably overly broad and you haven't given a lot of details so here is a generic answer.
The simplest solution I've seen is to have a layer on the outermost of your application whose job is to convert from HTTP to domain logic and back. These types are often called controllers but that word is used so much I prefer the word endpoints. Forgive my pseudocode here, it's been a while since I've used the Java HTTP types.
// Crude example
public class PaymentEndpoint {
public Response handlePayment(HttpRequest request) {
if (request.getContentType() == "application/json") {
Ticket ticket = deserializeTicket(request);
Payment payment = this.paymentService.processTicket(ticket);
return serializeTicketPayment(Payment);
} else if (request.getContentType() == "application/x-www-form-urlencoded") {
CCInfo ccInfo = getCcInfoFromForm(request);
Payment payment = this.paymentService.processPayment(ccInfo);
return serializeCcPayment(payment);
}
}
}
However, that can lead to a lot of boilerplate code. Most HTTP libraries now have methods for doing the domain->HTTP conversion in filters. For example, JAX-RS has annotations you can use to specify which method to use if the content type is X and which to use if the content type is Y and annotations to populate method parameters from form fields or JSON content.
JAX-RS also allows you to return POJOs from your endpoints and it will handle the conversion to a response in its own logic. For example, if you return an object, it will use Jackson to serialize the object to JSON and set the response status to 200. If you return void then it will set the response status to 204.
// Crude example
public class PaymentEndpoint {
#Consumes("application/x-www-form-urlencoded")
public Payment handleCcPayment(#FormParam("name") String name) {
CCInfo ccInfo = new CCInfo(name);
return this.paymentService.processPayment(ccInfo);
}
#Consumes("application/json")
public Payment handleTicketPayment(Ticket ticket) {
return this.paymentService.processTicket(ticket);
}
}
Now, I'm not entirely sure what your asking, but it almost seems like you might need to serialize a ticket payment to HTTP very differently than the way you would serialize a credit card payment to HTTP. If they are simply different JSON objects you can use the example above. However, if you need to set certain HTTP headers in one response and not the other then you might have to do something more fancy.
You could just shove the logic in the endpoint:
if (payment.getPaymentMethod() instanceof Card) {
//Set special HTTP headers
}
However, if you have several endpoints that have to repeat this same logic then it can quickly become boilerplate code. Then you usually extend your filter layer to control the serialization. For example, in JAX-RS there is the concept of a MessageBodyWriter. You can give the JAX-RS framework a custom message body writer which tells it how to convert a card payment into an HTTP response. Although if you were just setting HTTP headers you could probably use a ContainerResponseFilter instead.

How to return a subset of object properties from a Spring Boot restful GET call?

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

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")) {
...
}
}

Categories

Resources