/*
* Copyright (C) 2006 http://www.chaidb.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
package org.chaidb.db.api.keys;
import org.chaidb.db.exception.ChaiDBException;
import org.chaidb.db.exception.ErrorCode;
import org.chaidb.db.helper.ByteTool;
import org.chaidb.db.index.Key;
import java.util.ArrayList;
import java.util.Date;
public class DateKey implements Key {
public Date key;
/**
* Construct a DateKey from byte[]
*/
public DateKey(byte[] encoded) {
key = new Date(ByteTool.bytesToLong(encoded, 0, true));
}
/**
* Constructor
*/
public DateKey(Date key) {
this.key = key;
}
// implement Key methods
public byte[] toBytes() {
return ByteTool.longToBytes(key.getTime());
}
public int size() {
return 8;
}
public String toString() {
return key.toString();
}
public int getKeyType() {
return DATE_KEY;
}
public int compareTo(Key otherKey) throws ChaiDBException {
checkKeyType(otherKey);
DateKey key2 = (DateKey) otherKey;
return KeyTool.compareDate(key, key2.key);
}
private void checkKeyType(Key key) throws ChaiDBException {
int keyType = key.getKeyType();
if (keyType != DATE_KEY) {
ArrayList params = new ArrayList(2);
// required
params.add(Key.KEY_TYPES[Key.DATE_KEY]);
// found
params.add(Key.KEY_TYPES[keyType]);
throw new ChaiDBException(ErrorCode.INDEX_KEY_TYPE_ERROR, params);
}
}
// override java.lang.Object methods
public int hashCode() {
return key.hashCode();
}
public boolean equals(Object obj) {
if (obj instanceof DateKey) return KeyTool.compareDate(key, ((DateKey) obj).key) == 0;
return false;
}
public Object clone() {
return new DateKey((Date) key.clone());
}
}