GWT mix two objects in my TreeViewModel - java

I Have this Model :
1) Team :
public class Team {
private String nom ;
private Employee leader ;
private List<Employee> members = new ArrayList<Employee>();
private List<Person> persons = new ArrayList<Person>();
public Team() {
}
public Team(String nom, Employee leader, List<Employee> members, List<Person> persons) {
this.nom = nom;
this.leader = leader;
this.members = members;
this.persons = persons;
}
public Team(String nom) {
this.nom = nom;
}
public Employee addEmployee (Employee employee) {
members.add(employee);
return employee;
}
public Person addPerson (Person person) {
persons.add(person);
return person;
}
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Employee getLeader() {
return leader;
}
public void setLeader(Employee leader) {
this.leader = leader;
}
public List<Employee> getMembers() {
return members;
}
public void setMembers(List<Employee> members) {
this.members = members;
}
#Override
public String toString() {
return "Team{" +
"nom='" + nom + '\'' +
", leader=" + leader +
", members=" + members +
'}';
}
public Team(int i){
this.setNom("team"+i);
this.setLeader(new Employee("MoMo" + i, "dd" + i));
this.addEmployee(new Employee("mehdi" + i, "dd" + i));
this.addEmployee(new Employee("albert" + i+1,"dd"+ i));
this.addEmployee(new Employee("lolo" + i+2,"dd"+ i));
this.addPerson(new Person("Person" + i));
this.addPerson(new Person("Person" + i+1 ));
this.addPerson(new Person("Person" + i+2 ));
}
2)
public class Employee {
private String cin;
private String nom;
private String prenom;
3)
public class Person {
private String address;
private String name;
public Person(){
}
public Person(String name) {
this.name = name;
}
public Person(String name, String address) {
this.name = name;
this.address = address;
}
public String getAddress() {
return address;
}
public String getName() {
return name;
}
}
I want to build a GWT TreeViewModel like the following :
Team => (i want to have my list of persons and my list of employees mixed)
Here is my TreeViewModel
public class EmployeeTreeModel implements TreeViewModel {
private final List<Team> teamList;
private final SingleSelectionModel<Employee> selectionModel
= new SingleSelectionModel<Employee>();
public EmployeeTreeModel() {
teamList = new ArrayList<Team>();
{
for (int i = 0; i < 5 ; i++) {
teamList.add(new Team(i) );
}
}
}
#Override
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
ListDataProvider<Team> dataProvider
= new ListDataProvider<Team>(teamList);
Cell<Team> cell = new AbstractCell<Team>() {
#Override
public void render(Context context, Team value, SafeHtmlBuilder sb) {
if (value != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(value.getNom());
}
}
};
return new DefaultNodeInfo<Team>(dataProvider, cell);
}
else if (value instanceof Team) {
ListDataProvider<Employee> dataProvider
= new ListDataProvider<Employee>(
((Team) value).getMembers());
Cell<Employee> cell =
new AbstractCell<Employee>() {
#Override
public void render(Context context, Employee employee, SafeHtmlBuilder sb) {
if (employee != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(employee.getNom());
}
}
};
return new DefaultNodeInfo<Employee>(dataProvider, cell,selectionModel, null);
}
return null;
}
#Override
public boolean isLeaf(Object o) {
if (o instanceof Employee) {
return true;
}else if(o instanceof Person){
return true;
}
else return false;
}
}
in my actual code I can't mix Employees data and Person's Data because two different objects
Any way to do that ?
A listDataProvider who brings two Objects maybe ?

Related

Age filter in Java with ArrayList

I want to make a method that tells me who is the oldest person in the ArrayList and who is the youngest person. The method will receive the arraylist that i want to apply the method, i have 3 in my code, each one is an contact list.
The method is suppose to return the name of the person, but i don't know how to do it. Familia, Profissional and Amigos are my arraylists and "idade" = age and "nome" = name.
package com.company;
public class Contato {
public String nome;
public int idade;
public String sexo;
public String profissao;
public String telefone;
public String email;
public Contato(String nome, int idade, String sexo, String profissao, String telefone, String email) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
this.profissao = profissao;
this.telefone = telefone;
this.email = email;
}
#Override
public String toString() {
return "" +
nome + ',' +
idade + " anos de idade, " +
"do sexo " + sexo + ',' +
profissao + ',' +
" telefone nº " + telefone + ", " +
"e-mail:" + email;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.company;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GestaoContatos extends Contato {
ArrayList<Contato> Familia = new ArrayList();
ArrayList<Contato> Amigos = new ArrayList();
ArrayList<Contato> Profissional = new ArrayList();
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
}
public void adicionaContato(String nomeAgenda, Contato contato) {
if( nomeAgenda == "Familia"){
Familia.add(contato);
} else
if(nomeAgenda == "Amigos"){
Amigos.add(contato);
} else
if(nomeAgenda == "Profissional") {
Profissional.add(contato);
} else
System.out.println("Indispnível");
}
public void eliminaContato(String nomeContato) {
for(int i = 0; i < Familia.size(); i++) {
if(getFamilia().contains(nomeContato)) {
Familia.remove(nomeContato);
}
}
}
public void printaLista(String nomeAgenda){
if(nomeAgenda.equals("Familia")) {
Familia.forEach(System.out::println);
}
if(nomeAgenda.equals("Amigos")) {
Amigos.forEach(System.out::println);
}
if(nomeAgenda.equals("Profissional")) {
Profissional.forEach(System.out::println);
}
else {
throw new RuntimeException("Opcao invalida");
}
}
public void tooString() {
var contatos = new ArrayList<Contato>();
Familia.forEach(it -> contatos.add(it));
Amigos.forEach(it -> contatos.add(it));
Profissional.forEach(it -> contatos.add(it));
System.out.println(contatos.toString());
}
public void olderPerson(String nomeAgenda){
int i = 0;
if (nomeAgenda.equals("Amigos")) {
for (i = 0; Familia.size(); i++) {
Familia.stream().filter();
}
}
}
public void geraListaBinaria() throws IOException {
var file = new File("C:\\Users\\Jorge Luiz\\Desktop\\contatos.txt");
var writer = new FileWriter(file.getName());
writer.write(this.getProfissional().toString());
writer.write(this.getFamilia().toString());
writer.write(this.getProfissional().toString());
writer.close();
}
public ArrayList<Contato> getFamilia() {
return Familia;
}
public void setFamilia(ArrayList<Contato> familia) {
Familia = familia;
}
public ArrayList<Contato> getAmigos() {
return Amigos;
}
public void setAmigos(ArrayList<Contato> amigos) {
Amigos = amigos;
}
public ArrayList<Contato> getProfissional() {
return Profissional;
}
public void setProfissional(ArrayList<Contato> profissional) {
Profissional = profissional;
}
}
If you want to return oldest person in one list:
public Contato oldestPerson(String nomeAgenda){
return Familia.stream()
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
For all lists you can do:
public Contato oldestPerson(){
return Stream.of(Familia, Amigos, Profissional)
.flatMap(Collection::stream) // flatting to one long stream
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade))
.get();
}
EDIT
Based on the comment, we should change a couple of things to achieve what you want. First, we should define a Map<String, List<Contato>> and populate it in the constructor:
private Map<String, List<Contato>> contatoGroups;
private static final String familiaKey = "Familia";
private static final String amogisKey = "Amigos";
private static final String profissionalKey = "Profissional";
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
contatoGroups.put(familiaKey, new ArrayList<>());
contatoGroups.put(amogisKey, new ArrayList<>());
contatoGroups.put(profissionalKey, new ArrayList<>());
}
(Consider using enum instead of String as key in the map)
Then wherever you want to get a group, for example: Familia, you should do:
List<Contato> contatoes = contatoGroups.get(familiaKey);
And then we should change the oldestPerson() like this:
public Contato oldestPerson(String nomeAgenda){ // nomeAgenda could be "Familia", "Amigos"...
List<Contato> selectedGroup = contatoGroups.get(nomeAgenda);
return selectedGroup.stream()
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}

Using polymorphism to print out string occurrences

I having trouble figuring out how to print out how many times "Dr" titles appear in my array objects in my tester program as they contain more than one string. Is using the equals class the best way to approach this?
Note: I am using inheritance and polymorphism.
public class Driver {
public static void main(String[ ] args) {
Person[] persons = new Person[5];
persons[0] = new Person("John Smith");
persons[1] = new Person();
persons[2] = new TitledPerson("Rowan Bean", "Mr");
persons[3] = new TitledPerson("Phil McGraw", "Dr");
persons[4] = new TitledPerson("Hugo Strange", "Dr");
System.out.println("Person 3 and 4 are equal: " + persons[2].equals(persons[3]));
System.out.println();
String search = "Dr";
int counter = 0;
for(int i = 0; i < persons.length; i++) {
System.out.println(persons[i]);
if(persons[i] instanceof TitledPerson) {
if(persons[i].equals(search)) {
counter++;
}
}
}
System.out.println();
System.out.println("There are " + counter + " 'Dr' titles listed.");
}
}
Person Class:
public class Person {
private String name;
private final static String DEFAULT_NAME = "N/A";
public Person() {
this(DEFAULT_NAME);
}
public Person(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return "Name: " + name;
}
public boolean equals(Object obj) {
if(obj instanceof Person) {
Person otherPerson = (Person) obj;
return name.equalsIgnoreCase(otherPerson.getName());
} else {
return false;
}
}
}
TitledPerson Class:
public class TitledPerson extends Person {
private String title;
public TitledPerson() {
}
public TitledPerson(String name, String title) {
super(name);
this.title = title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
String parentString = super.toString();
parentString += ", " + title;
return parentString;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof TitledPerson) {
TitledPerson otherPers = (TitledPerson) obj;
return super.equals(obj) && this.title.equalsIgnoreCase(otherPers.title);
} else {
return false;
}
}
}
Change to using getTitle from your TitledPerson class while comparing with the search keyword.
if(((TitledPerson)persons[i]).getTitle().equals(search)) {
counter++;
}
The equals method in TitledPerson calls super class equals which will cause the name and title must be the same for equality.
I think the correct implementation of equals in TitledPerson should be
#Override
public boolean equals(Object obj) {
if(obj instanceof TitledPerson) {
TitledPerson otherPers = (TitledPerson) obj;
return this.title.equalsIgnoreCase(otherPers.title);
} else {
return false;
}
}
you seem to do this :
if(persons[i] instanceof TitledPerson) {
if(persons[i].equals(search)) {
counter++;
}
person is object with a name and a title
search on the other hand, is a string
so you need to do this :
if(persons[i] instanceof TitledPerson) {
if(persons[i].title.equals(search)) {
counter++;
}

Created add() method to insert objects into an array and all i get are null values

this is a class called Doglist to add the object to an array.
public class DogList {
private int numItems;
private DogItem[] dogListArray;
private int position;
DogList () {
numItems=0;
position = 0;
dogListArray = new DogItem[10];
}
public void add (DogItem item) {
dogListArray[numItems++]= new DogItem(item.getName(),
item.getBreed(),
item.getWeight(),
item.getOwner1(),
item.getOwner2()
);
}
public String toString() {
String result = "";
for (int i=0; i<numItems; i++) {
result += dogListArray[i].toString() + "\n";
}
return result;
}
public DogItem searchForDogItem (DogItem gi) {
System.out.println("Here is your obj value: " + gi );
return null;
}//This is the one im having trouble with.
}
I have all the setters and getters in the DogItem class.
and this is from the UI where i get the dog info(name, breed, weight, owners1&2 names)
public void searchForItem (String name ) {
DogItem gi = new DogItem (name);
gi = gl.searchForDogItem(gi);
if (gi==null) {
msgTextField.setText("Dog Not Found");
} else {
nameTextField.setText(String.valueOf(gi.getName()));
breedTextField.setText(String.valueOf(gi.getBreed()));
weightTextField.setText(String.valueOf(gi.getWeight()));
owner1TextField.setText(String.valueOf(gi.getOwner1()));
owner2TextField.setText(String.valueOf(gi.getOwner2()));
}
}
Ill try and clear things up as i go.
this is the output i get
Here is your obj value: null null 0.0 null null
Ok so here is what it probably should look like instead. Just from what I saw wrong already. However you'd probably want to override the toString() method of DogItem.
Main method example of this:
public class Main {
public static void main(String[] args) {
DogItem dogItem = new DogItem("Spot", "Dalmation", "45", "Bob", "Sandy");
DogItem.add(dogItem);
DogItem result = DogItem.searchForItem("Spot");
if (result == null) {
System.out.println("Dog not found");
// GUI error output goes here
} else {
System.out.println("Here is your obj value: " + result);
// Where your GUI stuff goes
}
}
}
DogItem example of this:
public class DogItem {
private static DogItem[] dogListArray = new DogItem[100];
private static int numItems = 0;
private String name;
private String breed;
private String weight;
private String owner1;
private String owner2;
public DogItem(String name, String breed, String weight, String owner1, String owner2) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owner1 = owner1;
this.owner2 = owner2;
}
public static void add(DogItem dogItem) {
dogListArray[numItems++] = dogItem;
}
public static DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogListArray) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
#Override
public String toString() {
String result = name + ", " + breed + ", " + weight + ", " + owner1 + " " + owner2;
return result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOwner1() {
return owner1;
}
public void setOwner1(String owner1) {
this.owner1 = owner1;
}
public String getOwner2() {
return owner2;
}
public void setOwner2(String owner2) {
this.owner2 = owner2;
}
}
These would be recommended changes from me though:
private static ArrayList<String> owners;
private static ArrayList<DogItem> dogsList;
public DogItem(String name, String breed, String weight, String owner) {
this.name = name;
this.breed = breed;
this.weight = weight;
this.owners.add(owner);
}
public void init() {
owners = new ArrayList<String>();
dogsList = new ArrayList<DogItem>();
}
public void addDog(DogItem dogItem) {
dogsList.add(dogItem);
}
public DogItem searchForItem(String name) {
DogItem dogItem = null;
for (DogItem result : dogsList) {
if (result != null) {
if (result.getName() == name) {
dogItem = result;
}
}
}
return dogItem;
}
public void addOwner(String owner) {
owners.add(owner);
}
public String getOwner() {
return owners.get(owners.size() - 1);
}

Why is my code not displaying these 2 Arraylists?

I need to display an ArrayList with a list of college degree/s that an individual may have.
In another ArrayList, I need display the list of individual/s that meet the requirement of college degree that a company is asking.
Tried a system.out inside the loops and it's not even accessing the for loops.
*The 2 methods with the for loops are at the end of this class
import java.util.ArrayList;
public class RecruitingCompany {
private String companyName;
private int phoneNumber;
private String address;
private ArrayList<CollegeDegree> collegeDegreeList = new ArrayList<>();
private ArrayList<Candidate> candidateList = new ArrayList<>();
private Candidate candidate;
private Requirement academicDegree;
public RecruitingCompany(){
/*main constructor*/
}
public RecruitingCompany(String companyName, int phoneNumber, String address){
this.companyName = companyName;
this.phoneNumber = phoneNumber;
this.address = address;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public ArrayList<CollegeDegree> getCollegeDegreeList() {
return collegeDegreeList;
}
public void setCollegeDegreeList(ArrayList<CollegeDegree> collegeDegreeList) {
this.collegeDegreeList = collegeDegreeList;
}
public ArrayList<Candidate> getCandidateList() {
return candidateList;
}
public void setCandidateList(ArrayList<Candidate> candidateList) {
this.candidateList = candidateList;
}
public Candidate getCandidate() {
return candidate;
}
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
}
public Requirement getAcademicDegree() {
return academicDegree;
}
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
}
public String showCandidateCollegeDegrees(){
String degree = "Candidato: " + candidate.getName() + "\n";
for (CollegeDegree cd: this.collegeDegreeList){
degree += cd.toString();
}
return degree;
}
public String selectByCollegeDegree(){
String person = "Título: " + academicDegree.getDegree() + "\n";
for (Candidate c: this.candidateList){
person += c.toString();
}
return person;
}
}
The Tester class
public class Tester {
public static void main(String[] args) {
AvailableJob availableJob = new AvailableJob(2005, 2011, "Contador", 444464444, "Metalco", "del poste de luz, 50m oeste", 550.000);
Candidate candidate = new Candidate("Asdrubal", 888888888, "Asdrubal#yahoo.com", "Bachillerato");
CollegeDegree collegeDegree = new CollegeDegree("Bachillerato Administracion", 2003, "Universidad Aguila Calva");
RecruitingCompany recruitingCo = new RecruitingCompany();
Requirement requirement = new Requirement("Bachillerato", 4);
recruitingCo.setCandidate(candidate);
recruitingCo.setAcademicDegree(requirement);
availableJob.setRequirement(requirement);
System.out.println(recruitingCo.showCandidateCollegeDegrees());
System.out.println();
System.out.println(recruitingCo.selectByCollegeDegree());
System.out.println();
System.out.println(availableJob.showRequirement());
//System.out.print(recruitingCo.getCandidateList());
}
}
You are not adding the new candidate or degree to the arraylists. Change the following methods it will work,
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
collegeDegreeList.add(academicDegree);
}
and
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
candidateList.add(candidate);
}
Now when you set a new Candidate object or CollegeDegree object it will be automatically added to the lists.
In your code, you need to do some changes:
setCollegeDegreeList(), setCandidateList() and setCandidate() methods
should be changed to addCollegDegree() and addCandidate()
recruitingCo.setCandidate(candidate) should be replaced to
recruitingCo.addCandidate(candidate);
Need to add recruitingCo.addCollegeDegree(collegeDegree); in main();
And you can get following code:
import java.util.ArrayList;
public class RecruitingCompany {
private String companyName;
private int phoneNumber;
private String address;
private ArrayList<CollegeDegree> collegeDegreeList = new ArrayList<>();
private ArrayList<Candidate> candidateList = new ArrayList<>();
private Requirement academicDegree;
public RecruitingCompany(){
/*main constructor*/
}
public RecruitingCompany(String companyName, int phoneNumber, String address){
this.companyName = companyName;
this.phoneNumber = phoneNumber;
this.address = address;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public ArrayList<CollegeDegree> getCollegeDegreeList() {
return collegeDegreeList;
}
public ArrayList<Candidate> getCandidateList() {
return candidateList;
}
public void addCollegeDegree(CollegeDegree collegeDegree) {
this.collegeDegreeList.add(collegeDegree);
}
public void addCandidate(Candidate candidate) {
this.candidateList.add(candidate);
}
public Requirement getAcademicDegree() {
return academicDegree;
}
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
}
public String showCandidateCollegeDegrees(){
String degree = "Candidato: " + candidate.getName() + "\n";
for (CollegeDegree cd: this.collegeDegreeList){
degree += cd.toString();
}
return degree;
}
public String selectByCollegeDegree(){
String person = "Título: " + academicDegree.getDegree() + "\n";
for (Candidate c: this.candidateList){
person += c.toString();
}
return person;
}
}
Tester:
public class Tester {
public static void main(String[] args) {
AvailableJob availableJob = new AvailableJob(2005, 2011, "Contador", 444464444, "Metalco", "del poste de luz, 50m oeste", 550.000);
Candidate candidate = new Candidate("Asdrubal", 888888888, "Asdrubal#yahoo.com", "Bachillerato");
CollegeDegree collegeDegree = new CollegeDegree("Bachillerato Administracion", 2003, "Universidad Aguila Calva");
RecruitingCompany recruitingCo = new RecruitingCompany();
Requirement requirement = new Requirement("Bachillerato", 4);
recruitingCo.addCandidate(candidate);
recruitingCo.addСollegeDegree(collegeDegree);
recruitingCo.setAcademicDegree(requirement);
availableJob.setRequirement(requirement);
System.out.println(recruitingCo.showCandidateCollegeDegrees());
System.out.println();
System.out.println(recruitingCo.selectByCollegeDegree());
System.out.println();
System.out.println(availableJob.showRequirement());
//System.out.print(recruitingCo.getCandidateList());
}
}

No results querying a Neo4j database using Spring Data Neo4j repositories

I have created a graph database as hierarchical tree as a result of converting a MySQL database in another Neo4j database. The transformation worked fine.
On the top level exist a node labeled as Root, on the second level are the countries labeled as Country. Every country has cities that is the third level labeled as City. And down for every city there are a subset of addresses labeled as Address. The relationships should be,
(root)-[:IS_ROOT]->(country)-[:HAS_CITY]->(city)-[:HAS_ADDRESS]->(address)
Later, using Spring Data Neo4j repositories, I tried to query the database with no result.
For the MySQL database I use JDBC, and for the Neo4j database I use Spring Data Neo4j as mentioned before.
This is the controller I use to create the Neo4j database,
#Controller("importer")
public class SakilaDbImportController {
private static final Logger logger = LoggerFactory.getLogger(SakilaDbImportController.class);
#Autowired
#Lazy
AddressNeoRepository addressRepo;
#Autowired
#Lazy
CityNeoRepository cityRepo;
#Autowired
#Lazy
CountryNeoRepository countryRepo;
#Autowired
#Lazy
RootRepository rootRepo;
#Autowired
Neo4jTemplate template;
#Autowired
SakilaDbApiClient client;
public SakilaDbImportController() {
}
#Transactional
public RootNeo createGraphDb() {
RootNeo root = doImportRoot();
return root;
}
#Transactional
public RootNeo importRoot() {
return doImportRoot();
}
private RootNeo doImportRoot() {
logger.debug("Importing root");
RootNeo root = new RootNeo("1", "Root");
root.addLabel("_Root");
//root.addLabel("Root");
System.out.println("root created " + root);
List<Country> data = client.readAllCountries();
if (data.isEmpty()) throw new RuntimeException("Data for Root not found.");
Map<CountryNeo, RoleIsRoot> roles = relateCountriesToRoot(root, data);
//template.save(root);
Set<CountryNeo> set = roles.keySet();
for(Iterator<CountryNeo> it = set.iterator(); it.hasNext();) {
root.isRoot(it.next());
}
rootRepo.save(root);
/*
for(RoleIsRoot role: roles){
template.save(role);
}
*/
return root;
}
private Map<CountryNeo, RoleIsRoot> relateCountriesToRoot(RootNeo root, List<Country> data) {
Map<CountryNeo, RoleIsRoot> roles = new HashMap<CountryNeo, RoleIsRoot>();
for (Country country : data) {
if(country.getCountry().equalsIgnoreCase("Canada"))
continue;
CountryNeo countryNeo = doImportCountryNeo(country);
RoleIsRoot role = root.isRoot(countryNeo, "IS_ROOT_OF");
System.out.println("RoleIsRoot: " + role);
roles.put(countryNeo, role);
}
return roles;
}
#Transactional
public CountryNeo importCountryNeo(Country country) {
return doImportCountryNeo(country);
}
private CountryNeo doImportCountryNeo(Country country) {
logger.debug("Importing countryNeo");
CountryNeo countryNeo = new CountryNeo(generateIndex(country.getCountryId()), country.getCountry());
countryNeo.addLabel("_Country");
//countryNeo.addLabel("Country");
System.out.println("new country: " + countryNeo);
List<City> data = client.readAllCitiesByCountry(country);
if (data.isEmpty()) throw new RuntimeException("Data for Country not found.");
Map<CityNeo, RoleHasCity> roles = relateCitiesToCountry(countryNeo, data);
Set<CityNeo> set = roles.keySet();
for(Iterator<CityNeo> it = set.iterator(); it.hasNext();) {
countryNeo.hasCity(it.next());
}
countryRepo.save(countryNeo);
/*
template.save(countryNeo);
for(RoleHasCity role: roles){
template.save(role);
}
*/
return countryNeo;
}
private Map<CityNeo, RoleHasCity> relateCitiesToCountry(CountryNeo countryNeo, List<City> data) {
Map<CityNeo, RoleHasCity> roles = new HashMap<CityNeo, RoleHasCity>();
for (City city : data) {
CityNeo cityNeo = doImportCityNeo(city);
RoleHasCity role = countryNeo.hasCity(cityNeo, "IS_CITY_FROM");
System.out.println("RoleHasCity: " + role);
roles.put(cityNeo, role);
}
return roles;
}
#Transactional
public CityNeo importCityNeo(City city) {
return doImportCityNeo(city);
}
private CityNeo doImportCityNeo(City city) {
logger.debug("Importing cityNeo");
CityNeo cityNeo = new CityNeo(generateIndex(city.getCityId()), city.getCity());
cityNeo.addLabel("_City");
//cityNeo.addLabel("City");
System.out.println("new city: " + cityNeo);
List<Address> data = client.readAllAddressesByCity(city);
if (data.isEmpty()) throw new RuntimeException("Data for City not found.");
Map<AddressNeo, RoleHasAddress> roles = relateAddressesToCity(cityNeo, data);
Set<AddressNeo> set = roles.keySet();
for(Iterator<AddressNeo> it = set.iterator(); it.hasNext();) {
cityNeo.hasAddress(it.next());
}
cityRepo.save(cityNeo);
/*
template.save(cityNeo);
for(RoleHasAddress role: roles){
template.save(role);
}
*/
return cityNeo;
}
private Map<AddressNeo, RoleHasAddress> relateAddressesToCity(CityNeo cityNeo, List<Address> data) {
Map<AddressNeo, RoleHasAddress> roles = new HashMap<AddressNeo, RoleHasAddress>();
for(Address address: data) {
AddressNeo addressNeo = doImportAddressNeo(address);
RoleHasAddress role = cityNeo.hasAddress(addressNeo, "IS_ADDRESS_IN");
System.out.println("RoleHasAddress: " + role);
roles.put(addressNeo, role);
}
return roles;
}
#Transactional
public AddressNeo importAddressNeo(Address address) {
return doImportAddressNeo(address);
}
private AddressNeo doImportAddressNeo(Address address) {
logger.debug("Importing addressNeo");
if (address == null) throw new RuntimeException("Address not found.");
AddressNeo addressNeo = new AddressNeo(generateIndex(address.getAddressId()), address.getAddress());
addressNeo.addLabel("_Address");
//addressNeo.addLabel("Address");
System.out.println("new address: " + addressNeo);
addressNeo.setPostalCode(address.getPostalCode());
addressRepo.save(addressNeo);
/*
template.save(addressNeo);
*/
return addressNeo;
}
private String generateIndex(int index) {
return String.valueOf(index);
}
}
And this is the service that, using the repositories, does the queries,
#Service
public class SakilaDbQueries {
#Autowired
#Lazy
AddressNeoRepository addressRepo;
#Autowired
#Lazy
CityNeoRepository cityRepo;
#Autowired
#Lazy
CountryNeoRepository countryRepo;
#Autowired
#Lazy
RootRepository rootRepo;
public SakilaDbQueries() {
}
public List<String> findAllCountryNames() {
CountryNeoData names = countryRepo.findAllCountryNames();
Collection<String> collection = names.getCountries();
List<String> list = new ArrayList<String>();
for(Iterator<String> it = collection.iterator(); it.hasNext(); ) {
list.add(it.next());
}
return list;
}
public List<CountryNeo> findAllCountries() {
Result<CountryNeo> result = countryRepo.findAll();
List<CountryNeo> list = new ArrayList<CountryNeo>();
for(Iterator<CountryNeo> it = result.iterator(); it.hasNext(); ) {
list.add(it.next());
}
return list;
}
}
And as an example,
Here is the NodeEntity Place as generic one,
#NodeEntity
public class Place {
#GraphId Long nodeId;
#Indexed(unique=true)
String id;
#Indexed(indexType=IndexType.FULLTEXT, indexName = "place")
String name;
#Labels
private Collection<String> labels = Collections.emptySet();
protected Place(String id, String name) {
this.id = id;
this.name = name;
}
protected Place() {
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addLabel(String label) {
HashSet<String> newLabels = new HashSet<>(this.labels);
if (newLabels.add(label)) this.labels = newLabels;
}
public void removeLabel(String label) {
HashSet<String> newLabels = new HashSet<>(this.labels);
if (newLabels.remove(label)) this.labels = newLabels;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Place place = (Place) o;
if (nodeId == null) return super.equals(o);
return nodeId.equals(place.nodeId);
}
#Override
public int hashCode() {
return nodeId != null ? nodeId.hashCode() : super.hashCode();
}
#Override
public String toString() {
return String.format("%s [%s]", name, id);
}
}
and CountryNeo that extends Place,
#NodeEntity
public class CountryNeo extends Place {
#RelatedTo(type = "HAS_CITY", direction = Direction.OUTGOING)
Set<CityNeo> cities;
#Fetch #RelatedToVia(type = "IS_ROOT", direction = Direction.INCOMING)
Iterable<RoleIsRoot> roles;
public CountryNeo() {
}
public CountryNeo(String id, String name) {
super(id, name);
}
public Set<CityNeo> getCities() {
return cities;
}
public void hasCity(CityNeo city) {
if(cities == null)
cities = new HashSet<CityNeo>();
cities.add(city);
}
public RoleHasCity hasCity(CityNeo city, String roleName) {
return new RoleHasCity(this, city, roleName);
}
public Collection<RoleIsRoot> getRoles() {
Iterable<RoleIsRoot> allRoles = roles;
return allRoles == null ? Collections.<RoleIsRoot>emptyList() : IteratorUtil.asCollection(allRoles);
}
}
The used roles,
#RelationshipEntity(type = "HAS_CITY")
public class RoleHasCity {
#GraphId Long id;
#StartNode CountryNeo country;
#EndNode CityNeo city;
String name;
public RoleHasCity() {
}
public RoleHasCity(CountryNeo country, CityNeo city, String roleName) {
this.country = country;
this.city = city;
this.name = roleName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CountryNeo getCountry() {
return country;
}
public void setCountry(CountryNeo country) {
this.country = country;
}
public CityNeo getCity() {
return city;
}
public void setCity(CityNeo city) {
this.city = city;
}
#Override
public String toString() {
return String.format("%s %s %s", city, name, country);
}
}
And the repository,
public interface CountryNeoRepository extends GraphRepository<CountryNeo> {
#Query("MATCH (n:CountryNeo) RETURN COLLECT(n.name) AS countries")
CountryNeoData findAllCountryNames();
#QueryResult
public class CountryNeoData {
Collection<String> countries = Collections.emptyList();
public Collection<String> getCountries() {
return countries;
}
}
}
And here is the main bean,
public class SakilaImporter {
private GraphDatabaseService graphDatabase;
private SakilaDbImportController importer;
private SakilaDbQueries queries;
public SakilaImporter(GraphDatabaseService graphDatabase,
SakilaDbImportController importer,
SakilaDbQueries queries) {
this.graphDatabase = graphDatabase;
this.importer = importer;
this.queries = queries;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
GraphDatabaseService graphDatabase = ctx.getBean("graphDatabaseService", GraphDatabaseService.class);
SakilaDbImportController importer = ctx.getBean("importer", SakilaDbImportController.class);
SakilaDbQueries queries = ctx.getBean("queries", SakilaDbQueries.class);
SakilaImporter sakilaImporter = new SakilaImporter(graphDatabase, importer, queries);
Transaction tx = graphDatabase.beginTx();
try {
sakilaImporter.createDatabase();
sakilaImporter.queryDatabase();
tx.success();
} finally {
tx.close();
}
ctx.close();
}
public void createDatabase() {
System.out.println("Importing data...");
final long start = System.currentTimeMillis();
RootNeo root = importer.createGraphDb();
if(root != null) {
final long time = System.currentTimeMillis() - start;
System.out.println("Import places took " + time + " ms.");
} else {
System.out.println("root: " + root);
}
}
public void queryDatabase() {
System.out.println();System.out.println();
System.out.println("List of countries.-");
List<CountryNeo> countries = queries.findAllCountries();
for(CountryNeo country: countries) {
System.out.println(country);
}
System.out.println();System.out.println();
System.out.println("List of country names.-");
List<String> names = queries.findAllCountryNames();
for(String name: names) {
System.out.println(name);
}
}
}
The result of both queries is an empty list
spring 2.5.6
spring framework 4.0.0.RELEASE
neo4j 2.1.8
spring data neo4j 3.1.2.RELEASE

Categories