Accessing 2 models with 1 controller in Java MVC? - java

Is accessing 2 models with 1 controller in Java MVC alright?
The code looks similar to this:
This is the 1st model
public class People {
private String id, name;
public People(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
I'm still not sure about PeopleList class necessity. This is the 2nd model.
public class PeopleList extends ArrayList<People>{
#Override
public boolean add(People e) {
return super.add(e);
}
#Override
public int size() {
return super.size();
}
}
Here is the controller:
public class PeopleListController {
PeopleList peopleList;
public People findPeopleById(String id) {
People person = new People("", "");
for (People p : peopleList) {
if (p.getId().equals(id)) {
return p;
}
}
return person;
}
}
In the peopleListController, I accessed people using p.getId().
Is it alright? If it is, then it means I don't need to create
peopleController.
Or should I access p.getId() via a new controller
called peopleController?
Or should I just remove the peopleList class
and make an arrayList in this controller? ArrayList peopleList
Thank you for your time.

Related

SDN4 is not returning nested Entities

Hello Stack overflow,
I have the following Problem:
I have these entity classes:
public class UnknownEntity extends NetworkEntity{
#Id
#GeneratedValue(strategy = UuidStrategy.class)
private String id;
#Override
public void setId(String id) {
this.id = id;
}
#Override
public String getId() {
return id;
}
}
#NodeEntity
public class NetworkEntity {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
protected String id;
public List<NetworkInterfaceEntity> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<NetworkInterfaceEntity> interfaces) {
this.interfaces = interfaces;
}
#Relationship(type = "is_composed_of")
protected List<NetworkInterfaceEntity> interfaces ;
}
#NodeEntity
public class NetworkInterfaceEntity {
public String getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getNetmask() {
return netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public InterfaceState getState() {
return state;
}
public void setState(InterfaceState state) {
this.state = state;
}
public List<NetworkInterfaceEntity> getSubInterfaces() {
return subInterfaces;
}
public void setSubInterfaces(List<NetworkInterfaceEntity> subInterfaces) {
this.subInterfaces = subInterfaces;
}
public long getBytesSent() {
return bytesSent;
}
public void setBytesSent(long bytesSent) {
this.bytesSent = bytesSent;
}
public long getBytesRecived() {
return bytesRecived;
}
public void setBytesRecived(long bytesRecived) {
this.bytesRecived = bytesRecived;
}
#Id
private String interfaceId;
private String ipAddress;
private String netmask;
private String macAddress;
private String name;
private InterfaceState state;
#Relationship(type = "is_composed_of")
private List<NetworkInterfaceEntity> subInterfaces;
private long bytesSent;
private long bytesRecived;
}
When I now try to query the UnknownEntities via a Neo4j Crud Repository with a custom #Query Method, the UnknownEntities wont be nested with the necessary NetworkInterfaceObjects, even tough my query returns these.
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN collect(unknown),nodes(p),rels(p)")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
In this particular case the NetworkInterfaceEntities do not contain more subInterfaces, so I only want the NetworkInterfaceEntities that belong the the UnknownEntity. But when I use this Query I only get UnknownEntities where the NetworkInterfaceList is null. I even tried different Querys to no avail for example:
"MATCH p=(u:UnknownEntitie)-[:is_composed_of]-(n:NetworkInterfaceEntity) WHERE n.ipAddress in {0} RETURN collect(n),nodes(p),rels(p)".
My Question is, if what I want is even possible with SDN4 Data and if it is, how I can achieve this, Since my alternative is to query the database for every NetworkInterface separately, which I think is really ugly.
Any help would be much appreciated.
please try if returning the full path like this:
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN p")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
works for your. If not, try naming the objects in question, i.e. RETURN i as subInterfaces works for you.
Are you using Spring Data Neo4j 4 or 5? If you're on 4, consider the upgrade to 5 to be on a supported level.
Please let me know, if this helps.

Deserialize an object's property which has an inconsistent name?

Using Retrofit here to consume Google Civic API.
The library requires you to create a model of what the API will return as I have done already with Election. Which is basically a copy of the google documentation.
(Retrofit binds the response properties to properties with the same name)
Election.Java :
public class Election {
private long id;
private String name;
private String electionDay;
private String ocdDivisionId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getElectionDay() {
return electionDay;
}
public void setElectionDay(String electionDay) {
this.electionDay = electionDay;
}
public String getOcdDivisionId() {
return ocdDivisionId;
}
public void setOcdDivisionId(String ocdDivisionId) {
this.ocdDivisionId = ocdDivisionId;
}
}
But Representatives have an inconsistent property name, thus I don't see a way to model this in a way Retrofit will know how to deserialize the API's response.
Representatives object (JSON) :
property name is called (key)
How do I let Retrofit deserialize a model that captures the property named variable after a key of the division?
Assuming you're using a Gson converter, I personally would use a map. I guess the same can be achieved with other converters, but I never used them. Say you have the following object:
public class Division {
#SerializedName("name")
#Expose
private String name;
#SerializedName("alsoKnownAs")
#Expose
private List<String> alsoKnownAs = new ArrayList<>();
#SerializedName("officeIndices")
#Expose
private List<Integer> officeIndices = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAlsoKnownAs() {
return alsoKnownAs;
}
public void setAlsoKnownAs(List<String> alsoKnownAs) {
this.alsoKnownAs = alsoKnownAs;
}
public List<Integer> getOfficeIndices() {
return officeIndices;
}
public void setOfficeIndices(List<Integer> officeIndices) {
this.officeIndices = officeIndices;
}
}
Which represents the object inside the divisions array. You can then have the class:
private class Divisions {
#SerializedName("divisions")
#Expose
private Map<String, Division> divisions = new HashMap<>();
// ...
}
Notice the usage of a map here? Behind the scenes Gson will be able to serialise and deserialise your objects. The class Divisions is the root of the json you gave us in the question.
Hope this helps

Settings Relationship Properties in Neo4J OGM

I found out about Neo4j OGM yesterday and quickly made a new project to test out how it works. One problem I've come across is setting Relationhip properties as this is crucial for my project. Here's an example:
Room Node:
#NodeEntity
public class Room {
#GraphId
Long id;
#Property(name="name")
String name;
#Relationship(type="CONNECTS")
List<Room> rooms;
public List<Room> getRooms() {
if(rooms == null)
rooms = new ArrayList<Room>();
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
public Room(String name){
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Room(){
}
public void connectsTo(Room room){
this.getRooms().add(room);
}
}
Connects Node (Relation):
#RelationshipEntity(type="CONNECTS")
public class Connects {
#GraphId
Long id;
#StartNode
Room startMapNode;
#EndNode
Room endMapNode;
#Property(name="length")
int length;
public Connects(Room startMapNode, Room endMapNode){
this.startMapNode = startMapNode;
this.endMapNode = endMapNode;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Room getStartMapNode() {
return startMapNode;
}
public void setStartMapNode(Room startMapNode) {
this.startMapNode = startMapNode;
}
public Room getEndMapNode() {
return endMapNode;
}
public void setEndMapNode(Room endMapNode) {
this.endMapNode = endMapNode;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public Connects(){
}
}
Main method:
public static void main(String[] args) {
SessionFactory sessionFactory = new SessionFactory("at.htl.in110010.domain");
Session session = sessionFactory.openSession("http://localhost:7474");
session.purgeDatabase();
Room roomOne = new Room("TEST_ROOM_ONE");
Room roomTwo = new Room("TEST_ROOM_TWO");
roomOne.connectsTo(roomTwo);
roomTwo.connectsTo(roomOne);
Connects connectRelation = new Connects(roomOne,roomTwo);
connectRelation.setLength(2);
session.save(connectRelation);
}
Now as you can see I've set the length in my main method, but when I check the database under http://localhost:7474 it shows the relation between the nodes but says it has no properties.
Here is the console output: http://pastebin.com/CByfmVcR
Any help in setting the Property would be very appreciated.
Or is there perhaps a different/easier way of mapping objects to the neo4J database ?
Thanks
Using a relationship entity is the right thing to do as you have properties on the relationship. But this also means that your relationship between rooms is represented by Connects.
So, Room should have a reference to Connects rather than to the other Room directly.
e.g.
#Relationship(type="CONNECTS")
List<Connects> rooms;
Here's a test that resembles your domain model:
https://github.com/neo4j/neo4j-ogm/tree/master/src/test/java/org/neo4j/ogm/domain/friendships and
https://github.com/neo4j/neo4j-ogm/blob/master/src/test/java/org/neo4j/ogm/integration/friendships/FriendshipsRelationshipEntityTest.java
I notice you're using neo4j-ogm 1.1.3. Please upgrade to 1.1.4 as it contains important fixes.

Cannot bind RemoteObject from BlazeDS

I'm using BlazeDS in Tomcat7 and Flex. I'm trying to use custom classes between the client and server.
In as:
package
{
[Bindable]
[RemoteClass(alias="remoting.Product")]
public class Product
{
public var name:String;
public var id:int;
public var isVisible:Boolean;
}
}
In Java:
package remoting;
public class Product {
public String name;
public int id;
public Boolean isVisible;
public Product(){
name = "Product 0.1";
id = 123;
isVisible = false;
}
public void setName(String _name){
name = _name;
}
public void setId(int _id){
id = _id;
}
public void setVisible(Boolean _isVisible){
isVisible = _isVisible;
}
}
Service part:
public Product echo() {
Product product = new Product();
product.setId(123);
product.setName("My Product");
product.setVisible(true);
return product;
}
I can successfully set the destination of the RemoteObject and call the echo() method. The result event fires up, with the Product object in event.result. However, it does not contain any sensible data. The variables from AS class just get initialized with null, 0 and true values. I'm wondering what's the problem. I tried returning a String with parameters from Product and it works fine, so they get set fine. The problem is in mapping.
I could go another way and implement Externalizable but I don't understand this part from the example:
name = (String)in.readObject();
properties = (Map)in.readObject();
price = in.readFloat();
What if there is a number of strings?
Cheers.
In java class: use private fields and implement getters.
package remoting;
public class Product {
private String name;
private int id;
private Boolean isVisible;
public Product() {
name = "Product 0.1";
id = 123;
isVisible = false;
}
public void setName(String _name){
name = _name;
}
public String getName(){
return name;
}
public void setId(int _id){
id = _id;
}
public int getId(){
return id;
}
public void setIsVisible(Boolean _isVisible){
isVisible = _isVisible;
}
public Boolean getIsVisible() {
return isVisible;
}
}
You could also switch from BlazeDS to GraniteDS: the latter has a powerful transparent externalization mechanism as well as code generation tools that can really save your time (see documentation here).

create a class to model a list

I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}

Categories