Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Filter - whitespace trimmer misbehaves  RSS feed

 
John O'Hanley
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Making a Servlet filter for trimming the leading space char's on each line. The implementation is acting in a way I cannot explain. The correct trimming appears to be done according to the log statements on the server, but the source in the browser shows the whitespace as still remaining! How can this be? Very puzzling behaviour...

public byte[] replaceContent(byte [] aBytes) {
fLogger.fine("Modified Output Stream : replaceContent().");

//eliminate initial spaces and tabs
byte[] result = new byte[aBytes.length];
for( int idx = 0 ; idx < aBytes.length; ++ idx ){
byte character = aBytes[idx];
if ( ! fCanEliminateSpacesAndTabs ) {

result[idx] = character;
// if ( character != '5' ) { //drop '5's as expected!
// result[idx] = character;
// }

if (character == '\r' || character == '\n') {
fCanEliminateSpacesAndTabs = true;
}
}
else {
if ( character == ' ' || character == '\t' ) {
//result[idx] = 'x'; //replaces spaces with x's as expected
//result[idx] = '\t'; //works as expected - replaces spaces with tabs
//result[idx] = '\u0000'; //logs OK, browser source not OK
//result[idx] = 0; //logs OK, browser source not OK
//when I 'do nothing' here to *drop* the whitespace, log shows OK, browser not OK - whitespaces reappears!!!
}
else {
result[idx] = character;
if ( character != '\r' && character != '\n' ) {
fCanEliminateSpacesAndTabs = false;
}
}
}
}
//This shows the desired result in the log, but served text still
//has initial spaces. why?
fLogger.fine("Result: " + new String(result)); //shows desired result!!
return result;
}
 
John O'Hanley
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Better formatting here :

 
John O'Hanley
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Found the problem.

String(byte[]) will apparently *eliminate* null items in the array. The servlet container was using the raw byte[], and leaves nulls in, in some form or other. The nulls are translated into empty spaces somewhere along the way.

See the javadoc for String(byte[]), which says :
"The behavior of this constructor when the given bytes are not valid in the default charset is unspecified"

The fix was push the nulls to the end of the array, and to trim them off at the end.

The corrected code reads as :
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!