Package org.chaidb.db.api.keys

Source Code of org.chaidb.db.api.keys.StringKey

/*
* 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.index.Key;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class StringKey implements Key {

    public String key;

    /**
     * Construct a StringKey from byte[]
     */
    public StringKey(byte[] encoded) {
        try {
            key = new String(encoded, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
    }

    /**
     * Constructor
     */
    public StringKey(String key) {
        this.key = key;
    }

    // implement Key methods

    public byte[] toBytes() {
        byte[] ret = null;
        try {
            ret = key.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return ret;
    }

    public int size() {
        return toBytes().length;
    }

    public String toString() {
        return key;
    }

    public int getKeyType() {
        return STRING_KEY;
    }

    public int compareTo(Key otherKey) throws ChaiDBException {
        checkKeyType(otherKey);
        StringKey key2 = (StringKey) otherKey;
        return KeyTool.compareString(key, key2.key);
    }

    private void checkKeyType(Key key) throws ChaiDBException {
        int keyType = key.getKeyType();
        if (keyType != STRING_KEY) {
            ArrayList params = new ArrayList(2);
            // required
            params.add(Key.KEY_TYPES[Key.STRING_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 StringKey) return KeyTool.compareString(key, ((StringKey) obj).key) == 0;
        return false;
    }

    public Object clone() {
        return new StringKey((String) key.toString());
    }
}
TOP

Related Classes of org.chaidb.db.api.keys.StringKey

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.