The basic requirement of my code is to accept a file input, parse it, convert it to a java type (A DTO essentially) for use in another component of the system.
I should also note that I am not actually parsing a file from a filesystem, the FileParser will be used by a Message Driven Bean that has the contents of the file as a String already.
I am looking for input and general design/code review, thanks for your time.
I have 4 classes:
- FileParser
- Message
- MessageFactory
- MessageFieldTypes
The format of the file is as follows:
FIELDONETYPE/FIELDONEVALUE
FIELDTWOTYPE/FIELDTWOVALUE
FIELDTHREETYPE/FIELDTHREEVALUE
FIELDFOURTYPE/FIELDFOURVALUE
FIELDFIVETYPE/FIELDFIVEVALUE
etc.
There are roughly 20 fields.
My initial thought was to parse the file into a hashmap and then create the object. Here is the code listing for the parser:
final public class FileParser
{
public static final Message parse(String text) {
Map<MessageFieldTypes, String> map = new LinkedHashMap<MessageFieldTypes, String>();
for(String line : text.split(" *\n *")) {
String[] keyValuePair = line.split(" */ *");
map.put(MessageFieldTypes.valueOf(keyValuePair[0]),
keyValuePair.length == 1 ? "" : keyValuePair[1]);
}
return MessageFactory.createFromHashMap(map);
}
}
Here is the code listing for the factory:
public class MessageFactory {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("ddMMMyyyy");
public static Message createFromHashMap(Map<MessageFieldTypes, String> map) {
Message message = new Message();
message.setFieldOne(new FieldOneType(map.get(MessageFieldTypes.FIELDONE),
map.get(MessageFieldTypes.FIELDTWO),
DATE_TIME_FORMATTER.parseDateTime(map.get(MessageFieldTypes.FIELDTHREE)).toLocalDate()));
message.setFieldFour(new FieldFourType(map.get(MessageFieldTypes.FIELDFOUR)));
message.setFieldFive(map.get(MessageFieldTypes.FIELDFIVE)));
return message;
}
}
And the Enum:
public enum MessageFieldTypes {
FIELDONE,
FIELDTWO,
FIELDTHREE,
FIELDFOUR,
FIELDFIVE
}
LinkedHashMap
? – Michael K Jul 25 '11 at 4:38