Skip to content

Commit

Permalink
Make observation immutable and implement equals/hashcode
Browse files Browse the repository at this point in the history
  • Loading branch information
sbernard31 committed Jan 4, 2018
1 parent 3dfa899 commit 9a95d5c
Showing 1 changed file with 52 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
*******************************************************************************/
package org.eclipse.leshan.core.observation;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.leshan.core.node.LwM2mPath;
Expand All @@ -25,10 +28,10 @@
*/
public class Observation {

private byte[] id;
private LwM2mPath path;
private String registrationId;
private Map<String, String> context;
private final byte[] id;
private final LwM2mPath path;
private final String registrationId;
private final Map<String, String> context;

/**
* Instantiates an {@link Observation} for the given node path.
Expand All @@ -42,7 +45,10 @@ public Observation(byte[] id, String registrationId, LwM2mPath path, Map<String,
this.id = id;
this.path = path;
this.registrationId = registrationId;
this.context = context;
if (context != null)
this.context = Collections.unmodifiableMap(new HashMap<>(context));
else
this.context = Collections.emptyMap();
}

/**
Expand Down Expand Up @@ -83,4 +89,45 @@ public String toString() {
return String.format("Observation [id=%s, path=%s, registrationId=%s, context=%s]", Hex.encodeHexString(id),
path, registrationId, context);
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((context == null) ? 0 : context.hashCode());
result = prime * result + Arrays.hashCode(id);
result = prime * result + ((path == null) ? 0 : path.hashCode());
result = prime * result + ((registrationId == null) ? 0 : registrationId.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Observation other = (Observation) obj;
if (context == null) {
if (other.context != null)
return false;
} else if (!context.equals(other.context))
return false;
if (!Arrays.equals(id, other.id))
return false;
if (path == null) {
if (other.path != null)
return false;
} else if (!path.equals(other.path))
return false;
if (registrationId == null) {
if (other.registrationId != null)
return false;
} else if (!registrationId.equals(other.registrationId))
return false;
return true;
}

}

0 comments on commit 9a95d5c

Please sign in to comment.