UUID every run is changing - java

I have an issue. I created the class "User" and in the constructor, I put the name which I have to write and the id which should be generated when I create an object. Unfortunately, I have created one object and every time when I run the code the UUID is changing the id. How can I write the code in the constructor to create one object ID which will not be changing every run?
public class User {
private String name;
private UUID id;
public User(String name) {
this.name = name;
this.id = UUID.randomUUID();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return String.valueOf(id);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name) && Objects.equals(id, user.id);
}
#Override
public int hashCode() {
return Objects.hash(name, id);
}
#Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
'}';
}
};
public class App {
public static void main(String[] args) {
User jan = new User("Jan");
System.out.println(jan);
}
The output:
User{name='Jan', id='089fb1bf-fc15-4af6-b8e9-0d9e88aaa392'}
User{name='Jan', id='24a4214c-f9b2-49b5-ae27-0c41edcaf5b1'}

From the comments, the problem is due to the fact that you're creating a new random UUID in your constructor:
public User(String name) {
this.name = name;
this.id = UUID.randomUUID();
}
To fix the randomness of the identifier, I would suggest adding the UUID as part of the constructor:
public User(UUID id, String name) {
this.id = id;
this.name = name;
}
This way, you can always control the value of the identifier used.
In the long run, depending on how you architect your application, that identifier could come from a Factory object or a database.

Related

Overridden equals and hashCode does not work on custom Object;

I have an below object
class CustomObj{
private String name;
private String dept;
public String getName(){
return this.name;
}
public String getDept(){
return this.dept;
}
private CustomObj(){
}
private CustomObj(CustomObjBuilder builder){
this.name = builder.name;
this.dept= builder.dept;
}
#Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomObj that = (CustomObj) o;
return that.name.equals(name) &&
that.dept.equals(dept);
}
#Override
public int hashCode() {
int result = 31;
result = 31 * result + name.hashCode();
result = 31 * result + dept.hashCode();
return result;
}
public static class CustomObjBuilder{
private String name;
private String dept;
public CustomObjBuilder(String name, String dept){
this.name = name;
this.dept = dept;
}
public CustomObjBuilder setName(String name){
this.name = name;
return this;
}
public CustomObjBuilder setDept(String dept){
this.dept = dept;
return this;
}
public CustomObj build(){
return new CustomObj(this);
}
}
}
and class that uses above
class XYZ{
Set<CustomObj> obj = new HashSet<CustomObj>();
public void process(String a, String b){
CustomObj o = new CustomObj.CustomObjBuilder(a,b).build();
if(!obj.contains(o)){
obj.add(o);
}
}
}
And a test class
class TestXYX{
#Test
public void test(){
XYZ xyz = new XYZ();
xyz.process("TEST","TESTABC");
xyz.process("TEST","TESTABC");
}
}
Beacuse I have overrideen hascode and equals, both the above are equal and when process is called second time, the control should not go into if(!obj.contains(o)) second time and size of the set should be 1. But when i run the test obj.add(o); is called two times. But the values of both this object and that objec inside equals methods are same, but
that.name.equals(name) && that.dept.equals(dept)
inside CustomObj returns false. Can someone please help me understand why?
The code is fine. To verify add an sysout to check Set size:
class XYZ {
Set<CustomObj> obj = new HashSet<CustomObj>();
public void process(String a, String b) {
CustomObj o = new CustomObj.CustomObjBuilder(a, b).build();
if (!obj.contains(o)) { // Fails second time for your use case.
obj.add(o);
}
System.out.println(obj.size()); // This is 1 in your use case.
}
}

How to create own Custom Predicate to compare composite id in hazelcast

I want to create my own custome predicate to compare composite id's inside object. The need is to because i have to write specific date comparison logic on object inside object (composite id). I don't want to compare individual attributes.i want to use composite id because it comes from invoker and I can't get result using Predicate.in and Predicate.equals
My Object structure is like below
Birth{id=BirthId{name='b3', dob=Wed Jan 01 10:53:20 IST 1902}, name='b3', dob=Wed Jan 01 10:53:20 IST 1902, description='MNP'}
and inside IMap it is stored like below
key : BirthId{name='b3', dob=Wed Jan 01 10:53:20 IST 1902}
value : Birth{id=BirthId{name='b3', dob=Wed Jan 01 10:53:20 IST 1902}, name='b3', dob=Wed Jan 01 10:53:20 IST 1902, description='MNP'}
My Java Classes(Birth and Birthid) Structure is below
public class Birth implements Serializable, Portable {
private static final long serialVersionUID = 1L;
private BirthId id;
private String name;
private Date dob;
private String description;
public BirthId getId() {
return id;
}
public void setId(BirthId id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public int hashCode() {
return (new HashCodeBuilder()).append(this.id).append(this.name).append(this.dob).toHashCode();
}
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (!(other instanceof Birth)) {
return false;
} else {
Birth rhs = (Birth) other;
return (new EqualsBuilder()).append(this.id, rhs.id).append(this.name, rhs.name).append(this.dob, rhs.dob).isEquals();
}
}
#Override public String toString() {
return "Birth{" + "id=" + id + ", name='" + name + '\'' + ", dob=" + dob + ", description='" + description + '\'' + '}';
}
public int getFactoryId() {
return 1;
}
public int getClassId() {
return 1;
}
public void writePortable(PortableWriter portableWriter) throws IOException {
portableWriter.writePortable("idComposite", getId());
portableWriter.writeUTF("id", getId().toString());
portableWriter.writeUTF("name", getName());
portableWriter.writeUTF("description", getDescription());
Date date = getDob();
portableWriter.writeLong("dob", ((date == null) ? -1 : date.getTime()));
}
public void readPortable(PortableReader portableReader) throws IOException {
setId((BirthId) portableReader.readPortable("idComposite"));
setName(portableReader.readUTF("name"));
setDescription(portableReader.readUTF("description"));
long date = portableReader.readLong("dob");
setDob(((date == -1) ? null : new Date(date)));
}
}
public class BirthId implements Comparable<BirthId>, Serializable, Portable {
private static final long serialVersionUID = 1L;
private String name;
private Date dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public int hashCode() {
return (new HashCodeBuilder()).append(this.name).append(this.dob).toHashCode();
}
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (!(other instanceof BirthId)) {
return false;
} else {
BirthId rhs = (BirthId) other;
return (new EqualsBuilder()).append(this.name, rhs.name).append(this.dob, rhs.dob).isEquals();
}
}
public int compareTo(BirthId rhs) {
return this == rhs ? 0 : (null == rhs ? -1 : (new CompareToBuilder()).append(this.name, rhs.name).append(this.dob, rhs.dob).toComparison());
}
#Override public String toString() {
return "BirthId{" + "name='" + name + '\'' + ", dob=" + dob + '}';
}
public int getFactoryId() {
return 1;
}
public int getClassId() {
return 2;
}
public void writePortable(PortableWriter portableWriter) throws IOException {
portableWriter.writeUTF("name", getName());
Date date = getDob();
portableWriter.writeLong("dob", ((date == null) ? -1 : date.getTime()));
}
public void readPortable(PortableReader portableReader) throws IOException {
setName(portableReader.readUTF("name"));
long date = portableReader.readLong("dob");
setDob(((date == -1) ? null : new Date(date)));
}
public static ClassDefinition getClassDefinition(int portableVersion) {
ClassDefinitionBuilder result = new ClassDefinitionBuilder(1, 2, portableVersion);
result.addUTFField("name");
result.addLongField("dob");
return result.build();
}
}
I have created own custom Predicate to compare dates like below
public class DatePredicate extends AbstractPredicate<Comparable, BirthId> {
Comparable[] values;
private volatile Set<Comparable> convertedInValues;
public DatePredicate() {
}
public DatePredicate(String attribute, Comparable... values) {
if (values == null) {
throw new NullPointerException("Array can't be null");
} else {
this.values = values;
}
}
protected boolean applyForSingleAttributeValue(Map.Entry entry, Comparable attributeValue) {
//My own date comparison logic
return true;
}
public int getId() {
return 99;
}
}
Caller code is
Predicate p = new DatePredicate("id", new BirthId("12345",passSpecifiedDate()));
Result res = imap.values(p);
I am getting below error
Exception in thread "main" com.hazelcast.nio.serialization.HazelcastSerializationException: com.hazelcast.internal.serialization.impl.ArrayDataSerializableFactory#5f007be3 is not be able to create an instance for id: 99 on factoryId: -32
I do not know the best way to create own custom predicate and hazelcast doc does not specify the also.
Could any please guide me how to do this?
#oomph-fortuity, your DatePredicate extends AbstractPredicate which implements IdentifiedDataSerializable and used by built-in Hazelcast predicates. Built-in Predicate Serializable Factory try to deserialize your class & fails since it only knows how to serialize/deserialize built-in Predicates.
Instead, just implement com.hazelcast.query.Predicate interface:
class DatePredicate implements Predicate<BirthId, Birth> {
BirthId birthIdToCompare;
public DatePredicate() {
}
public DatePredicate(BirthId birthId) {
this.birthIdToCompare = birthId;
}
#Override
public boolean apply(Map.Entry<BirthId, Birth> mapEntry) {
BirthId key = mapEntry.getKey();
///your custom logic
return true;
}
}
And call like this
Predicate p = new DatePredicate(new BirthId("12345",passSpecifiedDate()));
Result res = imap.values(p);
Let me know if that works.

cqengine cant index by equals

I'm trying to add an index where my override equals() determines if two objects are the same or not.
Car.java
public static class Car {
final String id;
private String name;
public Car(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static final Attribute<Car, Car> CAR = new SimpleAttribute<Car, Car>() {
#Override
public Car getValue(Car car, QueryOptions queryOptions) {
return car;
}
};
#Override
public String toString() {
return "Car{" + "id=" + id + ", name=" + name + '}';
}
}
Fetcher.java
public static final ResultSet<Car> get(final IndexedCollection<Car> indexedCollection, final Car car) {
return indexedCollection.retrieve(QueryFactory.equal(Car.CAR, car));
}
Main.java
public static void main(String args[]) {
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<>();
cars.addIndex(NavigableIndex.onAttribute(Car.CAR));
}
The problem is on this line cars.addIndex(NavigableIndex.onAttribute(Car.CAR)); where the error message is no suitable method found for onAttribute(Attribute<Car,Car>). Am I doing something wrong here or is there another call I should be using instead?
Remove cars.addIndex(NavigableIndex.onAttribute(Car.CAR));, because it is not really an usefull index... and I think this was not a motivation of the developer. You should create Attributes for CAR_ID and CAR_NAME and create an Query for comparison. In this case I misuse (to achieve what you expect) IndexedCollection as a simple Set. But... here is a possible solution, if I have understood you correctly:
Override equals in Car:
class Car {
private final int id;
private String name;
public Car(int i, String name) {
this.id = i;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if (!(obj instanceof Car)) return false;
Car car = (Car) obj;
if(car.getId() == this.getId())
if(car.getName().equals(this.getName()))
return true;
return false;
}
public static final Attribute<Car, Car> CAR = new SimpleAttribute<Car, Car>() {
#Override
public Car getValue(Car car, QueryOptions queryOptions) {
return car;
}
};
#Override
public String toString() {
return "Car{" + "id=" + id + ", name=" + name + '}';
}
}
Main:
IndexedCollection<Car> cars = new ConcurrentIndexedCollection<>();
cars.add(new Car(1, "test"));
cars.add(new Car(2, "test2"));
cars.add(new Car(3, "test3"));
Car s = new Car(2, "test2");
ResultSet<Car> cs= cars.retrieve(QueryFactory.equal(Car.CAR, s));
cs.forEach(c -> System.out.println(c.toString()));

Create Neo4j relation in spring data with existing node

I am trying to create relationships between nodes in Neo4j. I am using the Neo4J(2.1.8 Community) & spring-data-neo4j(3.3.0.RELEASE).
I am trying to create the below relation.
Create a new Employee(node) which will be reporting(Empty Relation) to the Manager(node) which is there in DB (Searching by name). I have used the below query.
public interface EmployeeRepository extends GraphRepository<Employee> {
#Query("START employee=node:({0}), manager=node:Employee(name={1}) CREATE employee-[:REPORTS_TO]->manager")
void addNewEmployee(Employee employee, String managerName);}
I got the below error.
Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: Error executing statement START employee=node:({0}), manager=node:Employee(name={1}) CREATE employee-[:REPORTS_TO]->manager; nested exception is Invalid input '(': expected whitespace or an identifier (line 1, column 21)
"START employee=node:({0}), manager=node:Employee(name={1}) CREATE employee-[:REPORTS_TO]->manager"
^
Can anyone please tell me what is wrong with this query? Also if this is not the right way to create the relations using GraphRepository then what else I can use to accomplish the same.
Thanks in advance.
Note: I have used this to learn the queries in Spring Data for Neo4j. Where they have shown the basic queries.
Updated: Employee Class
#NodeEntity
public class Employee {
#GraphId
private Long id;
private String name;
private String department;
#RelatedTo(type = "REPORTS_TO")
private Employee reportsTo;
#RelatedTo(type = "REPORTS_TO", direction = Direction.INCOMING)
Set<Employee> directReport;
public Employee() {
}
public Employee(String name, String department) {
this.name = name;
this.department = department;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Employee getReportsTo() {
return reportsTo;
}
public void setReportsTo(Employee reportsTo) {
this.reportsTo = reportsTo;
}
public Set<Employee> getDirectReport() {
return directReport;
}
public void setDirectReport(Set<Employee> directReport) {
this.directReport = directReport;
}
#Override
public int hashCode() {
return super.hashCode();
}
#Override
public boolean equals(Object obj) {
return super.equals(obj);
}
#Override
public String toString() {
return "Employee{" + "id=" + id + ", name=" + name + ", department=" + department + '}';
}
}
Please show the definition of employee!
You can also use template.createRelationshipBetween(nodeOrEntity,nodeOrEntity2,type)
For your example this should work:
public interface EmployeeRepository extends GraphRepository {
#Query("MATCH (employee:Employee), (manager:Employee)
WHERE id(employee) = {0} AND manager.name = {1}
CREATE employee-[:REPORTS_TO]->manager")
void addNewEmployee(Employee employee, String managerName);
}
perhaps better use, employee as a data-container / map for employee or just pass in the name directly:
#Query("MATCH (employee:Employee), (manager:Employee)
WHERE employee.name = {0}.name AND manager.name = {1}
CREATE employee-[:REPORTS_TO]->manager")
void addNewEmployee(Employee employee, String managerName);
}

What is Getters, setters, equals and toString for this program. How to write it

public class People {
// Code to create a random set of people omitted
public Set getAllPeople() {
return people;
}
public void setPerson(Person person) {
if (person.getId() == -1) {
person.setId(getNextId());
}
people.remove(person);
people.add(person);
}
public void deletePerson(Person person) {
people.remove(person);
}
private Set people = new HashSet();
}
public class Person
{
private int id;
private String name;
private String address;
private float salary;
// Getters, setters, equals and toString omitted
}
While looking after the DWR website i found this example.It states that they omitted Getters, setters, equals and toString. How to write those for this program. I wish to run this program and see. Any Suggestions Please. Help out..
Getters and Setters are used to retrieve your "private" variables ( = variables visible inside the class they are defined only), from outside the class.
For instance:
private String name;
would have a getter like this:
public String getName() {
return name;
}
And a setter like this:
public void setName(String name) {
this.name = name;
}
(you could use "protected" if you only wanted this variable to be visible in the package, and not in the whole project).
the toString() method is here if you want to display some information about your object, which might be useful from a debugging point of view.
The equals method would be used to know how you want to compare to objects of Person type (by ids only for instance).
Have a look at this link to have more info on what is equals.
As RonK suggested, be sure to implement hashCode if you do implement equals, they go together, and have to use the same fields (part of the contract).
The rule is that if:
objectA.equals(objectB) returns true
then
objectA.hashCode() has to be equal to objectB.hashCode()
for each property in Person class you need to define 2 methods
for example id:
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
and you need to override equals and hashcode method to put your own condition for equality
public boolean equals(Object that) {
if (that == null) {
return false;
}
if (!(that instanceof Person)) {
return false;
}
return this.id == ((Person) that).id;
}
public int hashCode() {
return id * 17;
}
public class Person
{
//Id should be unique
private int id;
private String name;
private String address;
private float salary;
public Person(int id, String name, String address, float salary)
{
this.id = id;
this.name = name; //Maybe check for null
this.address = address; //Maybe check for null
this.salary = salary; //Maybe check for > 0
}
public int getId()
{
return id;
}
//No setID() - do you want that? you properly shouldn't
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address; //Maybe check for null
}
public float getSalary()
{
return salary;
}
public setSalary(float salary)
{
this.salary = salary;
}
//A person is equal if they have the same ID
#Override
public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Person person = (Person)obj;
return person.id == id;
}
#Override
public int hashCode()
{
return id;
}
//Just returns the name but you could return more details
#Override
public String toString()
{
return name;
}
}
Added hashCode which is essential - especially if you use it in a HashSet.

Categories

Resources