public static String decodeModifiedUTF7( byte[] encodeBuf ) {
if( encodeBuf == null ) {
return null;
}
StringBuffer result = new StringBuffer();
int count = encodeBuf.length;
for( int i = 0; i < count; ++i ) {
if( encodeBuf[i] != '&' ) {
result.append( (char) encodeBuf[i] );
continue;
}
++i;
if( encodeBuf[i] == '-' ) {
// "&-"が出現したということで "&"を格納.
result.append( "&" );
continue;
}
// "&"から始まるデータブロック.
// ここから "-"が出るまでは変則なBase64で格納されている.
StringBuilder buf = new StringBuilder();
boolean isBlockEnd = false;
do {
if( encodeBuf[i] == '-' ) {
isBlockEnd = true;
} else {
buf.append( (char) encodeBuf[i++] );
}
} while( isBlockEnd == false );
byte[] decodeBase64 = decodeModifiedUTF7asBase64( buf.toString() );
try {
result.append( new String( decodeBase64, "UTF-16") );
} catch( UnsupportedEncodingException e ) {
}
}
return result.toString();
}
private static byte[] decodeModifiedUTF7asBase64( String str ) {
// 修正UTF-7では ","が使われてるので戻す.
String buf = str.replace( ',', '/' );
byte[] ret = null;
try {
int paddingCount = 4 - str.length() & 0x03;
if( paddingCount == 4 ) {
// 詰め物なしでデコードできる.
ret = Base64.decode( buf.getBytes( "ASCII" ), Base64.DEFAULT );
} else {
StringBuilder sb = new StringBuilder(buf);
for( int i = 0; i < paddingCount; ++i ) {
sb.append( "=" );
}
ret = Base64.decode( sb.toString().getBytes( "ASCII" ), Base64.DEFAULT );
}
} catch( UnsupportedEncodingException e ) {
}
return ret;
}