001/*
002 * ModeShape (http://www.modeshape.org)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *       http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.modeshape.schematic.document;
017
018import java.io.Serializable;
019import java.util.Arrays;
020import org.modeshape.schematic.Base64;
021import org.modeshape.schematic.annotation.Immutable;
022
023/**
024 * A {@link Bson.Type#BINARY binary} value for use within a {@link Document BSON Object}.
025 * 
026 * @author Randall Hauch <rhauch@redhat.com> (C) 2011 Red Hat Inc.
027 */
028@Immutable
029public final class Binary implements Serializable {
030    private static final long serialVersionUID = 1L;
031
032    private final byte type;
033    private final byte[] data;
034
035    public Binary( byte[] data ) {
036        this.type = Bson.BinaryType.GENERAL;
037        this.data = data;
038    }
039
040    public Binary( byte type,
041                   byte[] data ) {
042        this.type = type;
043        this.data = data;
044    }
045
046    public byte getType() {
047        return type;
048    }
049
050    public byte[] getBytes() {
051        return data;
052    }
053
054    public int length() {
055        return data.length;
056    }
057
058    @Override
059    public int hashCode() {
060        return length();
061    }
062
063    @Override
064    public boolean equals( Object obj ) {
065        if (obj == this) return true;
066        if (obj instanceof Binary) {
067            Binary that = (Binary)obj;
068            if (this.getType() != that.getType()) return false;
069            if (this.length() != that.length()) return false;
070            return Arrays.equals(this.getBytes(), that.getBytes());
071        }
072        return false;
073    }
074
075    @Override
076    public String toString() {
077        return "Binary (" + (int)type + ':' + length() + ')';
078    }
079
080    public String getBytesInBase64() {
081        return Base64.encodeBytes(data);
082    }
083}