package com.ora.rmibook.chapter15;
import java.util.*;
import java.io.*;
/*
Note that if you call equals or compareto
at the same time from instances, a deadlock
can result.
Recommendation: don't do that.
*/
public class AttributeSet implements Serializable, Comparable {
private TreeMap _underlyingMap;
public AttributeSet() {
_underlyingMap = new TreeMap();
}
public synchronized void add(String name, String value) {
if (null == name) {
return;
}
if (null == value) {
_underlyingMap.remove(name);
} else {
_underlyingMap.put(name, value);
}
}
public synchronized void remove(String name) {
_underlyingMap.remove(name);
}
public synchronized int getSize() {
return _underlyingMap.size();
}
public synchronized Iterator getNames() {
return _underlyingMap.keySet().iterator();
}
public synchronized String getValue(String name) {
return (String) _underlyingMap.get(name);
}
public synchronized boolean contains(String name) {
return (null != _underlyingMap.get(name));
}
public synchronized boolean contains(String name, String value) {
String internalValue = (String) _underlyingMap.get(name);
if (null != internalValue) {
return internalValue.equals(value);
}
return null == value;
}
public synchronized boolean equals(Object object) {
if (null == object) {
return false;
}
if (false == (object instanceof AttributeSet)) {
return false;
}
return (0 == compareTo(object));
}
public synchronized boolean subsetOf(AttributeSet otherAttributeSet) {
if (null == otherAttributeSet) {
return false;
}
Iterator i = getNames();
while (i.hasNext()) {
String name = (String) i.next();
String value = getValue(name);
if (false == otherAttributeSet.contains(name, value)) {
return false;
}
}
return true;
}
public synchronized int compareTo(Object object) {
if (null == object) {
return -1;
}
AttributeSet otherAttributeSet = (AttributeSet) object;
int sizeDifferential = _underlyingMap.size() - otherAttributeSet.getSize();
if (0 != sizeDifferential) {
return (sizeDifferential > 0) ? -1 : 1; //doesn't matter as long as we're consistent.
}
Iterator otherIterator = otherAttributeSet.getNames();
Iterator internalIterator = getNames();
while (otherIterator.hasNext()) {
String foreignName = (String) otherIterator.next();
String internalName = (String) internalIterator.next();
int firstComparison = internalName.compareTo(foreignName);
if (0 != firstComparison) {
return firstComparison;
}
String foreignValue = otherAttributeSet.getValue(foreignName);
String internalValue = getValue(foreignName);
int secondComparison = internalValue.compareTo(foreignValue);
if (0 != secondComparison) {
return secondComparison;
}
}
return 0;
}
}
|