litesoft
@ 948
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
package org.litesoft.sandbox.csapp.server; import java.io.*; public class SmallFileValidatorOnlyDisplayable7BitAscii implements SmallFileValidator { public static final SmallFileValidator INSTANCE = new SmallFileValidatorOnlyDisplayable7BitAscii(); @Override public AcceptedResult validate( String fileName, byte[] contents ) throws UnsupportedEncodingException { String text = new String( contents, "UTF-8" ); for ( int i = 0; i < text.length(); i++ ) { char c = text.charAt( i ); if ( (' ' <= c) && (c <= 126) ) { continue; } if ( c == '\r' || c == '\n' ) { continue; } throw new UnsupportedEncodingException( "Only Supporting a limited subset of 7-bit Ascii" ); } return new AcceptedResult( fileName, convertNewLines( text ), encode( text ) ); } private String convertNewLines( String text ) { int at = text.indexOf( "\r\n" ); if ( at != -1 ) { StringBuilder sb = new StringBuilder( text ); do { sb.deleteCharAt( at ); } while ( -1 != (at = sb.indexOf( "\r\n" )) ); text = sb.toString(); } return text.replace( '\r', '\n' ); } private String encode( String text ) { StringBuilder sb = new StringBuilder( text.length() + text.length() ); for ( int i = 0; i < text.length(); i++ ) { int c = text.charAt( i ); sb.append( HEX.charAt( (c >> 4) & 15 ) ); sb.append( HEX.charAt( c & 15 ) ); } return sb.toString(); } private static String HEX = "0123456789ABCDEF"; } |