0

Is it a way to extract and use values from a POST body before ending the Post method?

POST body:

{
    "proposalId": 124,
    "type": "credit",
    "customerId": "1001"
}

I want to check if the customerId already exists in the DB and if only exists to save the entity.

/*---Add new proposal---*/
   @PostMapping(value="/proposal", produces = "application/json", consumes = "application/json")
   @ResponseBody
   public ResponseEntity<?> saveProposal(HttpServletRequest request,
           HttpServletResponse response,@RequestBody Proposal proposal ) {
         String jsonString  = request.getParameter("customerId");
         System.out.println(jsonString);
       // Long  jsonLong = Long.valueOf(jsonString);
       long id = 0;


      //Customer checkCustomer = customerService.showCustomer(jsonLong);
     // System.out.println(checkCustomer);

      // if(checkCustomer!=null)

        //id = proposalService.save(proposal);
        return ResponseEntity.ok().body("New Proposal has been saved with ID:" + id);

   }

I have tried different approach, but I am getting always a null value. Any sugestion will be good, and of course if I can write this in a more stylish way, I will be glad to learn. Thank you!

Edit:

Proposal class:

package model;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;


import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@Table(name= "PROPOSAL")
@JsonIgnoreProperties(ignoreUnknown = false)

public class Proposal {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long proposalId;
    private String type;


    @ManyToOne(optional = false, cascade = CascadeType.MERGE, fetch=FetchType.EAGER)
    @JoinColumn(name="customerId")
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }


    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public Long getProposalId() {
        return proposalId;
    }

    public void setProposalId(Long proposalId) {
        this.proposalId = proposalId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }


    @Override
    public String toString() {
        return "Proposal [proposalId=" + proposalId + ", type=" + type + ", customer=" + customer + "]";
    }

}

Customer class

package model;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name= "CUSTOMER")
public class Customer {
       @Id
       @GeneratedValue(strategy = GenerationType.IDENTITY)

       private Long customerId;
       private String heading;
        private int ndg;
        private Date birthdate;
        private String name;
        private String surname;

       // @OneToMany(mappedBy="customer", cascade = CascadeType.ALL,  fetch=FetchType.LAZY)
       /* private List<Proposal> proposal;

         public List<Proposal> getProposal() {
            return proposal;
        }
        public void setProposal(List<Proposal> proposal) {
            this.proposal = proposal;
        }*/


        public Long getUserId() {
            return customerId;
        }
        public void setUserId(Long customerId) {
            this.customerId = customerId;
        }
        public String getHeading() {
            return heading;
        }
        public void setHeading(String heading) {
            this.heading = heading;
        }
        public int getNdg() {
            return ndg;
        }
        public void setNdg(int ndg) {
            this.ndg = ndg;
        }
        public Date getBirthdate() {
            return birthdate;
        }
        public void setBirthdate(Date birthdate) {
            this.birthdate = birthdate;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getSurname() {
            return surname;
        }
        public void setSurname(String surname) {
            this.surname = surname;
        }
}
SimonaC
  • 29
  • 1
  • 2
  • 10

1 Answers1

0

You don't need to manually parse the body when you already have everything you need in your porposal object. The @RequestBody annotation bounds the request body to the parameter. So you can use the following code:

   @PostMapping(value="/proposal", produces = "application/json", consumes = "application/json")
   @ResponseBody
   public ResponseEntity<?> saveProposal(HttpServletRequest request,
           HttpServletResponse response,@RequestBody Proposal proposal ) {

       long customerId = proposal.getCustomer().getUserId();
       Customer checkCustomer = customerService.showCustomer(customerId );

       if(checkCustomer!=null) {
           proposalService.save(proposal);
           return ResponseEntity.ok().body("New Proposal has been saved with ID:" + proposal.getProposalId());
       } else {
           return ResponseEntity.ok(); //change return to your liking
       }
   }

Edit: The Json does not represent the Porposal structure. The Customer in the Proposal is an Object and as such it needs to be an object in the Json aswell.

{
    "proposalId": 124,
    "type": "credit",
    "customer": {
        "customerId": "1001",
        "name": "Jon",
        "surname": "Do"
    }
}
Tom
  • 977
  • 11
  • 18
  • Thank you a lot! It makes sense. After I modify the code, I am receiving a 500 Internal Server Error. java.lang.NullPointerException controller.UserController.saveProposal(UserController.java:94) – SimonaC Apr 17 '18 at 11:19
  • @SimonaC you have to look into your UserController line 94 to pinpoint the NullPointer. Maybe the link can help you : https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – Tom Apr 17 '18 at 12:00
  • I managed to figure out that the "customerId": "1001" is not readable from the Java class. If i try to print all the values from the POST ( System.out.println(proposal.getProposalId()); System.out.println(proposal.getType()); System.out.println(proposal.getCustomer());), I get in the console the following result: 124 credit null. So, the customer is null. What I am doing wrong here? – SimonaC Apr 17 '18 at 12:02
  • I think I figured out. It was my mistake. I was sending the wrong body (I needed to include all customer information, not only the customerId). Thanks a lot! – SimonaC Apr 17 '18 at 12:25