Spring redirect simple rest POST with body (json) on another port - spring

I have 2 spring rest applications.
When I send data to the first one,
private Long id;
private String name;
private String surname;
private String productName;
private Double productValue;
First I create a client entry in DB with the fields:
private Long id;
private String name;
private String surname;
and than
I would like to make a redirect post to another port, another application
handling product data with body including the two fields:
private String productName;
private Double productValue;
private Long clientId;
to create a product entry in the db
after creating product, I would like to redirect back to the first app and show the saved client.
The question is, how should I build my Controller?
Do I have to use ModelAndView? - this is only a backend rest, without any front (run from postman :)

You may like to do this way first autowire RestTemplate and then use it to call another api -
#RestController
public class ProductResource {
#Autowired
RestTemplate restTemplate;
#Autowired
private ProductRepository repository;
#PostMapping
public ResponseEntity<Product> saveProduct(#RequestBody Product product) {
Product productSavedAtClient = repository.save(product);
Product savedProduct = restTemplate.postForObject("http://some.other.app/product", productSavedAtClient, Product.class);
return ResponseEntity.ok().body(savedProduct);
}
}

Related

Fortify Cross-Site Scripting : Content Sniffing fix for DTO response

So I'm trying to fix Fortify Vulnerability Issue for content-sniffing, and this needs to use StringEscapeUtils.escapeHtml4 for all attributes of the DTO.
My problem is that the DTO is not a simple object, but rather having nested objects as its attributes:
Root DTO:
public class ServiceOrderListDTO implements Serializable {
private String count;
private String next;
private String previous;
private List<ServiceOrderDetailDTO> results;
}
public class ServiceOrderDetailDTO implements Serializable {
private static final long serialVersionUID = -819641011600662396L;
#JsonProperty("order_code")
private String orderCode;
#JsonProperty("service_number")
private String serviceNumber;
#JsonProperty("customer_name")
private String customerName;
#JsonProperty("customer_brn")
private String customerBrn;
private CustomerDTO[] customer;
#JsonProperty("order_details")
private OrderDetailsDTO orderDetails;
#JsonProperty("site_a_address")
private String siteAAddress;
#JsonProperty("site_b_address")
private String siteBAddress;
#JsonProperty("dff_service_order_id")
private String dffServiceOrderID;
#JsonProperty("dff_response")
private DffResponse dffResponse;
private MilestonesDTO milestones;
private AppointmentsDTO appointments;
}
So I need to Iterate through all the child objects and apply the escapehtml4 function one by one.
However I got feedback that this may lead to performance issue. Is there a way that the escapeHtml4 be applied in the DTO as a whole?
I've been going through SO also but no viable solution so far.
Cross-Site Scripting/Content Sniffing vulnerability detected through static scan for API while returning response

Spring Framework Responses from POST

What is the standard object design for accepting a POST request from a client, saving the record to the database, and then returning a response back to the client? I'm working with the Spring framework.
Should I be sending back the entity and hiding properties that aren't necessary for the response?
#RestController
public class SomeController {
private final SomeService service;
#PostMapping(value = "/post/new", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SomeEntity> post(#RequestBody final SomeEntity someEntity) {
SomeEntity savedEntity = service.save(someEntity);
return ResponseEntity.ok(savedEntity);
}
}
#Entity
#Table(name = "posts")
public class SomeEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "title")
private String title;
#Column(name = "body")
#JsonIgnore
private String body;
#JsonIgnore
#Column(name = "deleted_ind")
private boolean deleted;
#JsonIgnore
#Column(name = "author")
private String author;
#Column(name = "created_at")
private LocalDateTime createdAt;
}
or would I accept some sort of POST request object that I convert to an entity, then re-assemble the entity into a response?
#JsonIgnoreProperties(ignoreUnknown = true)
public class SomePostRequestResource {
private String title;
private String body;
private String createdAt;
}
#RequiredArgsConstructor
#RestController
public class SomeController {
private final SomeService service;
private final SomeResourceAssembler resourceAssembler;
#PostMapping(value = "/post/new", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SomePostRequestResource> post(
#RequestBody final SomePostRequestResource someResource
) {
SomeEntity savedEntity = service.convertToEntityAndSave(someResource);
SomePostRequestResource response = resourceAssembler.toResource(savedEntity);
return ResponseEntity.ok(response);
}
}
But then maybe I only want to send back the createdAt, would I hide the other properties in the SomePostRequestResource, or do I need another object to represent the response, which only has the property I want to send back?
I would also appreciate any book or article suggestions related to desigining objects for use with a RESTful API. I have seen articles concerning how to design and name the endpoints, but not so many concerning how to design the objects on the backend.
I would recommend you create a DTO class for the incoming/outgoing data containing the filed that are set/viewable by the client like:
public class SomeEntityIncomingDto {
private String title;
....
}
public class SomeEntityOutgoingDto {
private Long id;
private String title;
....
}
On the other hand, You won't need to map your persistence entities to DTOs and vice versa manually, you can use a library like ModelMapper or MapStruct that handles the conversion automatically.

POJO dataset nested rendering

My POJO Datasource basically contains following structure.
// Company.java
public class Company implements Serializable {
private static final long serialVersionUID = 3130918429913376956L;
private String name;
private String address;
private String contactPerson;
private String mobile;
private String fax;
private String bankDetails;
private String email;
private List<Employee> emps;
//getter and setter.
}
// Employee.java
public class Employee implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4473328670062370497L;
private String name;
private int age;
private String designation;
//getter and setter
}
My scenario is like following
One PDF report may have more that one Company (ie List< Company >)
In case of more than one Company, it should start at new page.
If Employee list goes to next page then it should repeat Header on the next page.
Layout -
Layout xml source
Output Page 1
Page 2
There are two issues with this design
Employee Name header is getting repeated for every employee.
Company Header (Comp Name -> Company A ) should be rendered only once.
Can anyone suggest me correct approach ? Thanks in advance.
Move the 'company name' to the Header row and set the header property to not repeating on new pages. Move the 'Employee name' out of the grouping with 'Employee', so up to the level where 'company name' is now.
I think you know everything to solve this, you just have to fiddle with the groupings a bit.

How to handle POST restful webservice in Spring MVC which consume and produce data and image both

I am developing webservice which contain some information with image , for example , develop webservice which contain user information with photo. I want this done by POST request. How can I achieve this?
I want to store only image path in database.
What changes should i make in controller to retrive image from mobile and store it in database? I am taking UserInfoTemp object as request body.
To developing webservice I am using Spring MVC 4.0.3.Release.
Here is my code please review it:
#Entity
public class UserInfoTemp
{
#Id
#GeneratedValue
#Column(name="UserId")
private Long id;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="Email")
#JsonProperty(value="email")
private String email;
#Column(name="Phone")
private String phone;
#Column(name="ProfilePicLink")
private String profilePicLink;
#Column(name="ProfilePicThumbnailLink")
private String profilePicThumbnailLink;
//getter setter
}
Controller:-
// for registering user
#RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<Object> register(#RequestBody UserInfoTemp userInfoTemp)
{
try
{
userInfoService.save(userInfoTemp);
return new ResponseEntity<Object>(userInfoTemp, HttpStatus.CREATED);
}
catch(Exception e)
{
Message message = new Message();
message.setStatus(false);
message.setMessage("User information can not be null");
return new ResponseEntity<Object>(message, HttpStatus.CREATED);
}
}

javax.validation getting ignore from jersey

I am trying to use Jersey to get JSON request from the user to create vendor
#POST
#Produces({APPLICATION_JSON})
#Consumes({APPLICATION_JSON})
#Path("create")
public Response create(VendorTO vendorTO) throws Exception {
But before it converts in vendorTO object I want to validate it with javax.validation
I have added constraints in my pojo like this
{#JsonSerialize(include=Inclusion.NON_NULL)
public class VendorTO {
#NotNull
private Integer userId;
#Size(min = 2)
private String vendorName;
private String address1;
private String address2;
private String city;
private String state;
private String country;
private String email;
private String phone;
}
but it doesnt seems to be working. Can anyone help ?
You need to tell the framework that the parameter should be #Validated:
#POST
#Produces({APPLICATION_JSON})
#Consumes({APPLICATION_JSON})
#Path("create")
public Response create(#Valid VendorTO vendorTO) {
// ...
}
At this point, it appears Jersey does not support JSR 303 natively. You might have to write some ResourceFilters and handle the validation manually.

Resources