Text File Parsing/Processing

Status
Not open for further replies.
Okay --

So, I have some Java code which creates a file, then runs one of several external binaries upon that file using exec. The external binary reads the provided file, does its processing, then dumps its output into a file which the Java portion reads, parses and presses on with processing.

The output from the various binaries has a fixed, common part and an optional binary-specific part.

The problem is that the way that these things are described are 'hard-coded' in String.substring() calls. For example, if there are fields named 'date' and 'record_id' it would look something like:
Code:
date = inputLine.substring(0, 6);
record_id = inputLine.substring(6, 15);
This repeats for every field in the input format.

I would like to be able to describe the format, field names, etc., in a better way than using these hard-coded values.

I've been going down the line of two format Strings -- one for the fixed, common part and one for the variable part -- and two String arrays for the common and variable field names.

Code:
static final String COMMON_FORMAT = "%6s%9s";
static final String[] COMMON_FIELDS = { "DATE", "RECORD_ID" };

(Note: Very simplified example, but I'm looking at up to a couple dozen of these fields.)

Then work through the format ... somehow ... using the Scanner class.

But now that I'm working on it, this gets tedious really quick.

I'm wondering if there's a better way ...

Thanks in advance,
 
agifford and fitten":y399n1sy said:

Well, I'm not having trouble doing the parsing, what I *AM* having trouble with is how to map the parsed data to appropriate fields (or even a Map<String, String> structure) so that for every parsed field, I can easily look it up.

How would I use the REGEX named groups and map them to a usable data structure?

:confused:
 

agifford

Ars Tribunus Militum
2,142
zelmak":3or83itg said:
agifford and fitten":3or83itg said:

Well, I'm not having trouble doing the parsing, what I *AM* having trouble with is how to map the parsed data to appropriate fields (or even a Map<String, String> structure) so that for every parsed field, I can easily look it up.

How would I use the REGEX named groups and map them to a usable data structure?

:confused:

Nevermind, i thought java could return your named groups as a map like python could. Apparently java won't return you the names of the groups. You'd have to use a 3rd party regex library to get them to work, http://stackoverflow.com/questions/4155 ... ps-in-java

Then i would have used some reflection or something to turn that map<groupname, matched value> into objects. But thats moot at this point.
 
Had a problem similar to this in C# a little while ago, what I ended up doing was writing a framework where a generic mapping class would use collections of field definition objects to read the data. I defined several different generic string field mappings either using Regular expressions or other criteria (line numbers, column, and length etc.) to get the data from the source and then extended the string objects to parse other data formats.

Worked quite well.
 

fitten

Ars Legatus Legionis
55,636
Subscriptor++
Yeah... I wrote a Copybook file parsing library sometime back. It wasn't that fun but did pretty much what you describe. It would read in schema definitions and parse fixed width field data files. It would read the record (line), determine what type of line/record it was, load the appropriate definition, and parse the line. Of course, it would also have to understand the line groupings (each line wasn't necessarily a complete record... a "record" would consist of multiple lines in the file, each one parsed appropriately).
 
Bear with me if I sound crazy here, but I agree with Ravensroke

It sounds like you're trying to be "lazy" and not do proper OOP, create classes, and objects to define the structure of the objects you're dealing with, choosing instead for a "one-line-fix" of Regex, which is bound to cause more problems in the future.

"If you can't find time to do it right the first time, how are you going to find time to do it right the second"

"Use the right tool for the right job"

I don't think Regex is your solution, and I think you're perceiving text-parsing as your problem, when it looks like a lack of pre-planning is your problem.
 
Ravensroke":1thotsfi said:
Had a problem similar to this in C# a little while ago, what I ended up doing was writing a framework where a generic mapping class would use collections of field definition objects to read the data. I defined several different generic string field mappings either using Regular expressions or other criteria (line numbers, column, and length etc.) to get the data from the source and then extended the string objects to parse other data formats.

Worked quite well.

I think this is what I want and what I was trying to accomplish with my code above. I think I just need to externalize it from the classes that need the functionality.

Errr now reading your question a bit more closely, why not stick the numbers into an xml configuration file? That will let you tweak it for small changes. Big changes, you'll need to re-do some code anyway.

Well, as we already have over 120 configuration files for the system, AND my ranting about having too much "immutable configuration" (i.e., configuration items that rarely, if ever, change), I'm loathe to add additional configuration files at this point -- would be bad for my rep. :) I might have to bite the bullet, though.

Why so much config? Justification I've been given: (1) Hastens development so we don't have to recompile (a full build takes less than 5 minutes, small changes, much less, obviously), (2) Configuration doesn't need to be tested (this bit us on the butt a couple weeks ago when a configuration item was removed that apparently the system really really needed.) For instance, we have an object which operates like an enum, but the acceptable values for each entry come from a configuration file... which hasn't changed for nearly 10 years. (Did I mention this is a legacy system?)

fitten":1thotsfi said:
Yeah... I wrote a Copybook file parsing library sometime back. It wasn't that fun but did pretty much what you describe. It would read in schema definitions and parse fixed width field data files. It would read the record (line), determine what type of line/record it was, load the appropriate definition, and parse the line. Of course, it would also have to understand the line groupings (each line wasn't necessarily a complete record... a "record" would consist of multiple lines in the file, each one parsed appropriately).

Hrrmmmm... we have a similar facility in this project, but I'm fairly certain that it is delimiter-based; I don't believe it is flexible enough to support fixed-width fields. I'll take a look, though. Granted, I'll need to :gulp: add configuration files to support it. :sigh:

Would either of your libraries/projects be available for me to take a look at so I can steal borrow some ideas instead of re-inventing the wheel?
 
Suicidolt":h0hapt6k said:
Bear with me if I sound crazy here, but I agree with Ravensroke

It sounds like you're trying to be "lazy" and not do proper OOP, create classes, and objects to define the structure of the objects you're dealing with, choosing instead for a "one-line-fix" of Regex, which is bound to cause more problems in the future.

"If you can't find time to do it right the first time, how are you going to find time to do it right the second"

"Use the right tool for the right job"

I don't think Regex is your solution, and I think you're perceiving text-parsing as your problem, when it looks like a lack of pre-planning is your problem.

:sigh: moonshark ate my post AGAIN...

This is a legacy system, written in Java by C programmers (who didn't fully understand OOP) with the facilities available in Java 1.1 (every data structure is a raw, untyped Vector or a Hashtable). The code suffers from YAWA (yet another work-around) additions over the life of the project (started circa 1998); programmers prior to me were afraid to refactor stuff (and rightly so; this is some fragile stuff) so they just shoved changes in where they worked. There are no unit tests. I'm unable to make sweeping changes (due more to lack of unit tests and fragility than policy.) What I can do, however, is take some of the WTF-ness out of this morass of WTF-ery, add a smattering of 'common sense' to the code and refactor a bit here and there to make it more understandable and therefore more maintainable.

So, yes, I guess your statement about pre-planning being the problem is true. But I have what I have.

It isn't obvious to me how adding more classes and OOP would solve the problem of converting fixed-width text files into Java-accessible data structures. I'm quite open to any suggestions, however -- which is the reason for my original post.
 

Afty

Ars Scholae Palatinae
1,434
This won't help you directly because there is no Java version, but a professor at my university built a system called PADS (www.padsproj.org) that automatically generates a parser from a description of the input format. It was used inside AT&T Research, so it's more polished than most academic projects. It currently can generate parsers in C, ML, and Haskell.
 
Well, here's what I've worked through on my own, so far.

An object to represent the range of the string of which I'm concerned:
Code:
public class SubstringSlice { 
  private int start, width;
  public SubstringSlice(int start, int width) {
    this.start = start;
    this.width = width;
  }

  public int getStart() { 
    return start;
  }

  public int getWidth() {
    return width;
  }

  public int getEnd() {
    return start + width;
  }
}


An object to map field names to their slices:
Code:
public class FixedFieldMap implements Map {
  Map<String, SubstringSlice> map = new HashMap<String, SubstringSlice>();

  // all the stuff from Map forwarded to map

  getFieldValue(String fieldName, String inputLine) {
    SubstringSlice range = map.get(fieldName);
    String value = null;
    if (range != null) {
      value = inputLine.substring(range.getStart(), range.getEnd());
    }
    return value;
  }
}

An object representing the common input case; parses the fields in common from all input formats
Code:
public class CommonCase {
  protected Map<String, String> dataMap = new HashMap<String, String>();
  private FixedFieldMap commonFieldMap = new FixedFieldMap();

  protected static final String DATE = "DATE";
  protected static final String RECORD_ID = "RECORD_ID";

  static {  // static initializer
    commonfieldMap.put(DATE, new SubstringSlice(0, 6));
    commonfieldMap.put(RECORD_ID, new SubStringSlice(6, 14));
  }

  public CommonCase(String inputLine) {
    // populate the data map from the given input line
    for ( Map.Entry<String, SubstringSlice> entry : commonFieldMap.entrySet() ) {
      String fieldName = entry.getKey();
      SubstringSlice range = entry.getValue();
      String value = inputLine.substring(range.getStart(), range.getEnd());
      dataMap.put(fieldName, value);
    }
  }
}

Object(s) representing specific format(s); uses CommonCase 'parser' for common fields and local parser for specific fields
Code:
public class SpecificCase extends CommonCase {

  private static final FixedFieldMap localFieldMap = new FixedFieldMap();

  protected static final String BIRD_TYPE = "BIRD_TYPE";
  protected static final String LADEN_AIR_SPEED = "AIR_SPEED_LADEN";
  protected static final String UNLADEN_AIR_SPEED = "AIR_SPEED_UNLADEN";

  static {   // static initializer
    localFieldMap.put(BIRD_TYPE, new SubstringSlice(24, 12));
    localFieldMap.put(AIR_SPEED_LADEN, new SubstringSlice(36, 5));
    localFieldMap.put(AIR_SPEED_UNLADEN, new SubstringSlice(41, 5));
  }

  public SpecificCase(String inputLine) {
    super(inputLine)
    // populate the data map from the given input line
    for ( Map.Entry<String, SubstringSlice> entry : localFieldMap.entrySet() ) {
      String fieldName = entry.getKey();
      SubstringSlice range = entry.getValue();
      String value = inputLine.substring(range.getStart(), range.getEnd());
      dataMap.put(fieldName, value);
    }
  }

  public formatSpecificProcess() {
    // do stuff with the format specific data
  }
}

Of course, for 'flexibility', instead of using literal strings in the field names, I use named constant strings. (And yes, I know my ranges are not necessarily contiguous and there's currently no error-checking to ensure that the ranges overlap [feature?])

They are able to parse input appropriately. Now I'm working on making the output work. It seems I need to now worry about zero- and space-padding. :sigh:

Comments?
 

Afty

Ars Scholae Palatinae
1,434
Jackass JoeJoe":129kg9yd said:
Afty":129kg9yd said:
... but a professor at my university built a system called PADS (http://www.padsproj.org) that automatically generates a parser from a description of the input format ...

You mean he re-invented the wheel? The irony of YACC never ceases to amaze me.
From one of the PADS papers:
Traditional parsing systems such as YACC generate parsers from declarative specifications; however, they are not particularly well suited for writing data descriptions. In particular, such systems generally require users to write a separate lexer and construct inmemory data structures by hand. They typically only work on ASCII data and do not allow data-dependent parsing.

Also, the professor is a she.
 
Afty":7hf63mex said:
This won't help you directly because there is no Java version, but a professor at my university built a system called PADS (http://www.padsproj.org) that automatically generates a parser from a description of the input format. It was used inside AT&T Research, so it's more polished than most academic projects. It currently can generate parsers in C, ML, and Haskell.

Well, my wonderful proxy at work blocks everything that hasn't been classified by websense (or whoever they're using) so I'll have to remember to check this out at home.

I wonder if they're looking for a Java version. :)
 
given how much code you've probably already written, and the depth of the problem as it is starting to sound based on how you've described it, take my comments here with a grain of salt. I don't know what you're actually working with, and so at best, this is purely abstract anyway. But here is what I'm seeing.

zelmak":10wnnlc7 said:
It isn't obvious to me how adding more classes and OOP would solve the problem of converting fixed-width text files into Java-accessible data structures.

Yeah, this is what I thought you were doing. If I read your post correctly, you have access to all 3 parts of the code, the initial setup, the program that converts it, and the output.

What you should be doing (or rather, what those people who first wrote it should have done), is in the initial setup stage, creating the "parts" as objects (rather than, as above, doing so after the code is finished). You then kick it over to the "parser" and, knowing what it does, you shouldn't have any issue keeping your object structure from input to output (i.e. You're submitting a group of objects to the parser, and so the text that comes back is already partially parsed *I also liked the xml suggestions*). Since you know what the parser does, so well, your initial object should have properties in it that reference the different changes that could be made in the parser, and your output would have to fit these properties in EVERY case, not just "most".

Now I feel like an idiot, I feel like I'm trying to explain basic oop to a 5 year old, and from the sound of it you know what you're doing. It's still fairly early, so I'm going to blame a lack of coffee. I'm no java expert, but have a look at this: http://download.oracle.com/javase/6/doc ... owSet.html
 
Suicidolt":1e73jy2a said:
... creating the "parts" as objects (rather than, as above, doing so after the code is finished). You then kick it over to the "parser" and, knowing what it does, you shouldn't have any issue keeping your object structure from input to output (i.e. You're submitting a group of objects to the parser, and so the text that comes back is already partially parsed *I also liked the xml suggestions*)...

So ... each field would be an object, with settings defining where it falls in the input string, which justification model it uses, the ultimate data type? This would break down for us as we have several different child-objects which have the same field names but are located in different parts of the input string (yes, yes, I know, normalization of the input ... :sigh:)

Sadly, it sounds like we're re-creating a DBMS schema >.< (and it feels that tedious as I code it.)

The thing I don't like about using configuration files in this case is the disconnect between known field names and the actual code which uses them. If the config file has 'AIR_SPEED_LADEN' as a field name, and the coder expects 'LADEN_AIR_SPEED' (as I notice now I screwed up in my example above) you won't see that until you do developmental test (which we have very little of until we get to integration) instead of at coding/compile time. The 'field name knowledge' is now captured and/or used in two very different places. Goes against the grain for me.
 
With C# I took a page from various projects that used fluent configuration and did something like so:

Code:
public class Entity
{
	public string somefield { get; set; }
	public string otherfield { get; set; }
}

public class EntityMappings : FieldMappings<Entity>
{
	public EntityMappings()
	{
		Map(x => x.somefield).To(new StringField(line: 1, col: 10, length: 5));
		Map(x => x.otherfield).To(new RegexStringField(new Regex(@"linenoise")));
	}
}

public static void Main(string[] args)
{
	var mappings = new EntityMappings();
	var input = File.ReadAllLines("somefile");
	
	Entity result = mappings.Parse(input);
}

With extensions for stuff like tabular data and so on and so forth. It was done on company time so I probably won't ever be able to open-source it unfortunately.
 
Javolution provides a set of Struct and Union classes that you can probably use directly (Just create a Struct containing fixed length UTF8 strings) but if you look at the source you could also just steal the way that it handles defining the format and giving names to the fields within each Struct. I'm not sure how performant it actually is (it was more than fast enough for the code that I was writing), but it does give you the name and typesafety that you're looking for.
 

Redshift

Ars Scholae Palatinae
1,260
I personally would write a utility that takes bob-source.txt and bob-config.xml and returns a collection of Bob objects, like so.

Code:
   List<Bob> bobs = Thingy.parse("/dir/bob-source.txt", "bob-config.xml");

But if you really don't like config files this could be replace with.

Code:
   List<Bob> bobs = Thingy.parse("/dir/bob-source.txt", new ThingyConfigBuilder().add("property1", propDef).
              add("property2", propdef2).
              add("property3", propdef3).build();


You shouldn't be worried about hard coding "property3", either as input to the config builder, or in in a configuration file because every time you use Thingy you are going to write a Thingy_UT which thoroughly and exhaustively tests every field, and which is run automatically after each check in. Seriously. Anything less is armature hour.

Of course this has all been written before, and is out there somewhere...

My 2 cents.
 
Status
Not open for further replies.