spring boot crud api receive 404 error from post request: postman - java

I am working on the CRUD rest API and application is turning on but when I'm trying to make a post request there is a: "status": 404, "error": "Not Found". On the postman, I also add header content-type: application/JSON and requesting at URL: http://localhost:8080/tickets.
Do you know guys how to fix this?
Here is the code.
model:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table
public class Tickets {
#Id
#Column
private int ticketid;
#Column
private String title;
#Column
private String description;
#Column
private String creationDate;
#Column
private String severity;
#Column
private String status;
public int getTicketid() {
return ticketid;
}
public void setTicketid(int ticketid) {
this.ticketid = ticketid;
}
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 String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
controller:
import com.cisco.interview.model.Tickets;
import com.cisco.interview.service.TicketsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class TicketsController {
#Autowired
TicketsService ticketsService;
#GetMapping("/ticket")
private List<Tickets> getAllTickets() {
return ticketsService.getAllTickets();
}
#GetMapping("/ticket/{ticketid}")
private Tickets getTicket(#PathVariable("ticketid")int ticketid) {
return ticketsService.getTicketsById(ticketid);
}
#DeleteMapping("/ticket/{ticketid}")
private void deleteTicket(#PathVariable("ticketid")int ticketid) {
ticketsService.deleteTicket(ticketid);
}
#PostMapping(value = "/tickets")
private int saveTicket(#RequestBody Tickets tickets) {
ticketsService.saveUpdateTicket(tickets);
return tickets.getTicketid();
}
#PutMapping("/tickets")
private Tickets updateTicket(#RequestBody Tickets tickets) {
ticketsService.saveUpdateTicket(tickets);
return tickets;
}
}
service:
import com.cisco.interview.model.Tickets;
import com.cisco.interview.repository.TicketsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class TicketsService {
#Autowired
TicketsRepository ticketsRepository;
public List<Tickets> getAllTickets() {
List<Tickets> tickets = new ArrayList<Tickets>();
ticketsRepository.findAll().forEach(tickets1 -> tickets.add(tickets1));
return tickets;
}
public Tickets getTicketsById(int id) {
return ticketsRepository.findById(id).get();
}
public void saveUpdateTicket(Tickets tickets) {
ticketsRepository.save(tickets);
}
public void deleteTicket(int id) {
ticketsRepository.deleteById(id);
}
public void update(Tickets tickets, int ticketid) {
ticketsRepository.save(tickets);
}
}
repository:
import com.cisco.interview.model.Tickets;
import org.springframework.data.repository.CrudRepository;
public interface TicketsRepository extends CrudRepository<Tickets, Integer> {
}
im trying to make a post request at postman and getting 404 error

Have you specify the POST method in Postman ?
And the body of your request ?
Postam sample

Related

Return key value of a JSON request in Spring

I'm trying to create a route to perform a GET Request to /winner to show the restaurants that had the count of 3 votes in the JSON, but every time I do the GET, it returns the value of null instead of the value I would like.
I was expecting something like that:
{
"id": 1,
"restaurant": "Burger King",
"address": "Av. Ipiranga, 1600",
"website": "https://www.burgerking.com.br/",
"description": "Rede de fast-food famosa com hambúrgueres grelhados, batata frita e milk-shakes.",
"count": 3
}
Instead that, I'm just getting an empty JSON with the null value.
Here are the classes I'm using:
Restaurant.java
package com.dbserver.restaurantes.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "db_restaurants")
public class Restaurant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
#OneToMany(mappedBy = "id.restaurant")
private Set<Vote> votes = new HashSet<>();
public Restaurant() {
}
public Restaurant(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Set<Vote> getVotes() {
return votes;
}
}
RestaurantDTO.java
package com.dbserver.restaurantes.dto;
import com.dbserver.restaurantes.entities.Restaurant;
public class RestaurantDTO {
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
public RestaurantDTO() {
}
public RestaurantDTO(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public RestaurantDTO(Restaurant restaurantDTO) {
id = restaurantDTO.getId();
restaurant = restaurantDTO.getRestaurant();
address = restaurantDTO.getAddress();
website = restaurantDTO.getWebsite();
description = restaurantDTO.getDescription();
count = restaurantDTO.getCount();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
RestaurantServices.java
package com.dbserver.restaurantes.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.dto.VoteDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.repositories.RestaurantRepository;
#Service
public class RestaurantServices {
#Autowired
private RestaurantRepository repository;
#Transactional(readOnly = true)
public Page<RestaurantDTO> findAll(Pageable pageable) {
Page<Restaurant> result = repository.findAll(pageable);
Page<RestaurantDTO> page = result.map(x -> new RestaurantDTO(x));
return page;
}
#Transactional(readOnly = true)
public RestaurantDTO findById(Long id) {
Restaurant result = repository.findById(id).get();
RestaurantDTO dto = new RestaurantDTO(result);
return dto;
}
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = new ArrayList<>();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}
#Transactional
public Restaurant addRestaurant(Restaurant newRestaurant) {
return repository.saveAndFlush(newRestaurant);
}
}
RestaurantController.java
package com.dbserver.restaurantes.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.services.RestaurantServices;
#RestController
#RequestMapping(value = "/restaurants")
public class RestaurantController {
#Autowired
private RestaurantServices service;
#GetMapping
public Page<RestaurantDTO> findAll(Pageable pageable) {
return service.findAll(pageable);
}
#GetMapping(value = "/{id}")
public RestaurantDTO findById(#PathVariable Long id) {
return service.findById(id);
}
#SuppressWarnings("unchecked")
#GetMapping(value = "/winner")
public List<RestaurantDTO> findWinner(Integer count) {
return (List<RestaurantDTO>) service.findWinner(3);
};
#PostMapping
public Restaurant addRestaurant(#RequestBody Restaurant newRestaurant) {
return service.addRestaurant(newRestaurant);
}
}
you didn't access dao in the method findWinner.
restaurants instance has just created without accessing dao.
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = new ArrayList<>();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}
because in the find winner method you have initialized restaurants with an empty array list.
It should be like this.
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = repository.findAll();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}

Getting null value in db when using #embbeded in Spring boot Rest api? new to java help me out guys

Getting null values in database for the embedded Address entity. Using MySql database. The user entity is storing values fine but embedded Address entity is returning null value, can't figure out why it's not working. help me out guys.I am a beginner tried searching everywhere but no luck. Just a novice Api but it won't work the way i want it's really annoying.
Model class
package com.example.demo;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class User {
#Id
private int id;
private String name;
#Embedded
private Address address;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String toString() {
return "user [id=" + id + ", name=" + name + ",Address="+address+" ]";
}
public User(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
---------------------------------------------------------------------------------------------------------
**Model class**
package com.example.demo;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String cityname;
private String streetname;
private String Housename;
public Address() {
}
public Address(String cityname, String streetname, String housename) {
super();
this.cityname = cityname;
this.streetname = streetname;
Housename = housename;
}
public String getStreetname() {
return streetname;
}
public void setStreetname(String streetname) {
this.streetname = streetname;
}
public String getHousename() {
return Housename;
}
public void setHousename(String housename) {
Housename = housename;
}
public String getCityname() {
return cityname;
}
public void setCityname(String cityname) {
this.cityname = cityname;
}
}
---------------------------------------------------------------------------------------------------------
**controller class**
package com.example.demo;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class Croller {
#Autowired
TestRepo repo;
#PostMapping("/add")
public String save(#RequestBody User mode) {
repo.save(mode);
return "details saved";
}
#GetMapping("/get")
public List<User> retrive(){
return repo.findAll();
}
#GetMapping("/search")
public List<User> searchname(#RequestParam("name")String name){
return repo.name(name);
}
#GetMapping("/byid/{id}")
public Optional <User> getone (#PathVariable int id){
return repo.findById(id);
}
#PutMapping("/update")
public String updateid(#RequestBody User mode ) {
repo.save(mode);
return " user updated sucessfully";
}
#DeleteMapping("/remove/{id}")
public String delete(#PathVariable int id) {
repo.deleteById(id);
return "deleted with the given id:"+ id;
}
}
---------------------------------------------------------------------------------------------------------
Repository
package com.example.demo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepo extends JpaRepository <User, Integer> {
List <User> name(String name);
}
**Application.java**
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Demoapi2Application {
public static void main(String[] args) {
SpringApplication.run(Demoapi2Application.class, args);
}
}
Your request has to match the #RequestBody object for spring to map the keys appropriately
Try this request -
{
"id":19,
"name":"Alex",
"address":{
"cityname":"california",
"streetname":"ring road",
"Housename":"Housename"
}
}
Please make sure you give input as per your Model.

model mapper mapping errors

> PurchaseOrderHeaderDto
package com.assignment.dto;
import java.util.List;
import com.assignment.entity.PurchaseItem;
public class PurchaseOrderHeaderDto{
private List<PurchaseItem> itemList;
public List<PurchaseItem> getItemList() {
return itemList;
}
public void setItemList(List<PurchaseItem> itemList) {
this.itemList = itemList;
}
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getPaymentterms() {
return paymentterms;
}
public void setPaymentterms(String paymentterms) {
this.paymentterms = paymentterms;
}
public String getCompanycode() {
return companycode;
}
public void setCompanycode(String companycode) {
this.companycode = companycode;
}
private int ponumber;
private String vendor;
private String paymentterms;
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
private String companycode;
}
above is the code for the DTO class
> PurchaseOrderHeader
package com.assignment.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import com.fasterxml.jackson.annotation.JsonBackReference;
#Entity
#Table(name="PurchaseOrderHeader")
/*#FilterDef(name ="poFilter", parameters =#ParamDef(name ="ponumber", type ="int"))
#Filter(name ="poFilter", condition ="ponumber>=:ponumber")
*/
public class PurchaseOrderHeader implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2293787550626038248L;
#Id
#GenericGenerator(name = "generator", strategy = "increment")
#GeneratedValue(generator = "generator")
#Column(name="ponumber")
private int ponumber;
#JsonBackReference
#OneToMany( fetch = FetchType.EAGER,mappedBy = "purchaseorder",cascade = CascadeType.ALL)
private List<PurchaseItem> itemList;
public List<PurchaseItem> getItemList() {
return itemList;
}
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public void setItemList(List<PurchaseItem> itemList) {
this.itemList = itemList;
}
public Integer getCompanycode() {
return companycode;
}
public void setCompanycode(Integer companycode)
{
this.companycode = companycode;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getPaymentterms() {
return paymentterms;
}
public void setPaymentterms(String paymentterms) {
this.paymentterms = paymentterms;
}
#Column(name="companycode")
private Integer companycode;
#Column(name="status")
private String status;
#Column(name="vendor")
private String vendor;
#Column(name="paymentterms")
private String paymentterms;
public PurchaseOrderHeader() {
}
public PurchaseOrderHeader(int ponumber, Integer companycode, String status, String vendor, String paymentterms) {
this.ponumber = ponumber;
this.companycode = companycode;
this.status = status;
this.vendor = vendor;
this.paymentterms = paymentterms;
}
}
above is the code for the DO class
model mapper mapping errors ,Unable to convert String to Integer
DTO class has company code as String and the DO class has the company code
as Integer type when data is passed in json if string value is passed
for company code it should throw 400 bad request error in postman.
NumberFormatException on passing data in postman.
Mysql database used for db transactions.
SEVERE: Servlet.service() for servlet [spring] in context with path [/Pro] threw exception [Request processing failed; nested exception is org.modelmapper.MappingException: ModelMapper mapping errors:
1) Converter org.modelmapper.internal.converter.NumberConverter#6279a752 failed to convert java.lang.String to java.lang.Integer.
1 error] with root cause
java.lang.NumberFormatException: For input string: "asdfghertyu"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

spring 5 does not create method findByFieldName that supports Pageable

I am trying to use the findByFieldName generated methods in the repository interface. I am getting this error at compile time:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property source found for type Article!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77) ~[spring-data-commons-1.13.8.RELEASE.jar:na]
My Article model looks like this:
package com.infostream.models;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "articles")
public class Article extends Base {
private String ref_id;
public String getRef_id() {
return ref_id;
}
public void setRef_id(String ref_id) {
this.ref_id = ref_id;
}
public Article() {
}
public Article(String source_id, String ref_id, String title, String subject, String description, String url) {
this.source_id = source_id;
this.ref_id = ref_id;
this.title = title;
this.subject = subject;
this.description = description;
this.url = url;
}
public String getSource_id() {
return source_id;
}
public void setSource_id(String source_id) {
this.source_id = source_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#NotNull
private String source_id;
#NotNull
private String title;
private String subject;
private String description;
#NotNull
private String url;
}
My interface which defined the findByFieldName looks like this:
package com.infostream.repositories;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.infostream.models.Article;
import java.lang.String;
public interface ArticleRepositoryImpl extends PagingAndSortingRepository<Article, Long> {
Page<Article> findAll(Pageable pageRequest);
Page<Article> findBySource_id(String source_id, Pageable pageable);
}
As you can see in the model above, source_id is defined in the model.
On my main class that runs the application, i have defined the place for the jpa repositories.
package com.infostream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories("com.infostream.repositories")
public class InfoStreamSpringBootApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(InfoStreamSpringBootApplication.class, args);
}
}
Does anyone have a source example of how they achieve this?

Unable to fetch json object and array in Retrofit 2

I'm trying to parse the json from the api http://badiyajobs.com/apis/v1/rolesbut response.isSuccess is returning false
my modal class is,
package arpit.retrodemo;
import java.util.List;
import java.util.ArrayList;
public class Modal {
private List<RolesEntity> roles = new ArrayList<>();
public void setRoles(List<RolesEntity> roles) {
this.roles = roles;
}
public List<RolesEntity> getRoles() {
return roles;
}
public static class RolesEntity {
private String id;
private String role;
private String description;
private String icon_url;
private String created_at;
private String updated_at;
public void setId(String id) {
this.id = id;
}
public void setRole(String role) {
this.role = role;
}
public void setDescription(String description) {
this.description = description;
}
public void setIcon_url(String icon_url) {
this.icon_url = icon_url;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public String getId() {
return id;
}
public String getRole() {
return role;
}
public String getDescription() {
return description;
}
public String getIcon_url() {
return icon_url;
}
public String getCreated_at() {
return created_at;
}
public String getUpdated_at() {
return updated_at;
}
}
}
Sample json is,
{"roles":[
{
"id":"1",
"role":"Retail Sales Executive",
"description":"As a sales assistant....",
"icon_url":"",
"created_at":"2015-10-02 12:03:03",
"updated_at":null
}
]
}
APIService.java is,
package arpit.retrodemo;
import retrofit.Call;
import retrofit.http.GET;
public interface APIService {
#GET("/roles")
Call<Modal> getDetails();
}
MainActivity.java is,
package arpit.retrodemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;
public class MainActivity extends AppCompatActivity {
private static final String ENDPOINT = "http://badiyajobs.com/apis/v1";
private APIService service;
private Modal mod;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ENDPOINT)
.build();
service = retrofit.create(APIService.class);
Call<Modal> userList = service.getDetails();
userList.enqueue(new Callback<Modal>() {
#Override
public void onResponse(Response<Modal> response) {
if(response.isSuccess()){
Log.d("findRes", response.body().toString());
}else{
Log.d("find", "Something is wrong! " + response.errorBody().toString());
}
}
#Override
public void onFailure(Throwable t) {
Log.d("findError", t.getMessage());
}
});
}
}
Here i'm getting the following on logcat,
D/find: Something is wrong! com.squareup.okhttp.ResponseBody$1#52715c98
instead of the string representation of response.body()
You need to do the following:
public interface APIService {
#GET("roles") /*removed the / here */
Call<Modal> getDetails();
}
private static final String ENDPOINT = "http://badiyajobs.com/apis/v1/"; /* added the / here */

Categories

Resources