1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.ancientprogramming.fixedformat4j.format;
17
18 import com.ancientprogramming.fixedformat4j.exception.FixedFormatException;
19 import org.apache.commons.logging.Log;
20 import org.apache.commons.logging.LogFactory;
21
22 import static java.lang.String.format;
23
24
25
26
27
28
29
30 public class FixedFormatUtil {
31
32 private static final Log LOG = LogFactory.getLog(FixedFormatUtil.class);
33
34
35
36
37
38
39
40
41 public static String fetchData(String record, FormatInstructions instructions, FormatContext context) {
42 String result;
43 int offset = context.getOffset() - 1;
44 int length = instructions.getLength();
45 if (record.length() >= offset + length) {
46 result = record.substring(offset, offset + length);
47 } else if (record.length() > offset) {
48
49 result = record.substring(offset, record.length());
50 if (LOG.isDebugEnabled()) {
51 LOG.warn(format("The record field was not as long as expected by the instructions. Expected field to be %s long but it was %s.", length, record.length()));
52 }
53 } else {
54 result = null;
55 LOG.warn(format("Could not fetch data from record as the recordlength[%s] was shorter than or equal to the requested offset[%s] of the request data. Returning null", record.length(), offset));
56 }
57 if (LOG.isDebugEnabled()) {
58 LOG.debug(format("fetched '%s' from record", result));
59 }
60 return result;
61 }
62
63 public static FixedFormatter getFixedFormatterInstance(Class<? extends FixedFormatter> formatterClass, FormatContext context) {
64 FixedFormatter formatter = getFixedFormatterInstance(formatterClass, context.getClass(), context);
65 if (formatter == null) {
66 formatter = getFixedFormatterInstance(formatterClass, null, null);
67 }
68 if (formatter == null) {
69 throw new FixedFormatException("could not create instance of [" + formatterClass.getName() + "] because the class has no default constructor and no constructor with " + FormatContext.class.getName() + " as argument.");
70 }
71 return formatter;
72 }
73
74 public static FixedFormatter getFixedFormatterInstance(Class<? extends FixedFormatter> formatterClass, Class paramType, FormatContext paramValue) {
75 FixedFormatter result;
76 if (paramType != null && paramValue != null) {
77 try {
78 result = formatterClass.getConstructor(paramType).newInstance(paramValue);
79 } catch (NoSuchMethodException e) {
80 result = null;
81 } catch (Exception e) {
82 throw new FixedFormatException("Could not create instance with one argument constructor", e);
83 }
84 } else {
85 try {
86 result = formatterClass.getConstructor().newInstance();
87 } catch (NoSuchMethodException e) {
88 result = null;
89 } catch (Exception e) {
90 throw new FixedFormatException("Could not create instance with no arg constructor", e);
91 }
92 }
93 return result;
94 }
95 }