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 import java.io.InputStream;
21
22 import org.apache.commons.lang3.Validate;
23
24 /**
25 * Support and basic field options.
26 * @version $Revision: 1301248 $ $Date: 2012-03-15 17:20:49 -0500 (Thu, 15 Mar 2012) $
27 */
28 public abstract class FieldSupport extends EntitySupport {
29
30 /** Serialization version */
31 private static final long serialVersionUID = -8940832296518637934L;
32
33 /**
34 * Overflow behavior enumerated type.
35 */
36 public enum Overflow implements FieldOption {
37 /** Error on overflow */
38 ERROR() {
39 /**
40 * {@inheritDoc}
41 */
42 protected void check(byte[] b, int len) {
43 Validate.isTrue(b.length <= len,
44 "Value '%s' too large for field (%s)", new String(b), len);
45 }
46 },
47
48 /** Truncate on overflow (same as IGNORE) */
49 TRUNCATE,
50
51 /** Ignore overflow (same as TRUNCATE) */
52 IGNORE;
53
54 /**
55 * Check the overflow of the field
56 * @param b value
57 * @param len field length
58 */
59 protected void check(byte[] b, int len) {
60 }
61 }
62
63 /**
64 * Underflow behavior enumerated type.
65 */
66 public enum Underflow implements FieldOption {
67 /** Error on Underflow */
68 ERROR() {
69 /**
70 * {@inheritDoc}
71 */
72 protected void check(byte[] b, int len) {
73 Validate.isTrue(b.length >= len,
74 "Value '%s' too small for field (%s)", new String(b), len);
75 }
76 },
77
78 /** Ignore Underflow */
79 IGNORE;
80
81 /**
82 * Check the underflow of the field
83 * @param b value
84 * @param len field length
85 */
86 protected void check(byte[] b, int len) {
87 }
88 }
89
90 /**
91 * Convenience #readFrom alias.
92 * @param is InputStream for <code>readFrom</code>.
93 */
94 protected void dieOnExceptionRead(InputStream is) {
95 try {
96 readFrom(is);
97 } catch (IOException e) {
98 throw new RuntimeException(e);
99 }
100 }
101 }