My spring application isn't recognizing my webservice - java

My application is returning "[{},{}]" when I request asList. But when I request String it displays ok on browser.
Images: 1.IDE EndPoint 2.Browser Return
Endpoint
package br.com.devdojo.app.endpoint;
import br.com.devdojo.app.model.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static java.util.Arrays.asList;
#RestController
#RequestMapping("student")
public class StudentEndPoint {
#RequestMapping(method = RequestMethod.GET, path = ("/list"))
public List<Student> listAll(){
return asList(new Student("Aluno1"), new Student("Aluno2"));
}
}

Your Student class must be like below:
public class Student {
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Related

Generics with Java REST API

I have a problem in accessing get method of a generic class in REST API project. there are no errors but it returns null. here I mention the code. The idea working fine when I implemented without REST API. Insert and GetALL methods are working fine in REST API but problem is Repo class Get method couldn't work with REST.
package lk.ac.jfn.vau.DeptApi.Model;
public class Department extends PrimaryID<Long>{
private String Name;
private String Location;
public Department() {
//super();
}
public Department(long id, String name, String location) {
super(id);
Name = name;
Location = location;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
}
package lk.ac.jfn.vau.DeptApi.Model;
public class PrimaryID<U> {
private U Id;
public PrimaryID() {
}
public PrimaryID(U id) {
Id = id;
}
public U getId() {
return Id;
}
public void setId(U id) {
Id = id;
}
}
package lk.ac.jfn.vau.DeptApi.Repo;
import java.util.ArrayList;
import java.util.List;
import lk.ac.jfn.vau.DeptApi.Model.PrimaryID;
public class Repo<T extends PrimaryID<U>,U> {
List<T> list= new ArrayList<T>();
public List<T> getAll(){
return list;
}
public void insert(T obj) {
list.add(obj);
}
public T get(U id) {
for(T obj:list) {
//objects are there
System.out.println(obj);
//but getId returns null
if(obj.getId().equals(id)) {
return obj;
}
}
return null;
}
public void Delete(U id) {
list.remove(get(id));
}
public void Update(U id,T obj) {
list.set(list.indexOf(get(id)), obj);
}
}
package lk.ac.jfn.vau.DeptApi.Repo;
import lk.ac.jfn.vau.DeptApi.Model.Department;
public class DepartmentRepo extends Repo<Department, Long> {
}
package lk.ac.jfn.vau.DeptApi;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import lk.ac.jfn.vau.DeptApi.Model.Department;
import lk.ac.jfn.vau.DeptApi.Repo.DepartmentRepo;
#Path("/dept")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class DepartmentResource {
private static DepartmentRepo repo = new DepartmentRepo();
#GET
public List<Department> getDepartments() {
return repo.getAll();
}
#POST
public void addDepartment(Department department) {
repo.insert(department);
}
#GET
#Path("/{id}")
public Department getDepartment(#PathParam("id") long id) {
return repo.get(id);
}
#DELETE
#Path("/{id}")
public void deleteDepartment(#PathParam("id") long id) {
repo.Delete(id);
}
}
I found the problem. Problem is Object to JSON conversion. when I updated the JSON library it worked fine.
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>

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.

SpringBoot CRUD

I stuck with my Springboot Crud project and i need your helps.Problem is i want to use GET with my barcode string variable , and to DELETE and PUT using my id int variable but somehow i could not managed to DELETE and PUT with id variable and i stuck with this all the day. i will post my code and i will apriciate every help
Application.java
package com.javahelps.restservice;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.javahelps.restservice.entity.User;
import com.javahelps.restservice.repository.UserRepository;
import com.javahelps.restservice.repository.UserRepository2;
import com.javahelps.restservice.repository.UserRepository3;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Bean
protected CommandLineRunner init(final UserRepository userRepository , UserRepository2 userRepository2,UserRepository3 userRepository3) {
return null;
};
}
UserController.java
package com.javahelps.restservice.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties.Session;
import org.springframework.http.HttpStatus;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.javahelps.restservice.entity.User;
import com.javahelps.restservice.repository.UserRepository;
import com.javahelps.restservice.repository.UserRepository3;
import javassist.tools.web.BadHttpRequest;
#RestController
#RequestMapping(path = "/productnames")
public class UserController {
#Autowired
private UserRepository repository;
private UserRepository3 repository3;
#GetMapping
public Iterable<User> findAll() {
return repository.findAll();
}
#GetMapping(path = "/{barcode}")
public User find(#PathVariable("barcode") String barcode) {
return repository.findOne(barcode);
}
#PostMapping(consumes = "application/json")
public User create(#RequestBody User user) {
return repository.save(user);
}
#DeleteMapping(path = "/{barcode}")
public void delete(#PathVariable("barcode") String barcode) {
repository.delete(barcode);
}
#DeleteMapping(path = "1/{id}")
public void delete(#PathVariable("id") Integer id) {
repository.delete(id);
}
#PutMapping(path = "/{barcode}")
public User update(#PathVariable("barcode") String barcode, #RequestBody User user) throws BadHttpRequest {
if (repository.exists(barcode)) {
user.setBarcode(barcode);
return repository.save(user);
} else {
throw new BadHttpRequest();
}
}
}
UserRepository.java
package com.javahelps.restservice.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Repository;
import com.javahelps.restservice.entity.User;
#RestResource(exported = false)
#Repository
public interface UserRepository extends JpaRepository<User,String> {
}
User.java
package com.javahelps.restservice.entity;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="ProductNames")
public class User {
private int id;
#Id
private String barcode;
private String name;
private String category;
private int qty;
private Date dater;
private Date datel;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Date getDater() {
return dater;
}
public void setDater(Date dater) {
this.dater = dater;
}
public Date getDatel() {
return datel;
}
public void setDatel(Date datel) {
this.datel = datel;
}
#Override
public String toString() {
return "User{" + "='" +", id='"+ id + '\'' +", name='"+ barcode + '\'' + ", name='" + name + '\'' + ", category='" + category + '\''
+ ", qty='" + qty + '\'' + ", dater='" + dater + '\''+", datel='" + datel + '\'' +'}';
}
}
For delete based on id, since your primary key is not int id you have to write the below custom code in your interface extending JpaRepository.
And in your rest controller you have to invoke it like repository.deleteById(id);
#Repository
public interface UserRepository extends JpaRepository<User,String> {
#Modifying
#Transactional
#Query(value="delete from User u where u.id= ?1")
void deleteById(int id);
}
Similarly you may have to write code for your update statement as well (for PUT case).
Hope this helps.

Writing a Spring Boot application using an in-memory H2 Database

I am trying to create a in memory database in spring boot... Still learning about spring boot and databases. How would I create an in memory database for this.
I want to create an in memory database with 3 REST endpoints...
This is what I've done so far:
package com.jason.spring_boot;
/**
* The representational that holds all the fields
* and methods
* #author Jason Truter
*
*/
public class Employee {
private final long id;
private final String name;
private final String surname;
private final String gender;
public Employee(long id, String name, String surname, String gender){
this.id = id;
this.name = name;
this.surname = surname;
this.gender = gender;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getGender() {
return gender;
}
}
package com.jason.spring_boot;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* The resource controller handles requests
* #author Jason Truter
*
*/
#Controller
#RequestMapping("/employee")
public class EmployeeController {
private final AtomicLong counter = new AtomicLong();
/**
* GET method will request and return the resource
*/
#RequestMapping(method=RequestMethod.GET)
public #ResponseBody Employee getEmployee(#RequestParam(value = "name", defaultValue = "Stranger") String name,
String surname, String gender){
return new Employee(counter.getAndIncrement(), name, surname, gender);
}
}
package com.jason.spring_boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Spring rest web service controller not able to return List object

Thanks for looking into the issue i am facing and for your response.
Issue --> Spring rest controller not able to return List object.While making request from rest client browser extension I am not getting any errors but i can only see waiting animation icon and no response.I waited for few minutes then aborted the request,did this multiple time.Checked logs and based on it observed that response is coming till controller seems something to do with the return statement in controller.
Code as follows :-
Spring rest controller :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wells.exptrack.constants.Result;
import com.wells.exptrack.service.UserService;
#Controller
#RequestMapping(value="/rest/service")
public class EmployeeController {
#Autowired
UserService userService;
#RequestMapping(value="/get/all/News/user/{empId}", method=RequestMethod.GET,consumes = {"application/json"}, produces = "application/json")
public #ResponseBody Result getAllNews(#PathVariable("empId") int eId) {
return userService.getAllNews(eId);
} }
service class as follows:
#Override
#Transactional
public Result getAllNews(int empId) {
com.myorg.myproj.entities.Employee employeeEntity = userDao.getEmpById(empId);
List cards= employeeEntity.getCards();
com.myorg.myproj.entities.Card cardEntity = (Card) cards.get(0);
List allNews = cardEntity.getNews();
Result result = new Result();
NewsPayload tran = new NewsPayload();
tran.setNewsList(allNews);
result.setPayload(tran);
return result;
}
Other supporting classes :
public class Result {
private int code;
private String description;
private Payload payload;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Payload getPayload() {
return payload;
}
public void setPayload(Payload payload) {
this.payload = payload;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public class NewsPayload implements Payload{
private int empId;
public List getNewsList() {
return newsList;
}
public void setNewsList(List newsList) {
this.newsList = newsList;
}
private List newsList = new ArrayList();
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}

Categories

Resources