Java - strip binary from text files

snotnose

Ars Praefectus
3,453
Subscriptor
I've got a program that uses BufferedReader to read it's data. About a year ago my input source started showing up with binary characters, which of course breaks. After spending time trying to figure out where the binary data is coming from with no joy, and living with a stopgap sed script that strips the binary, I want to fix my program.

I should note that after running my input data through my sed script, the resulting file is identical to the original source that was sent to me. I have no control over the process by which I get the input text file.

I should also note that all the inserted binary data is 0x80 or higher. I don't want to just clear the 0x80 bit, that results in junk in my text. I want to delete all characters 0x80 or higher.

I'm not a Java guru and haven't written Java in a couple years now, so I turn to you.

What would be the best way to read my data, strip the binary data, and return a record just like BufferedReader.getRecord() does (that is, a text line ending in CRLF)? I'm not worried about the regexp to strip the binary data, I'm just not sure how to get the file data into a buffer that I can filter.
 

fitten

Ars Legatus Legionis
55,632
Subscriptor++
Well... my first thoughts are that you should find out why your input has changed. It may be something that you need to respond to other than simply by removing it out. It may be valid/valuable information. Maybe they started using unicode or something.

Second, it should be easy to filter it out, but doing that just added a bit of processing requirements to your input. The most straightforward way is to just get the original input, create another (new) buffer, and copy the original input character by character into a new buffer, not copying any character that has a value higher than 0x80... and that assumes there is still a CRLF at the end of the input as before. Then pass that buffer to your record generator. Doing something simple like this, first, to make sure it's feasible, it works, etc. it probably what I would do first before trying anything 'fancy' (and spending more time on figuring that out) and making sure that it all works (i.e. that binary data is, indeed, meaningless/useless).

I suspect there is something more going on, though, and you are going to end up needing to know what that 'binary' data is in your stream.
 

hestermofet

Ars Legatus Legionis
25,464
I suspect there is something more going on, though, and you are going to end up needing to know what that 'binary' data is in your stream.

I dunno, having lived in the ETL world for a few years now, upstream clients sometimes just start sending you garbage data with no reason, no motivation to investigate why something's changed, nor any intention to fix it. So you just clean up after their mess. I once had a client who started sending me coupons and promotions dated for the future, and they were losing hundreds of thousands of dollars every time they appeared on their website because they had to honor them, but more importantly now their competitors know what sales and promotions they will have in the future, and the exact dates. But of course, it was our job to filter them out, not their job to figure out why they were exporting proprietary business information in an output meant for a third party. :rolleyes:
 

snotnose

Ars Praefectus
3,453
Subscriptor
Trust me, I spent time both on trying to figure out where the garbage data was coming from (gmail) and why it was being inserted (no clue, no other email has the issue).

It truly is garbage data, the sender didn't put it in, and it serves no purpose.

I'll probably use a FileStream to read a byte at a time, I was just hoping there was a library routine I didn't know about that would do the job.
 

fitten

Ars Legatus Legionis
55,632
Subscriptor++
I suspect there is something more going on, though, and you are going to end up needing to know what that 'binary' data is in your stream.

I dunno, having lived in the ETL world for a few years now, upstream clients sometimes just start sending you garbage data with no reason, no motivation to investigate why something's changed, nor any intention to fix it. So you just clean up after their mess. I once had a client who started sending me coupons and promotions dated for the future, and they were losing hundreds of thousands of dollars every time they appeared on their website because they had to honor them, but more importantly now their competitors know what sales and promotions they will have in the future, and the exact dates. But of course, it was our job to filter them out, not their job to figure out why they were exporting proprietary business information in an output meant for a third party. :rolleyes:

Yeah, that is actually a major breech of (a sane company's) corporate data policy. I would have escalated that a bit. In the past when I worked for a company that was a third-party consumer of data for corporate communications, a part of our contract was that we would come up with an enforced schema for data transfer. We had a basic envelope and package and could easily expand it for more things, but it was basically an XSD and we shared that with the sender. It was their responsibility to validate against the XSD before sending because we were always validating upon receipt. It really helped clear up things like "there was a bunch of stuff added that we know nothing about". However, I imagine ad information like you mention would just but (brainstorming) in a list of coupons in the envelope and would pass because they were valid coupons, just released before they should be.
 

fitten

Ars Legatus Legionis
55,632
Subscriptor++
Trust me, I spent time both on trying to figure out where the garbage data was coming from (gmail) and why it was being inserted (no clue, no other email has the issue).

It truly is garbage data, the sender didn't put it in, and it serves no purpose.

I'll probably use a FileStream to read a byte at a time, I was just hoping there was a library routine I didn't know about that would do the job.

I'd still advise on doing the easy thing first and then worry about optimizing *if* performance is a problem. I'm assuming you contacted the sender to ask where it was coming from? If the sender didn't put it in there but you are getting it, that's a massive red flag... is some man-in-the-middle attack going on?
 

snotnose

Ars Praefectus
3,453
Subscriptor
Again, the sender is most definitely not adding the binary data. Something in the email path from them to me is adding the binary data. I don't know if it's a UTF-8 thing, a MIME thing, or what. Point is we've looked into it, dunno where the crap is coming from, it only happens with this particular data stream, and quite frankly I'm tired of dealing with it.
 

fitten

Ars Legatus Legionis
55,632
Subscriptor++
Then I'd go back to what I recommended above... the quickest, easiest way to do it... just write your own for loop copying the stuff you want to a new buffer and skipping the rest. If that becomes a performance bottleneck worthy of messing with, then investigate other ways to do it. And also be prepared for more of the same type of issues/patches in the future as more of these mysterious injections occur.
 
I suspect there is something more going on, though, and you are going to end up needing to know what that 'binary' data is in your stream.

I dunno, having lived in the ETL world for a few years now, upstream clients sometimes just start sending you garbage data with no reason, no motivation to investigate why something's changed, nor any intention to fix it. So you just clean up after their mess. I once had a client who started sending me coupons and promotions dated for the future, and they were losing hundreds of thousands of dollars every time they appeared on their website because they had to honor them, but more importantly now their competitors know what sales and promotions they will have in the future, and the exact dates. But of course, it was our job to filter them out, not their job to figure out why they were exporting proprietary business information in an output meant for a third party. :rolleyes:

Yeah, that is actually a major breech of (a sane company's) corporate data policy. I would have escalated that a bit.
Well, what ended up happening was after I implemented features to filter out their garbage data, they sent coupons in a slightly different form that passed my filtering, so they got burned again because they were too lazy to do their job. Being my company's second biggest client, and the fact the client had an axe to grind against me to begin with, I ended up getting fired as the scapegoat. But that's ok, I'm at a way better, way more professional org now, with substantially better pay, benefits, and work life balance. I used to work 9-9 and on call, now I work 9-5 with 15% more pay, and my weekends are my own. Meanwhile, the company that fired me has been in "startup mode" for the past twelve years, still hasn't turned a profit, and they are actually losing money on their biggest client because the sales department led directly by the CEO way overpromised what they were able to deliver, and the contract they signed doesn't cover the GCP operating costs they were providing to the client. :p I remember I had to work the last week of Christmas one year when the rest of my team was on holiday, because the CEO promised some crazy feature that was impossible. Probably while he was drunk. :facepalm:
 
With very narrow exceptions, you don't fix corrupted data. You solve the data path issue.

(Those narrow exceptions are data paths (like radio links) with known/expected rates of error, using data correction, and validation routines.).

Fix your problem not your data.

These types of issues go for injected binary data to data-corrupting errors that aren't caught. How do you know all of the errors are causing binary data? Can you be sure a digit isn't being changed, or a flag being modified in the stream?

You can play wack a mole if you want, but that's not even close to best practices.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,343
Subscriptor++
With very narrow exceptions, you don't fix corrupted data. You solve the data path issue.

(Those narrow exceptions are data paths (like radio links) with known/expected rates of error, using data correction, and validation routines.).

Fix your problem not your data.

These types of issues go for injected binary data to data-corrupting errors that aren't caught. How do you know all of the errors are causing binary data? Can you be sure a digit isn't being changed, or a flag being modified in the stream?

You can play wack a mole if you want, but that's not even close to best practices.

Yes, this. At a minimum, you need to get a cryptographic checksum / ECC added to the incoming data. You have something that is corrupting your data, eventually it will corrupt it in a way that looks non-corrupt. When that happens, you could find yourself footing the bill all sorts of different ways.
 

snotnose

Ars Praefectus
3,453
Subscriptor
I'm 99% sure it's a character set conversion issue. The problem is we don't know from where, we have no control over 90% of the pipeline, and we don't know why it's only this particular email it happens to.

All we do know for sure is clean data goes in, bad data comes out.

Time to close this thread, I've already fixed my program. It's noticeably slower but not enough to spend more time on.
 

nahtaN

Seniorius Lurkius
21
Where is the email server? Is it Google? Or is it your own server?
Is this a multipart message(MIME)? Or is it plain text? What is the MIME type?
Have you checked the raw email message sent stored in the server? Does it have this?

I think the issue here is a lack of understanding of the email standard. I think what would favor you very well here is to find a Java library that would do this lower level work for you, like one from Oracle or Apache Commons. Read the message that comes from one out from one of these libraries and see if this solves your issue.
 

Drizzt321

Ars Legatus Legionis
34,920
Subscriptor++
I'm 99% sure it's a character set conversion issue. The problem is we don't know from where, we have no control over 90% of the pipeline, and we don't know why it's only this particular email it happens to.

All we do know for sure is clean data goes in, bad data comes out.

Time to close this thread, I've already fixed my program. It's noticeably slower but not enough to spend more time on.

Heh, yeah, charsets. *shudder*

Did you look to see if there's a BOM (byte-order-mark) at the start of the file? I've found that on Excel sometimes puts that on CSV exports. Or other applications. Or if the raw MIME message has a different charset than you're expecting? I've done the same thing, I found org.mozilla.universalchardet.UniversalDetector to be useful to get me the charset so I can pass that to an InputStreamReader to read/parse in the file just fine.


Code:
private static final String findCharacterEncoding(UniversalDetector detector, InputStream is) throws IOException {
        byte[] buf = new byte[1024];

        int nread;
        String encoding = null;

        while ((nread = is.read(buf)) > 0 && !detector.isDone()) {
            detector.handleData(buf, 0, nread);
        }
        detector.dataEnd();
        encoding = detector.getDetectedCharset();
        detector.reset();
        return encoding;
    }
 

KlrMowse

Ars Scholae Palatinae
1,245
hmmm... you're wanting to "strip" binary char hex 80 or higher (which is 128 or higher in decimal) from your String input, is what i gathered...

if i'm not mistaken, hex char 80 and higher belong to standard charset 'Extended ASCII' (character code 128 to 255)

...and there's standard charset 'ASCII' (character code 0 to 127), which are the characters that you want to keep


with these in mind, not sure what the output would look like - i've no sample input to try out... but maybe, once you have your String input, do something similar like:


byte [] bytesOfInput = BufferedReaderStringInput.getBytes(Charset.forName("ASCII"));




again, not sure what the data stored in byte array bytesOfInput would look like after invoking Charset.forName(); the idea is to hopefully just grab the appropriate charset (0-127)

...if the charset name is not "ASCII", am not sure what the Java standard charset name is for non-extended ASCII - a quick Google-search should turn it up
 

snotnose

Ars Praefectus
3,453
Subscriptor
Thanks for playing, problem solved, thread closed.

Except something came up last month that makes me think the problem is on the other end. Still nothing I can fix, but clears gmail of effing up. The guy that wrote the code at the other end died 2.5 years ago, my problem showed up 2 years ago, so. huh. At least when the new guy says "I haven't changed anything" (I really don't think he knowingly has, he's not technical enough) I can tell my cat "yeah right".

Anywhoo, problem solved thread closed.
 

snotnose

Ars Praefectus
3,453
Subscriptor
This thread is like a Stack Overflow question where the user gets a bunch of input from the community, fixes their issue, and then never bothers sharing what the actual problem was, or what ultimately solved it, but IS bothered enough to say "Yeah, I fixed it, bugger off"

As I said before, the problem is on the other end and I have no way to directly investigate, let alone fix it. My fix was to modify my Java program to not crash when I got binary data in my ascii file.
 

snotnose

Ars Praefectus
3,453
Subscriptor
So… string.replaceAll(“[^0-9a-zA-Z]”, “”)?

You left out the punctuation...

Aren't you supposed to be recovering from surgery or somesuch? Go watch General Hospital while you remember what I'm reading in isn't a string cuz it has binary data in it. Which is the problem.

I mean that with a big grin, glad you're getting better. But I really want this thread to die ASAP.