Stack overflow error while invoking toString method - java

this is my code but when I execute the program I get many errors and I don't know why. May anyone help me?
RegisteredUser.java
public class RegisteredUser {
private String nickname;
ArrayList<ReviewDAO> reviews;
public RegisteredUser(String nickname) {
this.nickname = nickname;
reviews = new ArrayList<>();
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void addReview(ReviewDAO review) {
if (!this.reviews.contains(review)) {
this.reviews.add(review);
review.addRegisteredUser(this);
}
}
#Override
public String toString() {
return "RegisteredUser{" +
"nickname='" + nickname + '\'' +
", reviews=" + reviews +
'}';
}
}
ReviewDAO.java
public abstract class ReviewDAO {
RegisteredUser registeredUser;
public abstract boolean write(Review review);
public void addRegisteredUser(RegisteredUser registeredUser) {
this.registeredUser = registeredUser;
}
#Override
public String toString() {
return "ReviewDAO{" +
"registeredUser=" + registeredUser +
'}';
}
}
Review.java
public class Review {
private String title;
private String description;
private int rank;
private boolean isAnonymous;
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 int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public boolean isAnonymous() {
return isAnonymous;
}
public void setAnonymous(boolean anonymous) {
isAnonymous = anonymous;
}
}
ReviewDAO_MongoDB.java
public class ReviewDAO_MongoDB extends ReviewDAO {
#Override
public boolean write(Review review) {
return false;
// todo
}
}
ReviewDAO_Factory.java
public class ReviewDAO_Factory {
public ReviewDAO getReviewDAO(String technology) throws ExecutionControl.NotImplementedException {
if (technology.equals("mongodb"))
return new ReviewDAO_MongoDB();
else
throw new ExecutionControl.NotImplementedException("");
}
}
BusinessLogic.java
public class BusinessLogic {
public static void main(String[] args) throws ExecutionControl.NotImplementedException {
ReviewDAO_Factory reviewDAO_factory = new ReviewDAO_Factory();
RegisteredUser registeredUser = new RegisteredUser("Alessandro");
registeredUser.addReview(reviewDAO_factory.getReviewDAO("mongodb"));
System.out.println(registeredUser.toString());
}
}
I am getting
Exception in thread "main" java.lang.StackOverflowError
at RegisteredUser.toString(RegisteredUser.java:33)
at java.base/java.lang.String.valueOf(String.java:2951)
at ReviewDAO.toString(ReviewDAO.java:15)
...
Process finished with exit code 1
errors

First of all, the design looks faulty. You should never mix POJOs with DAOs. DAOs are "data access object" classes which deals with CRUD operations on the POJOs. Here you have 2 POJOs - Review and RegisteredUser. It's the responsibility of ReviewDAO to perform CRUD operations on managed/unmanaged instances (or entities) of Review.
And for RegisteredUser also you need another POJO probably (in your actual code).
Secondly, I see you are calling List contains method to check if the user already has given that review, yet you have not implemented "equals" and "hashCode" in the ReviewDAO.
public void addReview(ReviewDAO review) {
if (!this.reviews.contains(review)) {
this.reviews.add(review);
review.addRegisteredUser(this);
}
}
I have made few tweaks. Please check if it satisfies your need:
RegisteredUser class (Have used hashset cause "contains" search will be faster)
public class RegisteredUser {
private String nickname;
private Set<Review> reviews;
public RegisteredUser(String nickname) {
this.nickname = nickname;
reviews = new HashSet<>();
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public void addReview(Review review) {
if (!this.reviews.contains(review)) {
this.reviews.add(review);
//review.addRegisteredUser(this);
}
}
#Override
public String toString() {
return "RegisteredUser{" +
"nickname='" + nickname + '\'' +
", reviews=" + reviews +
'}';
}
}
ReviewDAO class:
public abstract class ReviewDAO {
private RegisteredUser registeredUser;
public abstract boolean write(Review review);
public void addRegisteredUser(RegisteredUser registeredUser) {
this.registeredUser = registeredUser;
}
}
Review class:
public class Review {
private String title;
private String description;
private int rank;
private boolean isAnonymous;
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 int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public boolean isAnonymous() {
return isAnonymous;
}
public void setAnonymous(boolean anonymous) {
isAnonymous = anonymous;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Review review = (Review) o;
return Objects.equals(title, review.title);
}
#Override
public int hashCode() {
return Objects.hash(title);
}
}
BusinessLogic class
public class BusinessLogic {
public static void main(String[] args) throws ExecutionControl.NotImplementedException {
ReviewDAO_Factory reviewDAO_factory = new ReviewDAO_Factory();
RegisteredUser registeredUser = new RegisteredUser("Alessandro");
Review review = new Review();
review.setTitle("some review");
review.setDescription("some desc");
registeredUser.addReview(review);
ReviewDAO reviewDAO = reviewDAO_factory.getReviewDAO("mongodb");
reviewDAO.addRegisteredUser(registeredUser);
System.out.println(registeredUser.toString());
}
}

Related

passing objects in mvp arch

I work with MVP Architecture I get information through an API. In the MODEL LEVEL, I have List I want to pass this List into PRESENTER LEVEL.
When I create a function to resolve this issue I got an error message "NULL ERROR"
Here is my code :
package com.example.lenovo.myapplication.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class CountryModel {
private String City;
private String Country;
private String Degree;
#SerializedName("posts")
public String getCity() {
return City;
}
public String getCountry() {
return Country;
}
public String getDegree() {
return Degree;
}
public void setCity(String city) {
City = city;
}
public void setCountry(String country) {
Country = country;
}
public void setDegree(String degree) {
Degree = degree;
}
public class ResultModel {
List<CountryModel> posts;
public List<CountryModel> getCountryModels() {
return posts;
}
public void setCountryModels(List<CountryModel> countryModels) {
this.posts = countryModels;
}
}
}
interface method
public CountryModel Get_Wather_Informations(int position);
model code
connection.enqueue(new Callback<CountryModel.ResultModel>() {
#Override
public void onResponse(Call<CountryModel.ResultModel> call, Response<CountryModel.ResultModel> response) {
countryModels = response.body().getCountryModels();
for (int i = 0; i < countryModels.size(); i++) {
CountryModel ye = new CountryModel();
ye.setCountry(countryModels.get(i).getCountry());
ye.setCity(countryModels.get(i).getCity());
ye.setDegree(countryModels.get(i).getDegree());
ARRAYS.add(ye);
Log.e("array size ", String.valueOf(ARRAYS.size()));
// Log.e("Size", String.valueOf(arrayList.size()));
}
#Override
public CountryModel Get_Wather_Informations(int position) {
return countryModels.get(position);
}
When I try to get an object from this list ( PRESENTER LAYER ) I get a null!
CountryModel COUNTRY_OBJ = new CountryModel();
COUNTRY_OBJ = MODEL.Get_Wather_Informations(0);

Parcelable Implementation for Custom Objects

I have 3 POJO types: a Recipe, which contains ingredients, and then the ingredients contain steps. Below is my setup, I am trying to implement Parcelable and cannot determine the appropriate read and write methods:
Recipe.Java:
public class Recipe implements Parcelable {
protected List<Ingredients> ingredients;
private String id;
private String servings;
private String name;
private String image;
private List<Steps> steps;
protected Recipe(Parcel in) {
in.createTypedArray(CREATOR.createFromParcel(Ingredients));
in.createTypedArray(Ingredients.);
id = in.readString();
servings = in.readString();
name = in.readString();
image = in.readString();
steps = in.readArrayList(ClassLoader.getSystemClassLoader());
}
public static final Creator<Ingredients> CREATOR = new Creator<Ingredients>() {
#Override
public Ingredients createFromParcel(Parcel parcel) {
return new Ingredients(parcel);
}
#Override
public Ingredients[] newArray(int i) {
return new Ingredients[0];
}
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel in) {
return new Recipe(in);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
public List<Ingredients> getIngredients() {
return ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
this.ingredients = ingredients;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getServings() {
return servings;
}
public void setServings(String servings) {
this.servings = servings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List<Steps> getSteps() {
return steps;
}
public void setSteps(List<Steps> steps) {
this.steps = steps;
}
#Override
public String toString() {
return "ClassPojo [ingredients = " + ingredients + ", id = " + id + ", servings = " + servings + ", name = " + name + ", image = " + image + ", steps = " + steps + "]";
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(id);
parcel.writeString(servings);
parcel.writeString(name);
parcel.writeString(image);
}
}
Ingredients.Java:
public class Ingredients {
private String measure;
private String ingredient;
private String quantity;
public Ingredients(Parcel parcel) {
}
public String getMeasure ()
{
return measure;
}
public void setMeasure (String measure)
{
this.measure = measure;
}
public String getIngredient ()
{
return ingredient;
}
public void setIngredient (String ingredient)
{
this.ingredient = ingredient;
}
public String getQuantity ()
{
return quantity;
}
public void setQuantity (String quantity)
{
this.quantity = quantity;
}
#Override
public String toString()
{
return "ClassPojo [measure = "+measure+", ingredient = "+ingredient+", quantity = "+quantity+"]";
}
}
Steps.Java:
public class Steps {
private String id;
private String shortDescription;
private String description;
private String videoURL;
private String thumbnailURL;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getShortDescription ()
{
return shortDescription;
}
public void setShortDescription (String shortDescription)
{
this.shortDescription = shortDescription;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getVideoURL ()
{
return videoURL;
}
public void setVideoURL (String videoURL)
{
this.videoURL = videoURL;
}
public String getThumbnailURL ()
{
return thumbnailURL;
}
public void setThumbnailURL (String thumbnailURL)
{
this.thumbnailURL = thumbnailURL;
}
#Override
public String toString()
{
return "ClassPojo [id = "+id+", shortDescription = "+shortDescription+", description = "+description+", videoURL = "+videoURL+", thumbnailURL = "+thumbnailURL+"]";
}
}
I suggest you to use third party library such as Paperparcel to reduce boilerplate.
Sample of usage:
#PaperParcel // (1)
public final class User implements Parcelable {
public static final Creator<User> CREATOR = PaperParcelUser.CREATOR; // (2)
long id; // (3)
String firstName; // (3)
String lastName; // (3)
#Override public int describeContents() {
return 0;
}
#Override public void writeToParcel(Parcel dest, int flags) {
PaperParcelUser.writeToParcel(this, dest, flags); // (4)
}
}

How to use jdbctemplate and row mapper to create object with a list of objects?

I was wondering how to use jdbctemplate and RowMapper to create object with a list of objects?
Below are the three objects that I need to get mapped based on data from the db.
public class UserDTO {
private String userID;
private String email;
private List<RooftopDTO> rooftops;
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<RooftopDTO> getRooftops() {
return rooftops;
}
public void setRooftops(List<RooftopDTO> rooftops) {
this.rooftops = rooftops;
}
}
public class RooftopDTO {
private String dealerID;
private String name;
private String address;
private List<VenueDTO> venues;
public String getDealerID() {
return dealerID;
}
public void setDealerID(String dealerID) {
this.dealerID = dealerID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<VenueDTO> getVenues() {
return venues;
}
public void setVenues(List<VenueDTO> venues) {
this.venues = venues;
}
}
public class VenueDTO {
private int integrationID;
private String rooftopID;
public int getIntegrationID() {
return integrationID;
}
public void setIntegrationID(int integrationID) {
this.integrationID = integrationID;
}
public String getRooftopID() {
return rooftopID;
}
public void setRooftopID(String rooftopID) {
this.rooftopID = rooftopID;
}
}
As you can see, I need to create lists of objects within each object. This is what I have so far in my MapperClass, but I can't figure out what else to do..
public class UserDTOMapper implements RowMapper<UserDTO> {
#Override
public UserDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
UserDTO userDTO = new UserDTO();
RooftopDTO rooftops = new RooftopDTO();
VenueDTO venues = new VenueDTO();
ArrayList<VenueDTO> venueList = new ArrayList<>();
ArrayList<RooftopDTO> rooftopList = new ArrayList<>();
userDTO.setUserID(rs.getString("user_id"));
userDTO.setEmail(rs.getString("email"));
rooftops.setDealerID(rs.getString("dealer_id"));
rooftops.setAddress(rs.getString("addr_1"));
rooftops.setName(rs.getString("dealer_nm"));
venues.setIntegrationID(rs.getInt("integration_id"));
venues.setRooftopID("act_org_id");
}
}
Can someone help me finish this mapRow method?

How to add a mongo id from one collection as a foreign key in another collection

In my Spring boot application, I have collection of Todos and a collection of Courses. In the view of the application, I return the collection of courses and display whatever course I need. The Todos are stored as 1 list which represents all the current Todos. What I would like to do is return a list of Todos for each course. So when the view is opened, the application would display the the course plus the individual todo list for that course.
Is there a way I can use the existing code to incorporate the new functionality. I have created the front end logic and would like to keep that. My initial idea was to add the the course id to the Todo.java, but that did not work.
Todo.java
#Document(collection="todos")
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=250)
#Indexed(unique=true)
private String title;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title) {
this.title = title;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s', completed='%s']",
id, title, completed);
}
}
TodoRepository.java
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
public List<Todo> findAll();
public Todo findOne(String id);
public Todo save(Todo todo);
public void delete(Todo todo);
}
Courses
#Document(collection = "courses")
public class Courses {
#Id
private String id;
private String name;
private String lecturer;
private String picture;
private String video;
private String description;
private String enroled;
public Courses(){}
public Courses(String name, String lecturer, String picture, String video, String description,String enroled) {
this.name = name;
this.lecturer = lecturer;
this.picture = picture;
this.video = video;
this.description = description;
this.enroled = enroled;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLecturer() {
return lecturer;
}
public void setLecturer(String lecturer) {
this.lecturer = lecturer;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEnroled() {
return enroled;
}
public void setEnroled(String enroled) {
this.enroled = enroled;
}
#Override
public String toString() {
return "Courses{" +
"id='" + id + "'" +
", name='" + name + "'" +
", lecturer='" + lecturer + "'" +
", description='" + description + "'" +
'}';
}
}

Does Neo4j OGM work well with interfaces?

I've developed two sets of classes - the first one are just classes, whereas in the second set, the classes derive from interfaces. Both the sets of classes mimic each other. The repositories for them are also similar. However, the repository works well for the first set of classes (nodes and relationships). For the second set of classes though, the repository is able to insert records, but the findAll method fails and doesn't return me any records.
Here's the first set of classes with the repository -
public abstract class Entity {
#GraphId
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || id == null || getClass() != o.getClass()) return false;
Entity entity = (Entity) o;
if (!id.equals(entity.id)) return false;
return true;
}
#Override
public int hashCode() {
return (id == null) ? -1 : id.hashCode();
}
}
public abstract class GenericRepository<T> implements IGenericRepository<T> {
private static final int DEPTH_LIST = 1;
private static final int DEPTH_ENTITY = 2;
private Session session;
public GenericRepository(String url, String username, String password) {
super();
session = Neo4jSessionFactory.getInstance().getNeo4jSession(url, username, password);
}
public Iterable<T> findAll() {
return session.loadAll(getEntityType(), DEPTH_LIST);
}
public T findOne(Long id) {
return session.load(getEntityType(), id, DEPTH_ENTITY);
}
public void delete(T entity) {
session.delete(session.load(getEntityType(), ((Entity) entity).getId()));
}
public T createOrUpdate(T entity) {
session.save(entity, DEPTH_ENTITY);
return findOne(((Entity) entity).getId());
}
public abstract Class<T> getEntityType();
}
#RelationshipEntity(type="MY_ROLE")
public class ARole extends Entity {
#Property
private String title;
#StartNode
private HomoSapiens start;
#EndNode
private HomoSapiens end;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public HomoSapiens getStart() {
return start;
}
public void setStart(HomoSapiens start) {
this.start = start;
}
public HomoSapiens getEnd() {
return end;
}
public void setEnd(HomoSapiens end) {
this.end = end;
}
public ARole() {}
public ARole(String title) {
this.title = title;
}
}
#NodeEntity
public class HomoSapiens extends Entity {
private String name;
#Relationship(type = "MY_ROLE", direction = Relationship.INCOMING)
private ARole aRole;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ARole getaRole() {
return aRole;
}
public void setaRole(ARole aRole) {
this.aRole = aRole;
}
public HomoSapiens() {}
public HomoSapiens(String name) {
this.name = name;
}
}
public class ARoleDao extends GenericRepository<ARole> implements IARoleDao {
public ARoleDao(String url, String username, String password) {
super(url, username, password);
}
#Override
public Class<ARole> getEntityType() {
return ARole.class;
}
}
Here's the second set of classes -
public interface IARole {
String getTitle();
void setTitle(String title);
IHomoSapiens getStart();
void setStart(IHomoSapiens start);
IHomoSapiens getEnd();
void setEnd(IHomoSapiens end);
}
public interface IHomoSapiens {
String getName();
void setName(String name);
IARole getARole();
void setARole(IARole aRole);
}
#RelationshipEntity(type="MY_DERIVED_ROLE")
public class DerivedARole extends Entity implements IARole {
#Property
private String title;
#StartNode
private IHomoSapiens start;
#EndNode
private IHomoSapiens end;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public IHomoSapiens getStart() {
return start;
}
public void setStart(IHomoSapiens start) {
this.start = start;
}
public IHomoSapiens getEnd() {
return end;
}
public void setEnd(IHomoSapiens end) {
this.end = end;
}
public DerivedARole() {}
public DerivedARole(String title) {
this.title = title;
}
}
#NodeEntity
public class DerivedHomoSapiens extends Entity implements IHomoSapiens {
private String name;
#Relationship(type = "MY_DERIVED_ROLE", direction = Relationship.INCOMING)
private IARole aRole;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public IARole getARole() {
return aRole;
}
public void setARole(IARole aRole) {
this.aRole = aRole;
}
public DerivedHomoSapiens() {}
public DerivedHomoSapiens(String name) {
this.name = name;
}
}
public class DerivedARoleDao extends GenericRepository<DerivedARole> {
public DerivedARoleDao(String url, String username, String password) {
super(url, username, password);
}
#Override
public Class<DerivedARole> getEntityType() {
return DerivedARole.class;
}
}
public class DerivedARoleDaoSpecs {
private DerivedARoleDao derivedARoleDao;
#Before
public void setUp() throws Exception {
derivedARoleDao = new DerivedARoleDao(DomainHelper.NEO_URL, DomainHelper.NEO_USERNAME,
DomainHelper.NEO_PASSWORD);
}
public void should_insert_data() {
IHomoSapiens start = new DerivedHomoSapiens("d-start");
IHomoSapiens end = new DerivedHomoSapiens("d-end");
IARole aRole = new DerivedARole("parent");
start.setARole(aRole);
end.setARole(aRole);
aRole.setStart(start);
aRole.setEnd(end);
IARole created = derivedARoleDao.createOrUpdate((DerivedARole)aRole);
assertThat(created, is(notNullValue()));
}
public void should_find_all() {
Iterable<DerivedARole> derivedARoles = derivedARoleDao.findAll();
assertThat(derivedARoles, is(notNullValue()));
assertThat(Iterables.isEmpty(derivedARoles), is(false));
assertTrue(Iterables.size(derivedARoles) > 0);
System.out.println(Iterables.size(derivedARoles));
}
#Test
public void should_do_crud() {
// should_insert_data();
should_find_all();
// should_find_by_id();
}
}
Am I missing something here? Or does the Neo4j OGM works well with classes (not implementing interfaces)?
The entire source code is at - https://github.com/mmwaikar/java-neo-ogm-ex (in case, it helps).
Thanks,
Manoj.
This should be fixed in 1.1.3
Till that is released, please try your code example with 1.1.3-SNAPSHOT.
You'll need to include
<repository>
<id>neo4j-snapshots</id>
<url>http://m2.neo4j.org/content/repositories/snapshots</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>

Categories