Spring InitBinder, Binding date of list of nested Beans - spring

I have Bean DealSheetForm which has List of OrderDto beans as its property.
OrderDtos has 4 datefields. I used #InitBinder to bind date format as MM/dd/yyyy at controller. Now I need to modify one of the date fields format to MM/dd/yyyy hh:mm:ss
I tried creating 2 CustomDateEditors in #InitBinder but that did not have any change on dateformat. If anyone has possible solution, please help me out.
Here is the DealSheetBean which contains OrdersDto Bean:
public class DealSheetForm {
private CustomerDto customer=new CustomerDto();
private AutoPopulatingList<OrdersDto> orders =new
AutoPopulatingList<OrdersDto>(OrdersDto.class);
public AutoPopulatingList<OrdersDto> getOrders() {
return orders;
}
public void setOrders(AutoPopulatingList<OrdersDto> orders) {
this.orders = orders;
}
public CustomerDto getCustomer() {
return customer;
}
public void setCustomer(CustomerDto customer) {
this.customer = customer;
}
}
Here is my Controller
#Controller
public class DealSheetController{
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM/dd/yyyy
HH:mm:ss");
dateFormat.setLenient(false);
dateTimeFormat.setLenient(false);
binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,
true));
binder.registerCustomEditor(Date.class,"orderDate",new
CustomDateEditor(dateTimeFormat, true));
}
#RequestMapping(value="/agent/dealsheet.do",method=RequestMethod.POST)
#ResponseBody
public String saveDealSheets(#ModelAttribute("dealSheet") DealSheetForm
dealSheet,Map<String,Object> map,HttpServletRequest
request,HttpServletResponse response){
try{
log.info("inside saveDealSheeeeeets()");
Authentication
auth=SecurityContextHolder.getContext().getAuthentication();
String user=auth.getName();
HoveyUserDto userDto=this.userService.getUserByUsername(user);
String agentNumber=userDto.getAgentNumber();
this.dealSheetService.saveDealSheetToDB(dealSheet,agentNumber);
String message="Orders Saved Successfully";
map.put("message", message);
return "success";
}
catch(Exception e){
log.error(e.getStackTrace().toString());
return "error";
}
} }

Related

Spring validating a object before returning it in a function not working

I have a service, that gets an xml/json string, tries to read it as an pojo, then returns it. Then, I want to show the result in thymeleaf. I did that successfully, but - in the model I have validation annotations, but if I submit invalid information it accepts the value, although I validated the method. Here is my code:
Controller:
#Controller
public class ConvertController implements WebMvcConfigurer {
#Autowired
PrintJSON printJSON;
#Autowired
PrintXML printXML;
#Autowired
ReadJSON readJSON;
#Autowired
ReadXML readXML;
#GetMapping("/read")
public String showReadForm() {
return "read";
}
#PostMapping("/read")
public String read(#RequestParam(value = "convertFrom") String
convertFrom, String text, Model model){
if("json".equals(convertFrom)){
Book newBook = readJSON.read(text);
model.addAttribute("result", newBook);
return "converted";
}else if("xml".equals(convertFrom)){
Book newBook = readXML.read(text);
model.addAttribute("result", newBook);
return "converted";
}
return "read";
}
#GetMapping("/print")
public String showPrintForm(Book book){
return "convert";
}
#PostMapping("/print")
public String convert(#RequestParam(value = "convertTo") String
convertTo, #Valid Book book, Errors errors, Model model) {
if(errors.hasErrors()){
return "convert";
}
if("json".equals(convertTo)){
model.addAttribute("result", printJSON.getJSON(book));
return "converted";
}
if("xml".equals(convertTo)){
model.addAttribute("result", printXML.getXML(book));
return "converted";
}
return "convert";
}}
Service
public class ReadXML {
#Autowired
#Qualifier("XmlMapper")
XmlMapper xmlMapper;
#Valid
public Book read(String xml){
try{
#Valid Book book = xmlMapper.readValue(xml, Book.class);
return book;
}
catch(JsonProcessingException e){
e.printStackTrace();
return new Book();
}
}
}
Model
public class Book {
#NotEmpty
private String title;
private String description;
private Date publishDate;
private int ISBN;
private List<#Valid Author> authors;
#Override
public String toString(){
String bookString = String.format("Title: %s\nDescription: %s\nPublish Date: %s\nISBN: %s\nAuthor", title, description, publishDate, ISBN);
for(Author a : authors){
bookString += a.toString();
}
return bookString;
}
public String getTitle() {
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(String newPublishDate) throws ParseException {
Date publishDate = new SimpleDateFormat(Constants.dateFormat).parse(newPublishDate);
this.publishDate = publishDate;
}
public int getISBN() {
return ISBN;
}
public void setISBN(int ISBN){
this.ISBN = ISBN;
}
public void addAuthor(Author author) {
authors.add(author);
}
public List<Author> getAuthors(){
return authors;
}
}
Where is my problem???
Thank you!

Format Date with OpenFeign

My Feign client is defined as follow :
#FeignClient(name = "${feign.name}",url = "${feign.url}",
configuration = {DateFormatConfiguration.class})
public interface MyFeignClient {
#GetMapping(value = "/test")
ResponseEntity<MyResponse> getResponse(#RequestParam(value = "date") Date date);
}
Where :
class DateFormatConfiguration {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
#Bean
public FeignFormatterRegistrar dateFeignFormatterRegistrar() {
return formatterRegistry -> formatterRegistry.addFormatter(new Formatter<Date>() {
#Override
public Date parse(String text, Locale locale) throws ParseException {
return df.parse(text);
}
#Override
public String print(Date object, Locale locale) {
return df.format(object);
}
});
}
}
However when I run this test :
#Test
public void test(){
Date date= new GregorianCalendar(2000, 12, 31).getTime();
myFeignClient.getResponse(date);
}
the request is sent into this format :
---> GET https:xxx/test?date=Wed%20Jan%2031%2000%3A00%3A00%20EST%202001
What I'm trying to have is :
---> GET https:xxx/test?date=2000-12-31
Where the date is formatter as I need.
I've tried also this solution, but not working neither:
class DateFormatConfiguration {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
#Bean
public JacksonEncoder feignEncoder() {
return new JacksonEncoder(customObjectMapper());
}
#Bean
public JacksonDecoder feignDecoder() {
return new JacksonDecoder(customObjectMapper());
}
private ObjectMapper customObjectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(df);
return objectMapper;
}
}
Any Ideas ?
You should consider trying replace necessary lines with something like this:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date= LocalDate.ofInstant(new GregorianCalendar(2000, 12, 31).getTime().toInstant(), ZoneId.of(TimeZone.getDefault().getID()));
String dateFormatted = date.format(dtf);

PayPal REST API returns INVALID_CURRENCY_AMOUNT_FORMAT

response-code: 400 details: name: VALIDATION_ERROR message: Invalid request - see details details: [{
"field": "transactions.amount",
"issue": "Cannot construct instance of com.paypal.platform.payments.model.rest.common.Amount, >problem: INVALID_CURRENCY_AMOUNT_FORMAT"
}] debug-id: 86ad5783892c3 information-link: https://developer.paypal.com/docs/api/payments/#errors
package com.spring.soap.api;
#Configuration
public class PaypalConfig {
#Value("${paypal.client.id}")
private String clientId;
#Value("${paypal.client.secret}")
private String clientSecret;
#Value("${paypal.mode}")
private String mode;
#Bean
public Map<String,String> paypalSdkConfig(){
Map<String,String> configMap= new HashMap<>();
configMap.put("mode",mode);
return configMap;
}
#Bean
public OAuthTokenCredential oAuthTokenCredential() {
return new OAuthTokenCredential(clientId,clientSecret,paypalSdkConfig());
}
#Bean
public APIContext apiContext() throws PayPalRESTException {
APIContext context = new APIContext(oAuthTokenCredential().getAccessToken());
context.setConfigurationMap(paypalSdkConfig());
return context;
}
}
{
#Autowired
PaypalService service;
public static final String SUCCESS_URL = "pay/success";
public static final String CANCEL_URL = "pay/cancel";
#GetMapping("/")
public String home() {
return "home";
}
#PostMapping("/pay")
public String payment(#ModelAttribute("order") Order order) {
try {
Payment payment = service.createPayment(order.getPrice(), order.getCurrency(), order.getMethod(),
order.getIntent(), order.getDescription(), "http://localhost:9090/" + CANCEL_URL,
"http://localhost:9090/" + SUCCESS_URL);
for(Links link:payment.getLinks()) {
if(link.getRel().equals("approval_url")) {
return "redirect:"+link.getHref();
}
}
} catch (PayPalRESTException e) {
e.printStackTrace();
}
return "redirect:/";
}
#GetMapping(value = CANCEL_URL)
public String cancelPay() {
return "cancel";
}
#GetMapping(value = SUCCESS_URL)
public String successPay(#RequestParam("paymentId") String paymentId, #RequestParam("PayerID") String payerId) {
try {
Payment payment = service.executePayment(paymentId, payerId);
System.out.println(payment.toJSON());
if (payment.getState().equals("approved")) {
return "success";
}
} catch (PayPalRESTException e) {
System.out.println(e.getMessage());
}
return "redirect:/";
}
}
{
#Autowired
private APIContext apiContext;
public Payment createPayment(
Double total,
String currency,
String method,
String intent,
String description,
String cancelUrl,
String successUrl) throws PayPalRESTException{
Amount amount = new Amount();
amount.setCurrency(currency);
total = new BigDecimal(total).setScale(2, RoundingMode.HALF_UP).doubleValue();
amount.setTotal(String.format("%.2f", total));
Transaction transaction = new Transaction();
transaction.setDescription(description);
transaction.setAmount(amount);
List<Transaction> transactions = new ArrayList<>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod(method);
Payment payment = new Payment();
payment.setIntent(intent);
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl(cancelUrl);
redirectUrls.setReturnUrl(successUrl);
payment.setRedirectUrls(redirectUrls);
return payment.create(apiContext);
}
public Payment executePayment(String paymentId, String payerId) throws PayPalRESTException{
Payment payment = new Payment();
payment.setId(paymentId);
PaymentExecution paymentExecute = new PaymentExecution();
paymentExecute.setPayerId(payerId);
return payment.execute(apiContext, paymentExecute);
}
}
It would appear your locale is formatting decimals with a comma (,) as the decimal separator.
The PayPal API exclusively accepts numbers with a period (.) as the decimal separator
Take this line:
amount.setTotal(String.format("%.2f", total));
Change %.2f to %.3f. The final code should look like:
amount.setTotal(String.format("%.3f", total));
In my case I was sending the SubTotal on Details with a NON rounded value:
141.750
So I just round the value like this:
details.setSubtotal(subTotal.setScale(2, BigDecimal.ROUND_HALF_EVEN).toString());
(In other words)
141.75

How to list data from database in a web page in spring framework

I have created a database called student base on the tutorial provided by tutorials point PDF, they have covered how to map the form and insert values in to the database using controllers, but they have not explained how to display the data from the database on to the webpage.
My code to list all students.
#Override
public List<Student> listStudents() {
String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
How to call this from my controller in spring and return the list to my webpage.
My contoller is given below
#Controller
public class StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student()
{
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Student student, ModelMap model)
{
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
studentJDBCTemplate.create(student.getName(), student.getAge());
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("msg", "Student Enrolled");
return "result";
}
// How to write the listing controller?
}
From the details you provide ,
public String ListStudents(ModelMap model)
{
List<Student> list= YourServiceClassObj.listStudents();
model.addAttribute("result", list);
return "View Name here";
}
public class AccountDAO {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public Account getAll(String user, String pass) {
String query = "SELECT * FROM dbo.USERR WHERE username=? AND password =?";
try {
conn = new DBContext().getConnection();
ps = conn.prepareStatement(query);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
while (rs.next()) {
return new Account(rs.getString(1),
rs.getString(2),
rs.getString(3));
}
} catch (Exception e) {
}
return null;
}
}
your controller and service methods should be like this .and then in the view use the controller returned attribute students.
#Controller
#RequestMapping(value = "/students", method = RequestMethod.GET)
public String students(ModelMap model)
{
List<Student> students= studentService.getStudents();
model.addAttribute("students", students);
return "student/studentList.html";
}
Service :
public interface StudentService {
List<Student> getStudents();
}
#Service
public class StudentServiceImpl implements StudentService {
#Override
public List<Student> getStudents() {
return studentRepository.findAll();
}

how does we enhance presistent class

AS I am new to JDO and datastore
I have set up a simple Google App Engine project based on Spring Framework to Perform Basic CRUD operation.
When I run my Application Its Show's
Persistent class "Class com.pandian.model.Customer does not seem to have been enhanced. You may want to rerun the enhancer and check for errors in the output." has no table in the database, but the operation requires it. Please check the specification of the MetaData for this class.
Customer
#PersistenceCapable
public class Customer {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private String name;
#Persistent
private String email;
#Persistent
private Date date;
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Customer() {
super();
}
Controller
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAddCustomerPage(ModelMap model) {
return "add";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView add(HttpServletRequest request, ModelMap model) {
String name = request.getParameter("name");
String email = request.getParameter("email");
Customer c = new Customer();
c.setName(name);
c.setEmail(email);
c.setDate(new Date());
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(c);
} finally {
pm.close();
}
return new ModelAndView("redirect:list");
}
#RequestMapping(value = "/update/{name}", method = RequestMethod.GET)
public String getUpdateCustomerPage(#PathVariable String name,
HttpServletRequest request, ModelMap model) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query q = pm.newQuery(Customer.class);
q.setFilter("name == nameParameter");
q.setOrdering("date desc");
q.declareParameters("String nameParameter");
try {
#SuppressWarnings("unchecked")
List<Customer> results = (List<Customer>) q.execute(name);
if (results.isEmpty()) {
model.addAttribute("customer", null);
} else {
model.addAttribute("customer", results.get(0));
}
} finally {
q.closeAll();
pm.close();
}
return "update";
}
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(HttpServletRequest request, ModelMap model) {
String name = request.getParameter("name");
String email = request.getParameter("email");
String key = request.getParameter("key");
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Customer c = pm.getObjectById(Customer.class, key);
c.setName(name);
c.setEmail(email);
c.setDate(new Date());
} finally {
pm.close();
}
// return to list
return new ModelAndView("redirect:list");
}
#RequestMapping(value = "/delete/{key}", method = RequestMethod.GET)
public ModelAndView delete(#PathVariable String key,
HttpServletRequest request, ModelMap model) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Customer c = pm.getObjectById(Customer.class, key);
pm.deletePersistent(c);
} finally {
pm.close();
}
PMF
public final class PMF {
private static final PersistenceManagerFactory pmfInstance = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
private PMF() {
}
list//JSP
....
<%
if(request.getAttribute("customerList")!=null){
List<Customer> customers =
(List<Customer>)request.getAttribute("customerList");
if(!customers.isEmpty()){
for(Customer c : customers){
%>
<tr>
<td><%=c.getName() %></td>
<td><%=c.getEmail() %></td>
...
Any body help me out from this.....
When you looked at the AppEngine docs for using JDO, you would have come across
https://developers.google.com/eclipse/docs/appengine_orm
This tells you HOW to enhance classes for use with JDO.

Resources