View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.flatfile;
18  
19  import java.io.IOException;
20  
21  import org.apache.commons.flatfile.util.RepeatingInputStream;
22  
23  /**
24   * Generic entity support stuff.
25   * @version $Revision: 1301242 $ $Date: 2012-03-15 17:14:40 -0500 (Thu, 15 Mar 2012) $
26   */
27  public abstract class EntitySupport implements Entity {
28  
29      /** Serialization version */
30      private static final long serialVersionUID = 1067918863342682612L;
31  
32      /**
33       * {@inheritDoc}
34       */
35      public void fill(byte b) throws IOException {
36          readFrom(RepeatingInputStream.of(b));
37      }
38  
39      /**
40       * {@inheritDoc}
41       */
42      public EntitySupport clone() {
43          try {
44              return (EntitySupport) super.clone();
45          } catch (CloneNotSupportedException e) {
46              throw new RuntimeException(e);
47          }
48      }
49  
50      /**
51       * {@inheritDoc}
52       * Naive implementation which can and should be overridden by subclasses.
53       */
54      public byte[] getValue(int offset, int length) {
55          if (offset + length > length()) {
56              throw new IndexOutOfBoundsException();
57          }
58          final byte[] value = getValue();
59          final byte[] result = new byte[length];
60          System.arraycopy(value, offset, result, 0, length);
61          return result;
62      }
63  
64      /**
65       * {@inheritDoc}
66       */
67      public void setValue(byte[] b, int offset, int length) {
68          if (offset + length > b.length) {
69              throw new IndexOutOfBoundsException();
70          }
71          final byte[] subset = new byte[length];
72          System.arraycopy(b, offset, subset, 0, length);
73          setValue(subset);
74      }
75  
76  }