<th:block th:each> is not retrieving data required? Table shows blank - html

This is my JSP file
<html>
<head>
<title>Todo's for ${name}</title>
</head>
<body>
<h1>Your ToDo's</h1>
<table>
<caption>Your Todo's are as follows:</caption>
<thead>
<tr>
<th>Description</th>
<th>Target Date</th>
<th>Is it completed?</th>
</tr>
</thead>
<tbody>
<th:block th:each="todo : ${todos}">
<tr>
<td th:text="${todo.desc}"></td>
<td th:text="${todo.targetDate}"></td>
<td th:text="${todo.done}"></td>
</tr>
</th:block>
</tbody>
</table>
<br/>
Add Todo
</body>
</html>
This is my TodoService.java file
package com.example.springboot.demo.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Service;
import com.in28minutes.springboot.web.model.Todo;
#Service
public class TodoService {
private static List<Todo> todos = new ArrayList<Todo>();
private static int todoCount = 3;
static {
todos.add(new Todo(1, "Prakriti", "Learn Spring MVC", new Date(),
false));
todos.add(new Todo(2, "Prakriti", "Learn Struts", new Date(), false));
todos.add(new Todo(3, "Prakriti", "Learn Hibernate", new Date(),
false));
}
public List<Todo> retrieveTodos(String user) {
List<Todo> filteredTodos = new ArrayList<Todo>();
for (Todo todo : todos) {
if (todo.getUser().equals(user)) {
filteredTodos.add(todo);
}
}
return filteredTodos;
}
public void addTodo(String name, String desc, Date targetDate,
boolean isDone) {
todos.add(new Todo(++todoCount, name, desc, targetDate, isDone));
}
public void deleteTodo(int id) {
Iterator<Todo> iterator = todos.iterator();
while (iterator.hasNext()) {
Todo todo = iterator.next();
if (todo.getId() == id) {
iterator.remove();
}
}
}
}
I have three values in the table but it doesn't retrieve them, can't understand why I have used the thymeleaf block properly only. Below is my TodoController.java file.
package com.example.springboot.demo.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.example.springboot.demo.service.LoginService;
import com.example.springboot.demo.service.TodoService;
#Controller
#SessionAttributes("name")
public class TodoController {
#Autowired
TodoService service;
#RequestMapping(value="/list-todos", method=RequestMethod.GET)
public String showTodosList(ModelMap model) {
String name=(String)model.get("name");
model.put("todos",service.retrieveTodos(name));
return "list-todos";
}
#RequestMapping(value="/add-todos", method=RequestMethod.GET)
public String showaddTodoPage(ModelMap model) {
return "add-todos";
}
#RequestMapping(value="/add-todos", method=RequestMethod.POST)
public String addTodos(ModelMap model, #RequestParam String desc) {
service.addTodo((String)model.get("name"), desc, new Date(), false);
return "redirect:/list-todos";
}
}
This is my Todo.java
package com.in28minutes.springboot.web.model;
import java.util.Date;
public class Todo {
private int id;
private String user;
private String desc;
private Date targetDate;
private boolean isDone;
public Todo(int id, String user, String desc, Date targetDate,
boolean isDone) {
super();
this.id = id;
this.user = user;
this.desc = desc;
this.targetDate = targetDate;
this.isDone = isDone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
public boolean isDone() {
return isDone;
}
public void setDone(boolean isDone) {
this.isDone = isDone;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Todo other = (Todo) obj;
if (id != other.id) {
return false;
}
return true;
}
#Override
public String toString() {
return String.format(
"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]", id,
user, desc, targetDate, isDone);
}
}
Output:
Please let me know what's needed to be done for the values to be displayed in the table.

Try using,
<tr th:each="todo : ${todos}">
<td th:text="${todo.desc}"></td>
<td th:text="${todo.targetDate}"></td>
<td th:text="${todo.done}"></td>
</tr>

Related

How to query a many to many relationship in spring boot repository

I am trying to have the api return a list of notes, associated by a many to many relationship with labels, given a label id. Spring boot automatically created a bridge table called notes_tables with a notes_id field and a labels_id field. Spring Boot also created a notes table and a labels table. I attempted the following:
#Query(value="select * from notes join notes_labels on note.id=notes_id join labels on labels_id=labels.id where labels_id=:lid", nativeQuery=true)
public List<Note> findNotesForLabel(#Param("lid") int labelId);
I just need to get this to work but I am specifically curious if I can get it to work with jpa method query. Any query will do as long as it works though.
EDIT:
Entities
Note.java
package com.example.maapi.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "notes")
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String note;
private String title;
private String status = "private";
#ManyToOne
#JsonIgnore
private User user;
#ManyToOne
#JsonIgnore
private Folder folder;
#ManyToMany
#JsonIgnore
private List<Label> labels;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Folder getFolder() {
return folder;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<Label> getLabels() {
return labels;
}
public void setLabels(List<Label> labels) {
this.labels = labels;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Note)) {
return false;
}
Note note = (Note) o;
return id == note.id && Objects.equals(note, note.note) &&
Objects.equals(title, note.title) && Objects.equals(status,
note.status) && Objects.equals(user, note.user) &&
Objects.equals(folder, note.folder) && Objects.equals(labels,
note.labels);
}
#Override
public int hashCode() {
return Objects.hash(id, note, title, status, user, folder,
labels);
}
}
Label.java
package com.example.maapi.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
import java.util.Objects;
#Entity
#Table(name = "labels")
public class Label {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;
private String status = "private";
#ManyToOne
#JsonIgnore
private User user;
#ManyToOne
#JsonIgnore
private Folder folder;
#ManyToMany(mappedBy = "labels")
#JsonIgnore
private List<Note> notes;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Folder getFolder() {
return folder;
}
public void setFolder(Folder folder) {
this.folder = folder;
}
public List<Note> getNotes() {
return notes;
}
public void setNotes(List<Note> notes) {
this.notes = notes;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Label)) {
return false;
}
Label label = (Label) o;
return id == label.id && Objects.equals(title, label.title) &&
Objects.equals(status, label.status) && Objects.equals(user,
label.user) && Objects.equals(folder, label.folder) &&
Objects.equals(notes, label.notes);
}
#Override
public int hashCode() {
return Objects.hash(id, title, status, user, folder, notes);
}
}
Services:
NoteService.java
package com.example.maapi.services;
import com.example.maapi.models.Folder;
import com.example.maapi.models.Note;
import com.example.maapi.models.User;
import com.example.maapi.repositories.FolderRepo;
import com.example.maapi.repositories.NoteRepo;
import com.example.maapi.repositories.UserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class NoteService {
#Autowired
NoteRepo noteRepo;
#Autowired
UserRepo userRepo;
#Autowired
FolderRepo folderRepo;
public List<Note> findAllNotes(){
return noteRepo.findAllNotes();
}
public Note findNoteById(int noteId){
return noteRepo.findNoteById(noteId);
}
public List<Note> findNotesByUser(int userId){
return noteRepo.findNotesByUser(userId);
}
public Note createNoteForUser(int userId, Note note){
User user = userRepo.findUserById(userId);
note.setUser(user);
return noteRepo.save(note);
}
public List<Note> findNotesByFolder(int folderId){
return noteRepo.findNotesByFolder(folderId);
}
public Note createNoteForFolder(int folderId, Note note){
Folder folder = folderRepo.findFolderById(folderId);
note.setFolder(folder);
note.setUser(folder.getUser());
return noteRepo.save(note);
}
public int updateNote(int noteId, Note updatedNote){
Note note = noteRepo.findNoteById(noteId);
updatedNote.setUser(note.getUser());
updatedNote.setFolder(note.getFolder());
noteRepo.save(updatedNote);
if(updatedNote.equals(note)){
return 1;
} else {
return 0;
}
}
public int deleteNote(int noteId){
noteRepo.deleteById(noteId);
if(noteRepo.findNoteById(noteId) == null) {
return 1;
} else {
return 0;
}
}
// SEARCH IMPLEMENTATION
public List<Note> searchForNote(String note){
return noteRepo.searchForNote(note);
}
}
LabelService.java
So this is the spring-booty way to do this that I was able to figure out. CrudRepository has findById(Integer id) which returns an Optional object.
All you have to do is optional.get() to return the encapsulated object and then you can return the desired field (in my case List notes) with a getter.
// CrudRepo interface provides the findById method which returns an Optional<Label>
// object that may or may not exist. Optional.get() returns the encapsulated object.
public List<Note> findNotesByLabelId(int labelId) {
Optional<Label> label = labelRepo.findById(labelId);
return label.get().getNotes();
}
Try this one!
SELECT * FROM notes n INNER JOIN notes_labels nl ON nl.notes_id = n.note_id WHERE nl.labels_id = ?1
Edit:
#Entity
#Table(name = "notes")
#NamedNativeQuery(name = "Note.getNoteByLabel", resultSetMapping = "getNote",
query = "SELECT n.id,n.note,n.title,n.status FROM notes n INNER JOIN notes_labels nl ON nl.notes_id = n.note_id WHERE nl.labels_id = ?1")
#SqlResultSetMapping(name = "getNote", classes = #ConstructorResult(targetClass = Note.class,
columns = {#ColumnResult(name = "id", type = Integer.class),#ColumnResult(name = "note", type = String.class)
#ColumnResult(name = "title", type = String.class),#ColumnResult(name = "status", type = String.class)}))
public class Note {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String note;
private String title;
private String status = "private";
NoteRepo.java
#Query(nativeQuery = true)
List<Note> getNoteByLabel(int labelId);
Build a proper constructor and try this one.
You have to think on it as if it was simple POO. For example, you can use:
#Query("FROM Note n WHERE (SELECT l FROM Label l WHERE l.id = :lid) MEMBER OF labels")
public List<Note> findNotesByLabel(#Param("lid") int id);
which basically means,
get all notes where given id's label is part of the labels attribute
I don't fully know each implementation yet, surely the documentation would give a better approach, but I just came up with that problem and it did the trick

Spring Data Rest - Exposing ID

I am trying to expose the Id of my domain on the Json response using Spring Data Rest, besides getting it on the self object. I try what I saw on the internet but it is not working. I am using Spring Boot and this is my starting class and my config class for exposing the Id.
package com.desingfreed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan("com.designfreed")
public class GaliasBackendApplication {
public static void main(String[] args) {
SpringApplication.run(GaliasBackendApplication.class, args);
}
}
package com.desingfreed.config;
import com.desingfreed.domain.Articulo;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import org.springframework.stereotype.Component;
#Component
public class ConfigurationRest extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Articulo.class);
}
}
package com.desingfreed.repositories;
import com.desingfreed.domain.Articulo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "articulos", path = "articulos")
public interface ArticuloRepository extends CrudRepository<Articulo, Long> {
}
package com.desingfreed.domain;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name = "STA11")
public class Articulo {
#Id
#GeneratedValue
#Column(name = "ID_STA11")
private Long id;
#Column(name = "COD_ARTICU")
private String codigo;
#Column(name = "DESCRIPCIO")
private String descripcion;
// #OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "articulo")
// private List<Precio> precios = new ArrayList<>();
public Articulo() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
// public List<Precio> getPrecios() {
// return precios;
// }
//
// public void setPrecios(List<Precio> precios) {
// this.precios = precios;
// }
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Articulo articulo = (Articulo) o;
if (id != null ? !id.equals(articulo.id) : articulo.id != null) return false;
if (codigo != null ? !codigo.equals(articulo.codigo) : articulo.codigo != null) return false;
return descripcion != null ? descripcion.equals(articulo.descripcion) : articulo.descripcion == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (codigo != null ? codigo.hashCode() : 0);
result = 31 * result + (descripcion != null ? descripcion.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Articulo{" +
"id=" + id +
", codigo='" + codigo + '\'' +
", descripcion='" + descripcion + '\'' +
'}';
}
}
Although doing this I still can get the Id on the Json response, I still get like this:
"_embedded" : {
"articulos" : [ {
"codigo" : "111012082",
"descripcion" : "VIRGEN LEV. FRESCA X 500G",
"_links" : {
"self" : {
"href" : "http://localhost:8080/articulos/1"
},
"articulo" : {
"href" : "http://localhost:8080/articulos/1"
}
}
Thanks very much!
For your information, i've created a simple component to dynamically expose every id.
#Component
public class EntityExposingIdConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
try {
Field exposeIdsFor = RepositoryRestConfiguration.class.getDeclaredField("exposeIdsFor");
exposeIdsFor.setAccessible(true);
ReflectionUtils.setField(exposeIdsFor, config, new ListAlwaysContains());
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
class ListAlwaysContains extends ArrayList {
#Override
public boolean contains(Object o) {
return true;
}
}
}

Primefaces 6 & Content Flow Error

I get java.io.IOException: java.lang.NullPointerException: Argument Error: Parameter url is null.
xhtml file:
<p:dataTable var="vehicleTransactionList" value="#{viewCompanyManagedBean.vehicleTransactionList}">
<p:column headerText="#{messages.saptrn}">
<h:outputText value="#{vehicleTransactionList.vehicleTransactionId}" />
</p:column>
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{viewCompanyManagedBean.vehicleTransactionList}" var="newimage">
<p:graphicImage value="#{newimage.imageLocations}" styleClass="content" />
<div class="caption">#{newimage.imageLocations}</div>
</p:contentFlow>
</p:column>
</p:dataTable>
The error is on the 2nd column #{newimage.imageLocations}
Managed Bean:
package com.company.beans;
import com.company.entities.Company;
import com.company.entities.Scale;
import com.company.entities.ScaleMeasurement;
import com.company.entities.VehicleTransaction;
import com.company.services.db.ScaleMeasurementService;
import com.company.services.db.ScaleService;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.primefaces.event.SelectEvent;
import sunw.io.Serializable;
#SuppressWarnings("deprecation")
#ManagedBean
#ViewScoped
public class ViewCompanyManagedBean implements Serializable {
static Logger webRecySys = null;
static {
webRecySys = Logger.getLogger("com.company.webRecySys");
}
public ViewCompanyManagedBean() {
}
#PostConstruct
public void populateCompanyData() {
prepareData(new Date());
images = new ArrayList<String>();
for (int i = 1; i <= 7; i++) {
images.add("file_" + i + ".jpg");
}
}
#PostConstruct
public void onDateSelect(SelectEvent event) throws UnknownHostException {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String date = format.format(event.getObject());
try {
Date selectedDate = format.parse(date);
prepareData(selectedDate);
} catch (ParseException e) {
e.printStackTrace();
}
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "Date Selected",format.format(event.getObject())));
}
private void prepareData(Date forData) {
ScaleService ss = new ScaleService();
ScaleMeasurementService sms = new ScaleMeasurementService();
Scale right = ss.find(getRightScale());
Scale left = ss.find(getLeftScale());
this.measurements = sms.getMeasurementForScale(right,forData);
this.measurements.addAll(sms.getMeasurementForScale(left,forData));
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
this.fileName = "Shredder_Measurements_"+ sdf.format(forData);
for ( ScaleMeasurement s : measurements ) {
if ( s.getScale().getScaleId().equalsIgnoreCase(rightScale) ) {
this.rightScaleMeasurementSum += s.getMeasurement();
}
if ( s.getScale().getScaleId().equalsIgnoreCase(leftScale) ) {
this.leftScaleMeasurementSum += s.getMeasurement();
}
}
vehicleTransactionList = getVehicleTransactionList( sdf.format(forData) , (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest() );
}
private ArrayList<VehicleTransaction> getVehicleTransactionList(String fileDateFormat,HttpServletRequest request) {
ResourceBundle resourceb = ResourceBundle.getBundle("com.company.messages.image");
String imgRootPath = resourceb.getString("imagerootpath");
ArrayList<VehicleTransaction> images = new ArrayList<VehicleTransaction>();
String name = request.getLocalName();
if ( name != null ) {
if ( name.startsWith("0") ) {
name = "localhost";
}
}
else {
name = "localhost";
}
Scale scale = new ScaleService().find("01");
Company c = new ScaleService().getCompanyFromScale(scale);
String companyName = c.getCompanyName().trim().replace(" ", "_");
String URL = "http://"+name+":"+request.getLocalPort()+imgRootPath+"/"+companyName+"/"+fileDateFormat+"/";
ArrayList<String> picUrls = new ArrayList<String>();
Document doc;
try {
doc = Jsoup.connect(URL).get();
for (Element file : doc.select("a")) {
String urlPathToFile = file.attr("href");
String fileName = file.text();
if ( urlPathToFile.endsWith(".jpg") && fileName.endsWith(".jpg") ) {
String picUrl = "http://"+name+":"+request.getLocalPort()+imgRootPath+"/"+companyName+"/"+fileDateFormat+"/"+fileName;
picUrls.add(picUrl);
}
}
} catch (IOException e) {
webRecySys.logp(Level.WARNING, this.getClass().getCanonicalName() , "getAllImagesList", "Cannot get list of Images: "+e.getMessage() );
}
ArrayList<String> vehicleTransactionIdList = getVehicleTransactionIds(picUrls);
for ( String vehicleTransactionId : vehicleTransactionIdList) {
ArrayList<String> imagesForTransaction = getVehicleTransaction(vehicleTransactionId,picUrls);
VehicleTransaction s = new VehicleTransaction(imagesForTransaction, vehicleTransactionId);
images.add(s);
}
return images;
}
private ArrayList<String> getVehicleTransaction(String vehicleTransactionId,ArrayList<String> picUrls) {
ArrayList<String> imagesForTransaction = new ArrayList<String>();
for (String url : picUrls) {
if ( url.contains(vehicleTransactionId)) {
imagesForTransaction.add(url);
}
}
return imagesForTransaction;
}
private ArrayList<String> getVehicleTransactionIds(ArrayList<String> picUrls) {
ArrayList<String> vehicleTransactionIds = new ArrayList<String>();
for ( String pic : picUrls ) {
String vehicleTransactionId = pic.substring(pic.lastIndexOf("/")+1);
vehicleTransactionId = vehicleTransactionId.substring(0,vehicleTransactionId.indexOf("_"));
if ( !existsInArl(vehicleTransactionId,vehicleTransactionIds) ) {
vehicleTransactionIds.add(vehicleTransactionId);
}
}
return vehicleTransactionIds;
}
private boolean existsInArl (String s , ArrayList<String> arl) {
boolean exists = false;
for ( String c : arl ) {
if ( c.equalsIgnoreCase(s) ) {
exists = true;
}
}
return exists;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<ScaleMeasurement> getMeasurements() {
return measurements;
}
public void setMeasurements(List<ScaleMeasurement> measurements) {
this.measurements = measurements;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public String getRightScale() {
return rightScale;
}
public void setRightScale(String rightScale) {
this.rightScale = rightScale;
}
public String getLeftScale() {
return leftScale;
}
public void setLeftScale(String leftScale) {
this.leftScale = leftScale;
}
public int getRightScaleMeasurementSum() {
return rightScaleMeasurementSum;
}
public void setRightScaleMeasurementSum(int rightScaleMeasurementSum) {
this.rightScaleMeasurementSum = rightScaleMeasurementSum;
}
public int getLeftScaleMeasurementSum() {
return leftScaleMeasurementSum;
}
public void setLeftScaleMeasurementSum(int leftScaleMeasurementSum) {
this.leftScaleMeasurementSum = leftScaleMeasurementSum;
}
public ArrayList<VehicleTransaction> getVehicleTransactionList() {
return vehicleTransactionList;
}
public void setVehicleTransactionList(
ArrayList<VehicleTransaction> vehicleTransactionList) {
this.vehicleTransactionList = vehicleTransactionList;
}
// Used for Calendar
private Date date;
// Used for Shredder Measurements
private List<ScaleMeasurement> measurements = new ArrayList<ScaleMeasurement>();
private String fileName;
private String rightScale = "02";
private String leftScale = "03";
private int rightScaleMeasurementSum;
private int leftScaleMeasurementSum;
// Used for Pictures
private List<String> images;
private ArrayList<VehicleTransaction> vehicleTransactionList = new ArrayList<VehicleTransaction>();
private static final long serialVersionUID = 7449888248791054139L;
}
VehicleTransaction Pojo:
package com.company.entities;
import java.util.ArrayList;
public class VehicleTransaction {
public VehicleTransaction() {
}
public VehicleTransaction(ArrayList<String> imageLocations, String vehicleTransactionId) {
super();
this.imageLocations = imageLocations;
this.vehicleTransactionId = vehicleTransactionId;
}
public ArrayList<String> getImageLocations() {
return imageLocations;
}
public void setImageLocations(ArrayList<String> imageLocations) {
this.imageLocations = imageLocations;
}
public String getVehicleTransactionId() {
return vehicleTransactionId;
}
public void setVehicleTransactionId(String vehicleTransactionId) {
this.vehicleTransactionId = vehicleTransactionId;
}
private ArrayList<String> imageLocations;
private String vehicleTransactionId;
}
What's my mistake?
resolved - the right xhtml code is:
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{vehicleTransactionList.imageLocations}" var="images">
<p:graphicImage value="#{images}" styleClass="content" />
<div class="caption">#{images}</div>
</p:contentFlow>
</p:column>
Whereas the wrong code was:
<p:contentFlow value="#{viewCompanyManagedBean.vehicleTransactionList}" var="newimage">
<p:graphicImage value="#{newimage.imageLocations}" styleClass="content" />
<div class="caption">#{newimage.imageLocations}</div>

Get String in list in adapter (gson)

I have a problem with my adapter. I already succeeded to display some informations from my JSON (codeLieu and libelle) that looks like this:
[
{
"codeLieu": "OTAG",
"libelle": "50 Otages",
"distance": null,
"ligne": [
{
"numLigne": "2"
},
{
"numLigne": "C2"
},
{
"numLigne": "12"
},
{
"numLigne": "23"
}
]
},
...
]
Here is my model:
package material.romain.com.projentreprise.Adapter;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class Response implements Serializable{
private String codeLieu;
private String libelle;
private String distance;
private List<LigneEntities> ligne;
public String getCode() {
return codeLieu;
}
public void setCode(String codeLieu) {
this.codeLieu = codeLieu;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public List<LigneEntities> getLigne() {return ligne;}
public void setLigne(List<LigneEntities> ligne) {
this.ligne = ligne;
}
public static class LigneEntities {
private String numLigne;
public String getLigne() {
return numLigne;
}
public void setLigne(String numLigne) {
this.numLigne = numLigne;
}
}
}
And finally this is my adapter :
package material.romain.com.projentreprise.Adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.iconics.IconicsDrawable;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import material.romain.com.projentreprise.R;
import material.romain.com.projentreprise.Util.CircularTextView;
import material.romain.com.projentreprise.Util.ColorLigne;
public class ListAdapter extends BaseAdapter implements Filterable {
private ArrayList<Response> arret;
private Context context;
private LayoutInflater inflater;
private MyFilter mFilter;
private ArrayList<Response> mSearchArret;
public ListAdapter(Context mContext, ArrayList<Response> mArretItem) {
this.context = mContext;
this.arret = mArretItem;
this.mSearchArret = mArretItem;
getFilter();
}
#Override
public int getCount() {
return mSearchArret.size();
}
#Override
public Object getItem(int position) {
return mSearchArret.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Response item = (Response) getItem(position);
ColorLigne.ViewHolder holder = null;
if (convertView == null) {
holder = new ColorLigne.ViewHolder();
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.each_list_item, parent, false);
holder.circleImage = (CircleImageView) convertView.findViewById(R.id.circleView);
holder.textArret = (TextView) convertView.findViewById(R.id.tvListArret);
holder.circle = (CircularTextView) convertView.findViewById(R.id.tvArretColor);
convertView.setTag(holder);
} else {
holder = (ColorLigne.ViewHolder) convertView.getTag();
}
Drawable color = new ColorDrawable(ContextCompat.getColor(context, R.color.tanVert));
Drawable image = new IconicsDrawable(context).icon(FontAwesome.Icon.faw_bus).color(Color.WHITE).sizeDp(48).paddingDp(10);
LayerDrawable ld = new LayerDrawable(new Drawable[]{color, image});
holder.circleImage.setImageDrawable(ld);
holder.textArret.setText(item.getLibelle());
return convertView;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new MyFilter();
}
return mFilter;
}
class MyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (prefix != null && prefix.length() > 0) {
ArrayList<Response> tempList = new ArrayList<>();
for (Response value : arret) {
if (value.getLibelle().toLowerCase().contains(prefix.toString().toLowerCase())) {
tempList.add(value);
}
}
results.count = tempList.size();
results.values = tempList;
} else {
results.count = arret.size();
results.values = arret;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
try {
mSearchArret = (ArrayList<Response>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And I would like to get strings from "ligne" but it's in a list and I don't know how to access it. My goal is to put the strings into a circleTextView.
Edit:
I tried this in getView method
Response item = getItem(position);
for(Response value: arret){
value = item;
String ligneItem = value.getLigne().toString();
ColorLigne.setColorLigne(ligneItem, holder, context);
holder.circle.setText(ligneItem);
holder.circle.setStrokeWidth(0);
}
Add below method to your Response.java
public String getItems() {
StringBuilder builder = new StringBuilder();
for (LigneEntities entity : getLigne()) { //loop through every item from the list
builder.append(entity.getLigne() + ","); //add to StringBuilder
}
builder.replace(builder.length() - 1, builder.length(), "");//remove last ,(semicolon)
return builder.toString();
}
setting to your CircleTextView
holder.circle.setText(item.getItems());

Can't parse JSON because of recursive relationships when using #RelatedToVia

I am new to Neo4j and I want to connect a node (Person) with a node (Asset) but also, store the time that this connection has been created. I figured out that I have to use #RelatedtoVia annotation. I have followed the Spring cineasts tutorial ([https://github.com/spring-projects/spring-data-neo4j/tree/master/spring-data-neo4j-examples/cineasts][1] ) Although, everything works fine as far as the tests and the database population are concerned, I get weird results at the REST service. Here is my code:
Node Person
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.*;
import org.springframework.data.neo4j.template.Neo4jOperations;
import java.util.*;
#NodeEntity
public class Person {
#GraphId
Long id;
#Indexed
private String displayName;
#Indexed(unique = true, failOnDuplicate = true)
private Long personId;
private String firstName;
private String lastName;
private Date birthday;
private String aboutMe;
private String thumbnailURL;
private String email;
private enum gendertypes {male, female, other};
private gendertypes gender;
private String[] languages;
private boolean active;
public static final String CONSUMED = "CONSUMED";
//empty & full constructor
//getters&setters
#RelatedToVia(type = "CONSUMED", elementClass = ConsumedDate.class)
#Fetch
Iterable<ConsumedDate> consumedDates;
public ConsumedDate consumedDate(Neo4jOperations template, Asset asset, Date timestamp) {
final ConsumedDate consumedDate = template.createRelationshipBetween(this, asset, ConsumedDate.class, CONSUMED, false).consumedDate(timestamp);
return template.save(consumedDate);
}
public Collection<ConsumedDate> getConsumedDates() {
return IteratorUtil.asCollection(consumedDates);
}
}
Node Asset
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import static org.neo4j.graphdb.Direction.INCOMING;
#NodeEntity
public class Asset {
#GraphId
private Long id;
#Indexed(unique=true, failOnDuplicate = true)
private Long assetId;
private String description;
private String type;
private String[] tags;
public Asset() {}
public Asset(Long assetId, String description, String type, String[] tags) {
this.assetId = assetId;
this.description = description;
this.type = type;
this.tags = tags;
}
public Long getAssetId() {return assetId; }
public void setAssetId(Long assetId) {
this.assetId = assetId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String[] getTags() {
return tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
#RelatedTo(type = "CONSUMED", direction = INCOMING)
Set<Person> persons;
#RelatedToVia(type="CONSUMED", elementClass=ConsumedDate.class, direction=INCOMING)
#Fetch
Iterable<ConsumedDate> consumedDates;
public Collection<Person> getPersons() {
return persons;
}
public Collection<ConsumedDate> getConsumedDates() {
Iterable<ConsumedDate> allConsumedDates = consumedDates;
return allConsumedDates == null ? Collections.<ConsumedDate>emptyList() : IteratorUtil.asCollection(allConsumedDates);
}
#Override
public String toString() {
return "An asset with ID " + assetId + " description " + description + " type " + type;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Asset asset = (Asset) o;
if (id == null) return super.equals(o);
return id.equals(asset.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
Relationship Entity ConsumedDate
import org.springframework.data.neo4j.annotation.EndNode;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.RelationshipEntity;
import org.springframework.data.neo4j.annotation.StartNode;
import java.util.Date;
#RelationshipEntity(type = "CONSUMED")
public class ConsumedDate {
#GraphId
Long id;
#EndNode
Asset asset;
#StartNode
Person person;
Date timestamp;
public ConsumedDate consumedDate(Date timestamp){
this.timestamp=timestamp;
return this;
}
public Asset getAsset() {
return asset;
}
public Person getPerson() {
return person;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ConsumedDate consumedDate = (ConsumedDate) o;
if (id == null) return super.equals(o);
return id.equals(consumedDate.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
Controller
import gr.ntua.sam.context.neo4j.AssetRepository;
import gr.ntua.sam.context.neo4j.LocationRepository;
import gr.ntua.sam.context.neo4j.PersonRepository;
import gr.ntua.sam.context.resources.*;
import com.wordnik.swagger.annotations.ApiOperation;
import org.neo4j.graphdb.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.support.Neo4jTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.util.*;
import java.util.List;
#RestController
#Configuration
#EnableNeo4jRepositories
public class ContextController {
#Autowired
Neo4jTemplate template;
#Autowired
AssetRepository assetRepository;
#Autowired
PersonRepository personRepository;
#ApiOperation(value = "Show the available assets", response = Asset.class)
#RequestMapping(value = "/asset", method = RequestMethod.GET)
public ResponseEntity<List<Asset>> getAssets() throws NotFoundException {
List<Asset> results = assetRepository.all();
return new ResponseEntity<List<Asset>>(results, HttpStatus.OK);
}
#ApiOperation(value = "Create a new asset",response = Asset.class)
#RequestMapping(value = "/asset", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Asset> saveAsset(#RequestBody Asset asset) {
Asset savedAsset = assetRepository.save(asset);
return new ResponseEntity<Asset>(savedAsset, HttpStatus.CREATED);
}
//Persons
#ApiOperation(value = "Get a list of all the available Persons")
#RequestMapping(value = "/person", method = RequestMethod.GET)
public ResponseEntity<List<Person>> getPersons() throws ParseException {
List<Person> results = personRepository.all();
return new ResponseEntity<List<Person>>(results, HttpStatus.OK);
}
#ApiOperation(value = "Creates a new Person node to store information about a user", response = Person.class)
#RequestMapping(value = "/person", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Person> savePerson(#RequestBody Person person) {
Person savedPerson = personRepository.save(person);
return new ResponseEntity<Person>(savedPerson, HttpStatus.CREATED);
}
#ApiOperation(value = "Creates relationship between a Person and an Asset")
#RequestMapping(value = "/person/{personId}/consumes/", method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Void> consumes(#PathVariable("personId") Long personId, #RequestBody LinkedAsset linkedAsset) {
Person person = personRepository.findByPersonId(personId);
List<Long> assetIds = linkedAsset.getAssetIDs();
for (Long assetId : assetIds) {
Asset currentAsset = assetRepository.findByAssetId(assetId);
Date date= linkedAsset.getTimestamp();
ConsumedDate consumedDate= person.consumedDate(template,currentAsset,date);
template.save(consumedDate);
}
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
The problem is that when I create a relationship between a Person and an Asset, along with a timestamp (I have created the class LinkedAsset which serves as a JSON input model and has nothing to do with Neo4j) and then try to get through REST the person or the asset, all I get is something definitely not JSON with the person or the asset appearing infinite times. Is there a way to face this problem?
Thank you in advance!