While testing api in postman getting error 404 - spring-boot

Model Class
public class SimpleResponse {
private String message;
private long id;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
Controller class
#RestController
public class WebController {
// #RequestParam indicates that the endpoint /sample will have one Query
// parameter called name.
#RequestMapping("/sample")
public SimpleResponse sample(#RequestParam(value = "name", defaultValue = "Kabir") String name) {
SimpleResponse sm = new SimpleResponse();
sm.setId(1);
sm.setMessage("This message is for Kabir"+name);
return sm;
}
}
While developing a Spring Boot Rest Api i am geeting 404 error.Unable to find the Error.Can anyone help me to resolve this issue?

Above code works fine, did you check your application logs?

Check whether if your application.properties file contains a property as server.servlet.context-path. If it does, then append that to your URL after the domain.
http://localhost:8888/<append_here>/sample?name=Kabir

Related

Printing Json data that is in array using rest template in SpringBoot

#Component
public class JsonData {
#JsonProperty("id")
private Integer id;
#JsonProperty("createdAt")
private Date cratedAt;
#JsonProperty("name")
private String name;
#JsonProperty("email")
private String email;
#JsonProperty("imageUrl")
private String url;
public JsonData() {
}
public JsonData(Integer id, Date cratedAt, String name, String email, String url) {
this.id = id;
this.cratedAt = cratedAt;
this.name = name;
this.email = email;
this.url = url;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getCratedAt() {
return cratedAt;
}
public void setCratedAt(Date cratedAt) {
this.cratedAt = cratedAt;
}
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 String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Controller
#RestController
public class JsonDataController {
#RequestMapping(value = "/template/products")
public void getAllData() {
RestTemplate template = new RestTemplate();
String url = "https://5ef99e4bbc5f8f0016c66d42.mockapi.io/testing/data";
ResponseEntity < JsonData[] > response = template.exchange(url, JsonData[].class);
for (JsonData jsonData: response.getBody()) {
System.out.println(jsonData.getName());
System.out.println(jsonData.getEmail());
}
}
}
I am trying to print json data that is array using rest template but I am getting error in this line "ResponseEntity < JsonData[] > response = template.exchange(url, JsonData[].class);" my error is "cannot resolve method" Can anyone tell me correct way of doing this .I am new to spring I do not have proper understanding it would be helpful if some one can give their suggeestion in this code
RestTemplate does not have any method with signature exchange(String, Class<T>).
That is why you are getting "cannot resolve method" error for template.exchange(url, JsonData[].class);.
Here is an example of correct usage of one of the methods from RestTemplate.exchange API:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<JsonData[]> response = restTemplate.exchange(url, HttpMethod.GET, null, JsonData[].class);
RestTemplate also has another method - getForEntity that makes a GET call with the given URL and expected return type. (without need for passing null for not required fields)
RestTemplate template = new RestTemplate();
String url = "https://5ef99e4bbc5f8f0016c66d42.mockapi.io/testing/data";
ResponseEntity <JsonData[]> response = template.getForEntity(url, JsonData[].class);

415--Unsupported Media Type in Spring

I am getting unsupported mediatype error.
My User Profile class looks like this
Class UserProfile{
private int age;
private String name,
private String currenecy;
}
And this is the method in controller
#RequestMapping(value = "/Create", method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserProfileResponse> createUserProfile(#RequestBody UserProfile userProfile)
{
UserProfileResponse userProfileResponse = new UserProfileResponse();
int id = createUserProfileData(userProfile)
userProfileResponse.setId(id);
return new ResponseEntity<UserProfileResponse>(userProfileResponse,HTTPStatus.OK);
}
I am trying to send the request through POSTMAN but getting
Error 415--Unsupported Media Type
My Request in POstman looks like this
Content-Type:application/json
Accept:application/json
Method is : POST
{
"age":28,
"name":"Sam",
"currency": "INR"
}
Suggest me what I am missing?
Don't forget to select "JSON" format, filled in arbitrary JSON string in the textarea.
Also use either Accept or Content-type at a time.
If that doesn't work then can you check like below by removing consumes and adding headers manually.
#RequestMapping(value = "/Create", method=RequestMethod.POST, headers = "Accept=application/json",produces=MediaType.APPLICATION_JSON_VALUE)
I could see the response coming back with your code. I am deliberately returning the same object just to test the connectivity. Following is my code:
#RequestMapping(value = "/create", method= RequestMethod.POST,consumes= MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<UserProfile> createUserProfile(#RequestBody UserProfile userProfile)
{
System.out.println("Got request");
return new ResponseEntity<>(userProfile, HttpStatus.OK);
}
Used getter and setter in UserProfile
public class UserProfile {
private int age;
private String name;
private String currenecy;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCurrenecy() {
return currenecy;
}
public void setCurrenecy(String currenecy) {
this.currenecy = currenecy;
}
}
Finally after after spending some time.. I figured out why it was not working.
In my java based spring configuration file I missed "#EnableWebMvc".
After adding it, my problem got resolved.
#Configuration
**#EnableWebMvc** // This annotation was missing.
#ComponentScan(basePackages="com.hemant.*")
public class TestConfiguration {}

Spring Data JPA JpaRepository only uses No Arg Constructor

I have this simple REST API that i created with Spring Boot.
In this app, I have a a POJO called Expense with 4 fields. I have a no Argument constructor and another constructor that takes only two inputs. One String value "item" and one Integer value "amount". The date is set using the LocalData.now() method and the id is set automatically in a MySql db running in the server.
Here's my Entity class
#Entity
public class Expense {
#Id
#GeneratedValue (strategy = GenerationType.AUTO)
private Integer id;
private String date;
private String item;
private Integer amount;
//No Arg Construction required by JPA
public Expense() {
}
public Expense(String item, Integer amount) {
this.date = LocalDate.now().toString();
this.item = item;
this.amount = amount;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
}
I have another class with RestController annotation where i have set a method to post Expense object with a post method using Request Mapping annotation.
#RestController
public class ExpController {
private ExpService expService;
private ExpenseRepo expenseRepo;
#Autowired
public ExpController(ExpService expService, ExpenseRepo expenseRepo) {
this.expService = expService;
this.expenseRepo = expenseRepo;
}
#RequestMapping(path = "/addExp", method=RequestMethod.POST)
public void addExp(Expense expense){
expenseRepo.save(expense);
}
}
Now finally i am using PostMan to make the HTTP Post Request. I have made a simple Json Format text to send Item and Amount
{
"item":"Bread",
"amount": 75
}
After I make the post request, all i can see is that a new Entry is created but all values are set to null.
I have done some experimentation and found out that the expenseRepo.save(expense) method is only using the default no Arg constructor to save the data. But it's not using the second constructor that takes the two parameters that I am passing through Postman
How to solve this issue. Please help
Change your controller method like this
#RequestMapping(path = "/addExp", method=RequestMethod.POST)
public void addExp(#RequestBody Expense expense){
expenseRepo.save(expense);
}
You need to use #RequestBody

Getting 415 unsupported media type while consuming an api which I created

#RequestMapping(value="/sam", method=RequestMethod.POST, consumes = {"text/plain", "application/*"})
public void test(HttpServletRequest request, HttpServletResponse response, #RequestBody Test test) {
try {System.out.println("*******************inside**************************");
} catch(Exception exception) {
exception.printStackTrace();
}
}
public class Test {
private String desc;
private int id;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Request body I used is
{
"id": 88,
"desc":"test"
}
Even though I have added consumes in request mapping I'm getting 415 when I try to access from postman and also I have set the request header in postman, content-type as application/json
I missed the json converter library, so when I added jackson-databind maven dependency in my pom.xml it worked.

org.axonframework.eventsourcing.IncompatibleAggregateException (Axon framework: Aggregate identifier must be non-null after applying an event)

I try to config cqrs and event sourcing with axon.
SeatReseveCreateCommand is work properly. but SeatReserveUpadateCommand is not work correct.
this is my SeatReserve aggregate
#Aggregate
public class SeatReserve {
#AggregateIdentifier
private String id;
private String seatid;
private Date date;
#SuppressWarnings("unused")
private SeatReserve() {
}
#CommandHandler
public SeatReserve(SeatReseveCreateCommand seatReseveCreateCommand) {
apply(new SeatReseveCreateEvent(seatReseveCreateCommand.getMyid(), seatReseveCreateCommand.getSeatId(),
seatReseveCreateCommand.getDate()));
}
#CommandHandler
public SeatReserve(SeatReserveUpadateCommand upadateCommand) {
apply(new SeatReserveUpadateEvent(id, upadateCommand.getSeatId()));
}
#EventSourcingHandler
public void on(SeatReseveCreateEvent seatReseveCreateEvent) {
this.id = seatReseveCreateEvent.getId();
this.seatid = seatReseveCreateEvent.getSeatId();
this.date = seatReseveCreateEvent.getDate();
}
#EventSourcingHandler
public void on(SeatReserveChangeEvent upadateEvent) {
seatid = upadateEvent.getSeatId();
}
}
this is my controller
#RestController
public class TestController {
private final CommandGateway commandGateway;
public TestController(CommandGateway commandGateway) {
this.commandGateway=commandGateway;
}
#PostMapping
public String fileComplaint(#RequestBody Map<String, String> request) {
String id = UUID.randomUUID().toString();
SeatReseveCreateCommand command=new SeatReseveCreateCommand(id,request.get("seatid"),new Date(request.get("date")));
commandGateway.send(command);
return id;
}
#PatchMapping
public String fileComplaintUpdate(#RequestBody Map<String, String> request) {
SeatReserveUpadateCommand command= new SeatReserveUpadateCommand(request.get("id"),request.get("seatid"));
commandGateway.send(command);
return request.get("id");
}
}
I try to send request using postman
this is my create request
this is my update request
update make this error
2018-01-03 10:44:53.608 WARN 11138 --- [nio-8085-exec-1] o.a.c.gateway.DefaultCommandGateway : Command 'com.thamira.research.api.bankaccount.SeatReserveUpadateCommand' resulted in org.axonframework.eventsourcing.IncompatibleAggregateException(Aggregate identifier must be non-null after applying an event. Make sure the aggregate identifier is initialized at the latest when handling the creation event.)
how can I solve this.
The problem is that your update command is defined as a constructor. The command should go to the already existing aggregate instance.
Changing the command handler to:
#CommandHandler
public void handle(SeatReserveUpadateCommand upadateCommand) {...}
should fix the issue.

Resources