how to properly create a rest method using dto - java

I need to send a request to a third-party service, then get an object from the response and display it on the browser.
package com.statusinfonew.springboot.controller;
import java.util.Collections;
import java.util.List;
import lombok.Data;
import lombok.val;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.statusinfonew.springboot.model.ParamsPays;
import com.statusinfonew.springboot.service.dto.OpenJsonFormat;
#Controller
#RestController
public class MyRestController {
RestTemplate restTemlate;
#GetMapping({"/"})
public String showGeneralPage(Model model) {
model.addAttribute("general", "Welcome to App");
return "hello";
}
#GetMapping(path = "/go")
public List<ParamsPays> getInfoError(#RequestParam(value="token") String token,
#RequestParam(value="orderId")String orderId){
final String url =String.format("https://exemple.ru/payment/rest/getOrderStatus.do?
token=%s&orderId=%s", token, orderId);
OpenJsonFormat dto =restTemlate.getForObject(url, OpenJsonFormat.class);
return Collections.singletonList(toModel(dto));
}
private ParamsPays toModel(OpenJsonFormat dto) {
return new ParamsPays();
}
package com.statusinfonew.springboot.service.dto;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
#Data
public class OpenJsonFormat {
#JsonProperty("actionCode")
private String actionCode;
#JsonProperty("amount")
private String amount;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date date;
}
When I enter a get request, an error is issued:
This application has no explicit mapping for /error, so you are seeing this as a fallback.
http://localhost:8080/go?token=sdwggvpa0k4ponpkt9&orderId=6afsf0-a0bc-7ffd-a9a8-790d4s179
Wed Apr 21 21:26:35 SAMT 2021
There was an unexpected error (type=Internal Server Error, status=500).
I understand that I am making a gross mistake. Please help me figure it out

Related

How to resolve error "System could not find specific path" - Java Spring Boot

I'm a beginner in the area of ​​programming and I'm developing a project where I'm trying to send data from my student registration form, which contains a file input for the student's profile picture, but every time I submit the data it's not registered and I get the same message:
error: "Internal Server Error"
message: "Invalid file: java.io.FileNotFoundException:
C:\fakepath\Perfil.jpg (System could not find specific path)"
status: 500
trace: "java.lang.IllegalArgumentException: Invalid file:
java.io.FileNotFoundException
Error description:
java.io.FileNotFoundException: C:\fakepath\Perfil.jpg (System could not find specific path)
at java.base/java.io.FileInputStream.open0(Native Method) ~[na:na]
at java.base/java.io.FileInputStream.open(FileInputStream.java:216) ~[na:na]
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157) ~[na:na]
at com.example.demo.controller.StudentController.saveStudent(studentController.java:63) ~[classes/:na]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:577) ~[na:na]
Function With Error in Student Controller:
package com.example.demo.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.relation.RelationTypeNotFoundException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import lombok.AllArgsConstructor;
#RestController
#RequestMapping("/registry/student")
#AllArgsConstructor
public class StudentController {
private final StudentRepository studentRepos;
private final ImageModelController imgCot;
#PostMapping
public Student saveStudent(#RequestBody Student record) throws IOException{
File arqFile = record.getPicByte();
FileItem fileItem = new DiskFileItemFactory().createItem("file",
Files.probeContentType(arqFile.toPath()), false, arqFile.getName());
// BELOW LINE WITH ERROR
try (InputStream in = new FileInputStream(record.getPicByte()); OutputStream out = fileItem.getOutputStream()) {
// ABOVE LINE WITH ERROR
in.transferTo(out);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid file: " + e, e);
}
CommonsMultipartFile multipartFile = new CommonsMultipartFile( fileItem);
imgCot.uploadFile(multipartFile);
return studentRepos.save(record);
}
}
Student Repository:
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
Class Student**:**
package com.example.demo.model;
import java.io.File;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.format.annotation.DateTimeFormat;
import lombok.Data;
#Data
#Entity
public class Student {
#Id
#Column(columnDefinition = "serial")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long idStudent;
#Column(length = 50, nullable = false)
private String studentName;
#Column(nullable = false)
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date startDate;
#Column(nullable = false)
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date endDate;
#Column(nullable = false)
private File picByte;
}

While Doing Request Validation in Springboot, Response is not as expected

I am trying to validate the json-resquest using hibernate-validator, it is working as expected but response is not there in postman.
Customer.java
import java.time.LocalDate;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({ "cin", "firstName"})
public class Customer {
#JsonProperty("cin")
private String cin;
#JsonProperty("firstName")
#NotEmpty(message = "First Name must have some values")
#Size(min = 2, message = "First Name must greater or equal to 2 characters")
private String firstName;
//getters and setters
}
and Errors class - to wrap error in one object.
public class Errors {
private Integer status;
private String message;
private List<String> details;
public Errors(Integer status, String message, List<String> details) {
super();
this.status = status;
this.message = message;
this.details = details;
}
// Getters and Setters
}
ControllerAdvice class
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.ecommerce.ms.customer.model.Errors;
#ControllerAdvice
#ResponseBody
public class CustomerExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(value=ConstraintViolationException.class)
public final ResponseEntity<Errors> handleConstraintViolation(ConstraintViolationException ex, WebRequest request) {
List<String> details = ex.getConstraintViolations().parallelStream().map(e -> e.getMessage())
.collect(Collectors.toList());
Errors error = new Errors(HttpStatus.BAD_REQUEST.value(), "Request Validation Error", details);
return ResponseEntity.badRequest().body(error);
}
}
CustomerController.java
*
*/
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ecommerce.ms.customer.api.service.CustomerService;
import com.ecommerce.ms.customer.model.Customer;
#RestController
#RequestMapping("/api/customers")
public class CustomerController {
#Autowired
private CustomerService customerService;
#GetMapping("/status")
public String getStatus() {
return "ok";
}
#PostMapping(consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON)
public ResponseEntity<Customer> addCustomer(#Valid #RequestBody Customer customer) {
return ResponseEntity.accepted().body(customerService.addCustomer(customer));
}
}
Hibernate-validator is already added pom.xml and I am expecting the below reason.
{
"status":400,
"message": "Request Validation Error",
"details":["First Name must greater or equal to 2 characters"]
}
I am trying to to get proper response body but I couldn't find it in postman.
Looking at the ResponseEntityExceptionHandler there is no such method that handles ConstraintValidationExceptions, and therefore the custom method you have created is not being called.
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.html
As well:
You cannot catch ConstraintViolationException.class because it's not
propagated to that layer of your code, it's caught by the lower
layers, wrapped and rethrown under another type. So that the exception
that hits your web layer is not a ConstraintViolationException.
Ref: SpringBoot doesn't handle org.hibernate.exception.ConstraintViolationException
An example of proper usage is to use the method handleMethodArgumentNotValid and return the Errors as body:
#RestControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler{
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
Map<String, Object> responseBody = new LinkedHashMap<>();
List<String> allErrors = new ArrayList<>();
ex.getBindingResult().getAllErrors().forEach(error -> allErrors.add(error.getDefaultMessage()));
responseBody.put("Errors:", allErrors);
return new ResponseEntity<>(responseBody, headers, status);
}
}

Spring boot with Mongo db rest Api

I have created a crud application Using spring boot initializer.
Dependencies:
Lombok
Spring Web
Spring Mongo
This app calls from a database/cluster that I have set up on atlas. but I want it to call the correct collection and just do a simple get all api call in postman
but I get a server 500 error
Service Java file:
package com.fullstack.app.Service;
import com.fullstack.app.exception.EntityNotFoundException;
import com.fullstack.app.Model.*;
import com.fullstack.app.Model.Request.WCCreationRequest;
import com.fullstack.app.Repository.StatusData_WCRepo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
#Service
#RequiredArgsConstructor
public class StatusDataService {
private static StatusData_WCRepo wcRepository;
public StatusData createData (WCCreationRequest request) {
StatusData statusData = new StatusData();
BeanUtils.copyProperties(request, statusData);
return wcRepository.save(statusData);
}
public static List<StatusData> getAllData() {
return wcRepository.findAll();
}
}
request:
package com.fullstack.app.Model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
#Document(collection = "StatusData_WC")
public class StatusData {
#Id
private String ID_Number;
private String Surname;
private String Full_Names;
private String Address;
private String VR;
private Integer Ward;
private Integer VD_Number;
}
Controller:
package com.fullstack.app.Controller;
import com.fullstack.app.Model.StatusData;
import com.fullstack.app.Model.Request.WCCreationRequest;
import com.fullstack.app.Service.StatusDataService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import lombok.RequiredArgsConstructor;
#RestController
#RequestMapping(value = "/api/statusData")
#RequiredArgsConstructor
public class StatusDataController {
private final StatusDataService sdService;
#GetMapping("/statusdata")
public ResponseEntity getAllData(#RequestParam(required = false) String id) {
if (id == null) {
return ResponseEntity.ok(StatusDataService.getAllData());
}
return ResponseEntity.ok(StatusDataService.getAllData());
}
}
Application properties:
spring.data.mongodb.uri=mongodb+srv://*****:******#cluster0.wlmmf.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

Can a Hibernate #Id be a string? [duplicate]

This question already has answers here:
Hibernate String Primary Key with Annotation
(4 answers)
Closed 2 years ago.
I have a table with some information of company offices and its Id is a string. I'm trying to map it in Hibernate with the #Id tag but its giving me an error for java.lang.NumberFormatException
This causes me to wonder if its possible to use strings as Ids or if I'm missing something?
Here is the error:
Jul 23, 2020 1:18:09 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.NumberFormatException: For input string: "officeCode"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at javax.el.ListELResolver.coerce(ListELResolver.java:150)
at javax.el.ListELResolver.getValue(ListELResolver.java:67)
...
This is the office class:
package com.ver.company.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "offices")
public class Office implements Serializable{
public Office() {}
#Id
private String officeCode;
#Column
private String city;
#Column
private String phone;
#Column
private String addressLine1;
#Column
private String addressLine2;
#Column
private String state;
#Column
private String country;
#Column
private String postalCode;
#Column
private String territory;
}
}
Dao implementation:
package dom.ver.company.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import dom.ver.company.model.Office;
#Repository
public class OfficeDaoImpl implements OfficeDao {
public OfficeDaoImpl () {}
#Autowired
private SessionFactory sessionFactory;
public void insertOffice(Office office) {
sessionFactory.getCurrentSession().saveOrUpdate(office);
}
public List<Office> selectOffices() {
return sessionFactory.getCurrentSession().createQuery("from Office")
.list();
}
}
Service:
package dom.ver.company.service;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import dom.ver.company.OfficeDao;
import dom.ver.company.dao.OfficeDaoImpl;
import dom.ver.company.model.Office;
#Service
#Transactional
public class OfficeServiceImpl implements OfficeService {
#Autowired
private OfficeDao officeDao;
#Override
#Transactional
public List<Office> selectOffices() {
return officeDao.selectOffices();
}
}
Controller class:
package dom.ver.company.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import dom.ver.company.model.Office;
import dom.ver.company.service.OfficeService;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
#Controller
public class OfficeController {
#Autowired
OfficeService officeServiceImpl;
OfficeController(){}
#RequestMapping({ "/", "/index" })
public ModelAndView loadIndex(ModelAndView model) {
List<Office> officeList = officeServiceImpl.selectOffices();
model.addObject("officeList", officeList);
model.setViewName("index");
return model;
}
}
If you don't specify the generation strategy, Hibernate will use GenerationType.AUTO, which is not applicable to String.
You can use it like this:
#Id
#GeneratedValue(generator="uuid")
#GenericGenerator(name="uuid", strategy="uuid2")
private String officeCode;

how can i get the object not map address?

I'm try to connect java spring boot with mysql. when i run the code i got the map address like this
This is my first code
This is EmpController1
package com.example.rest.controller;
import com.example.rest.repository.R1pro;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.rest.repository.EmpRepository1;
import java.util.ArrayList;
import java.util.List;
#RestController
#RequestMapping(value = "/emp")
#Slf4j
public class EmpController1 {
#Autowired
private EmpRepository1 empRepository1;
#RequestMapping(value="/ee", method = RequestMethod.GET)
#ResponseBody
public String getCategoryList() {
List<String> sj = new ArrayList<String>();
Gson gson= new Gson();
System.out.println(123);
List<R1pro> emps1 = this.empRepository1.findByLimit();
return emps1.toString();
}
}
This is my EmpRepository1 code
package com.example.rest.repository;
import com.example.rest.Emp;
import com.example.rest.Emp1;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface EmpRepository1 extends JpaRepository<Emp1, Integer> {
#Query(value = "select * from d_RANGE limit 1",nativeQuery = true)
public List<R1pro> findByLimit();
}
This is R1pro code
package com.example.rest.repository;
import java.util.Date;
public interface R1pro {
public String USER_ID();
public String CUST_GP();
}
This is my Emp1 code
package com.example.rest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;
#Entity
#Table(name = "TEMP_TEST_M78_2W")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Emp1 {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String USER_ID;
private String CUST_GP;
}
This is my Application code
package com.example.rest;
import com.example.rest.repository.EmpRepository;
import com.example.rest.repository.EmpRepository1;
import com.example.rest.repository.R1pro;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.List;
#SpringBootApplication
#Slf4j
public class Application {
#Autowired
EmpRepository empRepository;
#Autowired
EmpRepository1 empRepository1;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
CommandLineRunner start() {
return args -> {mysql();};
}
private void mysql() {
List<R1pro> emp1 = this.empRepository1.findByLimit();
}
}
When i run the code i got this result
[org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap#27ae5583]
So i change the EmpController1 code
package com.example.rest.controller;
import com.example.rest.repository.R1pro;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.rest.repository.EmpRepository1;
import java.util.ArrayList;
import java.util.List;
#RestController
#RequestMapping(value = "/emp")
#Slf4j
public class EmpController1 {
#Autowired
private EmpRepository1 empRepository1;
#RequestMapping(value="/ee", method = RequestMethod.GET)
#ResponseBody
public String getCategoryList() {
List<String> sj = new ArrayList<String>();
Gson gson= new Gson();
System.out.println(123);
List<R1pro> emps1 = this.empRepository1.findByLimit();
for (int i =0; i<emps1.size();i++)
{
sj.add(emps1.get(i).USER_ID()+" "+ emps1.get(i).CUST_GP());
}
return sj.toString();
}
}
When i run the code i got this Error message
java.lang.IllegalArgumentException: Invoked method public abstract java.lang.String com.example.rest.repository.R1pro.USER_ID() is no accessor method!
Actually this method same as mysql data columns
USER_ID varchar(150)
CUST_GP varchar(1)
This is my sql columns informations
I don't know what is the problem also any solution.. so if someone knows that please teach me
I really admire to solve this issue
thank you!
You need to tweak your interface into something like this -
public interface R1pro {
String getUSER_ID();
String getCUST_GP();
}
The resultset is mapped only to the getter methods similar to the one created in Emp1 class

Categories