001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.flatfile;
018
019import java.io.IOException;
020
021import org.apache.commons.flatfile.util.RepeatingInputStream;
022
023/**
024 * Generic entity support stuff.
025 * @version $Revision: 1301242 $ $Date: 2012-03-15 17:14:40 -0500 (Thu, 15 Mar 2012) $
026 */
027public abstract class EntitySupport implements Entity {
028
029    /** Serialization version */
030    private static final long serialVersionUID = 1067918863342682612L;
031
032    /**
033     * {@inheritDoc}
034     */
035    public void fill(byte b) throws IOException {
036        readFrom(RepeatingInputStream.of(b));
037    }
038
039    /**
040     * {@inheritDoc}
041     */
042    public EntitySupport clone() {
043        try {
044            return (EntitySupport) super.clone();
045        } catch (CloneNotSupportedException e) {
046            throw new RuntimeException(e);
047        }
048    }
049
050    /**
051     * {@inheritDoc}
052     * Naive implementation which can and should be overridden by subclasses.
053     */
054    public byte[] getValue(int offset, int length) {
055        if (offset + length > length()) {
056            throw new IndexOutOfBoundsException();
057        }
058        final byte[] value = getValue();
059        final byte[] result = new byte[length];
060        System.arraycopy(value, offset, result, 0, length);
061        return result;
062    }
063
064    /**
065     * {@inheritDoc}
066     */
067    public void setValue(byte[] b, int offset, int length) {
068        if (offset + length > b.length) {
069            throw new IndexOutOfBoundsException();
070        }
071        final byte[] subset = new byte[length];
072        System.arraycopy(b, offset, subset, 0, length);
073        setValue(subset);
074    }
075
076}