Unable to fetch json object and array in Retrofit 2 - java

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 */

Related

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

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

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;
}

Failed to receive any response from server in android using Retrofit and PHP as backend

Failed to receive body from response. i used php as back end server in android using Retrofit . in my every project i used retrofit but this time i failed getting response body from server i don't know where is the problem.
I search all over the internet but i failed to get out myself from the problem. in below i put all of my code. Thanks you a lot in advance
VideoApi.class
import java.util.List;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
public interface VideoApi {
String BASE_URL = "https://mozeloapp.in/ViddoApp/ViddoVideoRetrive.php/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
#GET(BASE_URL)
Call<List<VideoModel>> getVideoLink();
}
ModelClass.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class VideoModel {
#SerializedName("id")
#Expose
private String id;
#SerializedName("categoryId")
#Expose
private String categoryId;
#SerializedName("categoryName")
#Expose
private String categoryName;
#SerializedName("videoLink")
#Expose
private String videoLink;
public VideoModel() {
}
public VideoModel(String id, String categoryId, String categoryName, String videoLink) {
this.id = id;
this.categoryId = categoryId;
this.categoryName = categoryName;
this.videoLink = videoLink;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getVideoLink() {
return videoLink;
}
public void setVideoLink(String videoLink) {
this.videoLink = videoLink;
}
}
MainActivity.java
private VideoApi videoApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoApi = VideoApi.retrofit.create(VideoApi.class);
Call<List<VideoModel>> call = videoApi.getVideoLink();
call.enqueue(new Callback<List<VideoModel>>() {
#Override
public void onResponse(Call<List<VideoModel>> call, Response<List<VideoModel>> response) {
if (response.isSuccessful()){
for (VideoModel videoModel : response.body()){
String link = videoModel.getVideoLink();
Log.d("VIDEOLINK", "onResponse: "+link);
}
}else {
Log.d("VIDEOLINK", "onResponse: "+"failed");
}
}
#Override
public void onFailure(Call<List<VideoModel>> call, Throwable t) {
Log.d("VIDEOLINK", "onResponse: "+t.getLocalizedMessage());
}
});
}
}
You seem to be wrong in the attributes you parse. I expect that from this line:
Log.d("VIDEOLINK", "onResponse: "+link);
You get the output
"onResponse: null"
Correct your SerializedName definitions:
#SerializedName("name")
#Expose
private String categoryName;
#SerializedName("link")
#Expose
private String videoLink;
I am basing my answer on what I see as response from your API.

How to add array list to rest API request using Rest Assured?

I'm using rest assured for Rest api testing with the help of POJO classes like getter and setter methods to set the values but i'm stuck with array list in between rest request,please any one provide proper code to get exact below request to post using rest assured.
Request:
{
"firstName":"SuryaNAMASKARAM",
"lastName":"mangalam",
"mobileNo" :4954758490,
"emailId" :"surya.mangalam#futureretail.in",
"houseNoStreet":"123456",
"buildingName":"",
"landmark":"Nirmala jathara",
"paymentDetail" :
[{"paymentType":"CASH","No":"3519000012","Date":"16-06-2018","amount":"100.00"}]
}
CustomerCreate Class:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("firstName")
#Expose
private String firstName;
#SerializedName("lastName")
#Expose
private String lastName;
#SerializedName("mobileNo")
#Expose
private Integer mobileNo;
#SerializedName("emailId")
#Expose
private String emailId;
#SerializedName("houseNoStreet")
#Expose
private String houseNoStreet;
#SerializedName("buildingName")
#Expose
private String buildingName;
#SerializedName("landmark")
#Expose
private String landmark;
#SerializedName("paymentDetail")
#Expose
private List<PaymentDetail> paymentDetail = null;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getMobileNo() {
return mobileNo;
}
public void setMobileNo(Integer mobileNo) {
this.mobileNo = mobileNo;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getHouseNoStreet() {
return houseNoStreet;
}
public void setHouseNoStreet(String houseNoStreet) {
this.houseNoStreet = houseNoStreet;
}
public String getBuildingName() {
return buildingName;
}
public void setBuildingName(String buildingName) {
this.buildingName = buildingName;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public List<PaymentDetail> getPaymentDetail() {
return paymentDetail;
}
public void setPaymentDetail(List<PaymentDetail> paymentDetail) {
this.paymentDetail = paymentDetail;
}
}
PaymentDetails:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class PaymentDetail {
#SerializedName("paymentType")
#Expose
private String paymentType;
#SerializedName("No")
#Expose
private String no;
#SerializedName("Date")
#Expose
private String date;
#SerializedName("amount")
#Expose
private String amount;
public String getPaymentType() {
return paymentType;
}
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Test Class:
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.test.requestpojo.Example;
import com.test.requestpojo.PaymentDetail;
public class TestAPI {
public void setTestData() throws JSONException {
Example example = new Example();
example.setFirstName("Rajesh");
example.setLastName("Kuchana");
example.setMobileNo("3434343434");
example.setEmailId("rajesh.kuchana#futureretail.in");
example.setDateOfBirth("10-10-2018");
example.setGender(1);
example.setHouseNoStreet("Test");
example.setBuildingName("Test");
example.setLandmark("Test");
List<PaymentDetail> data = new ArrayList<PaymentDetail>();
PaymentDetail paymentDetail = new PaymentDetail();
paymentDetail.setAmount("999.00");
data.add(paymentDetail);
JSONObject jsonObject = new JSONObject(example);
JSONArray jsonArray = new JSONArray(data);
jsonArray.put(data);
System.out.println(jsonArray.put(data));
}
In your test class, what you must do is separate the test data creation to a different class and pass that as data provider to your test method. This is from design point of view.
Coming to your problem:
You are already using gson, why are you constructing a JSONObject. Instead do something like below;
Gson gson = new Gson();
String _my_obj = gson.toJson(example);
Hope this is what you are looking for.

Empty join table for ManyToMany Relationship

A similar question with a different issue has been answered before. I have a bidirectional #ManyToMany relationship using Hibernate. The data persists to the separate entity tables, but the id column that maps to the entity tables is empty. I have tried the suggestions in Empty Join Table resulting from JPA ManyToMany, ManyToMany relationship, deleting records from relationship table and Hibernate Many-to-many association: left hand side collection contains elements, but right hand side collection is empty, but have not had success so far. Below is my code for completeness (I am still learning java and the spring framework, so I apologise for any rookie mistakes in advance):
CaseStudy Class
#Entity
public class CaseStudy {
#Id
#GeneratedValue (strategy = GenerationType.AUTO)
private Long caseStudyId;
private String location;
private String equipment;
private String issue;
private String solution;
private String benefit;
private float upper_dissolved_Oxygen;
private float lower_dissolved_Oxygen;
private float upper_pH;
private float lower_pH;
private float upper_temp;
private float lower_temp;
private float upper_conductivity;
private float lower_conductivity;
#CreationTimestamp
private Date created;
#ManyToOne
#JsonBackReference
private User user;
private int likes;
#ManyToMany(mappedBy="casestudyList", fetch = FetchType.EAGER)
private List<WaterQuality> waterQualityList = new List<WaterQuality>();
#OneToMany(mappedBy = "casestudy", fetch = FetchType.EAGER)
private List<Comment> commentList;
public Long getCaseStudyId() {
return caseStudyId;
}
public void setCaseStudyId(Long caseStudyId) {
this.caseStudyId = caseStudyId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getSolution() {
return solution;
}
public void setSolution(String solution) {
this.solution = solution;
}
public String getBenefit() {
return benefit;
}
public void setBenefit(String benefit) {
this.benefit = benefit;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
public String getEquipment() {
return equipment;
}
public void setEquipment(String equipment) {
this.equipment = equipment;
}
public float getUpper_dissolved_Oxygen() {
return upper_dissolved_Oxygen;
}
public void setUpper_dissolved_Oxygen(float upper_dissolved_Oxygen) {
this.upper_dissolved_Oxygen = upper_dissolved_Oxygen;
}
public float getLower_dissolved_Oxygen() {
return lower_dissolved_Oxygen;
}
public void setLower_dissolved_Oxygen(float lower_dissolved_Oxygen) {
this.lower_dissolved_Oxygen = lower_dissolved_Oxygen;
}
public float getUpper_pH() {
return upper_pH;
}
public void setUpper_pH(float upper_pH) {
this.upper_pH = upper_pH;
}
public float getLower_pH() {
return lower_pH;
}
public void setLower_pH(float lower_pH) {
this.lower_pH = lower_pH;
}
public float getUpper_temp() {
return upper_temp;
}
public void setUpper_temp(float upper_temp) {
this.upper_temp = upper_temp;
}
public float getLower_temp() {
return lower_temp;
}
public void setLower_temp(float lower_temp) {
this.lower_temp = lower_temp;
}
public float getUpper_conductivity() {
return upper_conductivity;
}
public void setUpper_conductivity(float upper_conductivity) {
this.upper_conductivity = upper_conductivity;
}
public float getLower_conductivity() {
return lower_conductivity;
}
public void setLower_conductivity(float lower_conductivity) {
this.lower_conductivity = lower_conductivity;
}
public List<WaterQuality> getWaterQualityList() {
return waterQualityList;
}
public void setWaterQualityList(List<WaterQuality> waterQualityList) {
this.waterQualityList = waterQualityList;
}
}
WaterQuality Class
#Entity
public class WaterQuality {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long waterQualityId;
private String description;
private String status;
private float dissolved_Oxygen;
private float pH;
private float temp;
private float conductivity;
#CreationTimestamp
private Date publishDate;
#ManyToOne
#JsonBackReference
private User user;
#ManyToMany(targetEntity = CaseStudy.class, cascade = {CascadeType.ALL})
#JoinTable(
joinColumns = {#JoinColumn(name="water_quality_id")},
inverseJoinColumns = {#JoinColumn(name="case_study_id")})
private Set<CaseStudy> casestudyList = new HashSet<CaseStudy>();
public Long getWaterQualityId() {
return waterQualityId;
}
public void setWaterQualityId(Long waterQualityId) {
this.waterQualityId = waterQualityId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public float getDissolved_Oxygen() {
return dissolved_Oxygen;
}
public void setDissolved_Oxygen(float dissolved_Oxygen) {
this.dissolved_Oxygen = dissolved_Oxygen;
}
public float getpH() {
return pH;
}
public void setpH(float pH) {
this.pH = pH;
}
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public float getConductivity() {
return conductivity;
}
public void setConductivity(float conductivity) {
this.conductivity = conductivity;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Set<CaseStudy> getCasestudyList() {
return casestudyList;
}
public void setCasestudyList(Set<CaseStudy> casestudyList) {
this.casestudyList = casestudyList;
}
public List<CaseStudy> getDissolvedOxygenalert() {
List<CaseStudy> dissolvedOxygenalert = casestudyList.stream() //convert list to stream
.filter(casestudy -> casestudy.getUpper_dissolved_Oxygen() < getDissolved_Oxygen() || casestudy.getLower_dissolved_Oxygen() > getDissolved_Oxygen())
.collect(Collectors.toList()); //collect the output and convert streams to a List
System.out.print(dissolvedOxygenalert);
return dissolvedOxygenalert;
}
}
I have tried deleting the database and creating it again, but it hasn't solved the problem so far.
Below is the code for persisting the data to the database
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CaseStudy Service Implementation
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scrunch.data.dao.CaseStudyDao;
import com.scrunch.data.model.CaseStudy;
import com.scrunch.data.model.User;
import com.scrunch.data.service.CaseStudyService;
#Service
public class CaseStudyServiceImpl implements CaseStudyService{
#Autowired
private CaseStudyDao casestudyDao;
public CaseStudy save(CaseStudy casestudy) {
return casestudyDao.save(casestudy);
}
public Set<CaseStudy> findByUser(User user) {
return casestudyDao.findByUser(user);
}
public CaseStudy findByCaseStudyId(Long caseStudyId) {
return casestudyDao.findByCaseStudyId(caseStudyId);
}
public Set<CaseStudy> findAll() {
return casestudyDao.findAll();
}
}
WaterQuality Service Implementation
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scrunch.data.dao.WaterQualityDao;
import com.scrunch.data.model.User;
import com.scrunch.data.model.WaterQuality;
import com.scrunch.data.service.WaterQualityService;
#Service
public class WaterQualityServiceImpl implements WaterQualityService{
// private static final Logger LOGGER = LoggerFactory.getLogger(WaterQualityServiceImpl.class);
#Autowired
private WaterQualityDao waterQualityDao;
#Override
public List<WaterQuality> listAllWaterQualityByUserAndDescription(
User user, String description) {
return waterQualityDao.findAllWaterQualityByUserAndDescriptionContaining(user, description);
}
#Override
public WaterQuality save(WaterQuality waterQuality) {
return waterQualityDao.save(waterQuality);
}
#Override
public List<WaterQuality> findByUser(User user) {
return waterQualityDao.findByUser(user);
}
#Override
public WaterQuality findWaterQualityById(Long waterQualityId) {
return waterQualityDao.findByWaterQualityId(waterQualityId);
}
#Override
public List<WaterQuality> findAll() {
return waterQualityDao.findAll();
}
}
WaterQuality Controller
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.fasterxml.jackson.annotation.JsonIgnore;
import com.scrunch.data.model.CaseStudy;
import com.scrunch.data.model.User;
import com.scrunch.data.model.WaterQuality;
import com.scrunch.data.service.WaterQualityService;
#RestController
#RequestMapping("/rest")
public class WaterQualityResource {
private String location;
private String equipment;
private String issue;
private String solution;
private String benefit;
private float upper_dissolved_Oxygen;
private float lower_dissolved_Oxygen;
private int likes;
#Autowired
private WaterQualityService waterQualityService;
#RequestMapping(value="/waterquality/add", method=RequestMethod.POST)
public WaterQuality addWaterQuality(#RequestBody WaterQuality waterQuality) {
waterQuality.setCasestudyList(new HashSet<CaseStudy>());
CaseStudy casestudy = new CaseStudy();
casestudy.setLocation(location);
casestudy.setEquipment(equipment);
casestudy.setIssue(issue);
casestudy.setSolution(solution);
casestudy.setBenefit(benefit);
casestudy.setUpper_dissolved_Oxygen(upper_dissolved_Oxygen);
casestudy.setLower_dissolved_Oxygen(lower_dissolved_Oxygen);
waterQuality.getCasestudyList().add(casestudy);
return waterQualityService.save(waterQuality);
}
Get request for all waterqualities response returns and endless loop of the same results.
[{"waterQualityId":1,"description":"sdfdsf","status":"dsfdsf","dissolved_Oxygen":5.0,"pH":7.0,"temp":72.0,"conductivity":500.0,"publishDate":1472784062000,"dissolvedOxygenalert":[{"caseStudyId":2,"location":null,"equipment":null,"issue":null,"solution":null,"benefit":null,"upper_dissolved_Oxygen":0.0,"lower_dissolved_Oxygen":0.0,"upper_pH":0.0,"lower_pH":0.0,"upper_temp":0.0,"lower_temp":0.0,"upper_conductivity":0.0,"lower_conductivity":0.0,"created":1472784062000,"likes":0,"waterQualityList":[{"waterQualityId":1,"description":"sdfdsf","status":"dsfdsf","dissolved_Oxygen":5.0,"pH":7.0,"temp":72.0,"conductivity":500.0,"publishDate":1472784062000,"dissolvedOxygenalert":[{"caseStudyId":2,"location":null,"equipment":null,"issue":null,"solution":null,"benefit":null,"upper_dissolved_Oxygen":0.0,"lower_dissolved_Oxygen":0.0,"upper_pH":0.0,"lower_pH":0.0,"upper_temp":0.0,"lower_temp":0.0,"upper_conductivity":0.0,"lower_conductivity":0.0,"created":1472784062000,"likes":0,"waterQualityList":
I am able to get data populated to the join table, but it seems to populate endlessly. It happens when the water quality data is added.
It is not clear in code posted, how you are trying to save associated entity. You should persist like this...
WaterQuality waterQuality = new WaterQuality();
//Set other fields too
CaseStudy caseStudy1 = new CaseStudy();
CaseStudy caseStudy2 = new CaseStudy();
CaseStudy caseStudy3 = new CaseStudy();
CaseStudy caseStudy4 = new CaseStudy();
//Set other fileds of case study too
List<CaseStudy> caseStudyList = waterQuality.getCaseStudyList();
caseStudyList.add(caseStudy1);
caseStudyList.add(caseStudy2);
caseStudyList.add(caseStudy3);
caseStudyList.add(caseStudy4);
waterQualityService.save(waterQuality);
If you will assign WaterQuality objects to CaseStudy Entity and save CaseStudy, then associations won't be populated in JoinTable.
And one more important thing, use Set instead of List for Collection.In case of List, Suppose, You already have 100 case study for waterQuality and if you want to delete one of them, Then it will delete entire case studies first and then add all case study again except the deleted one. Use Set if your collection does not contain duplicates. If your collection contains duplicates too, Then use List with index.

Categories

Resources