public static String toPackageName ( String nsUri ) { if ( nsUri == null || nsUri . length ( ) == 0 ) { return null ; } // remove scheme and :, if present // spec only requires us to remove 'http' and 'urn'... int idx = nsUri . indexOf ( ' ' ) ; String scheme = "" ; if ( idx >= 0 ) { scheme = nsUri . substring ( 0 , idx ) ; if ( scheme . equalsIgnoreCase ( "http" ) || scheme . equalsIgnoreCase ( "urn" ) ) nsUri = nsUri . substring ( idx + 1 ) ; } // tokenize string List < String > tokens = tokenize ( nsUri , "/: " ) ; if ( tokens . size ( ) == 0 ) { return null ; } // remove trailing file type, if necessary if ( tokens . size ( ) > 1 ) { // for uri's like "www.foo.com" and "foo.com", there is no trailing // file, so there's no need to look at the last '.' and substring // otherwise, we loose the "com" (which would be wrong) String lastToken = tokens . get ( tokens . size ( ) - 1 ) ; idx = lastToken . lastIndexOf ( ' ' ) ; if ( idx > 0 ) { lastToken = lastToken . substring ( 0 , idx ) ; tokens . set ( tokens . size ( ) - 1 , lastToken ) ; } } // tokenize domain name and reverse. Also remove :port if it exists String domain = tokens . get ( 0 ) ; idx = domain . indexOf ( ' ' ) ; if ( idx >= 0 ) domain = domain . substring ( 0 , idx ) ; ArrayList < String > r = reverse ( tokenize ( domain , scheme . equals ( "urn" ) ? ".-" : "." ) ) ; if ( r . get ( r . size ( ) - 1 ) . equalsIgnoreCase ( "www" ) ) { // remove leading www r . remove ( r . size ( ) - 1 ) ; } // replace the domain name with tokenized items tokens . addAll ( 1 , r ) ; tokens . remove ( 0 ) ; // iterate through the tokens and apply xml->java name algorithm for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { // get the token and remove illegal chars String token = tokens . get ( i ) ; token = removeIllegalIdentifierChars ( token ) ; // this will check for reserved keywords if ( keywords . contains ( token . toLowerCase ( ) ) ) { token = ' ' + token ; } tokens . set ( i , token . toLowerCase ( ) ) ; } // concat all the pieces and return it return combine ( tokens , ' ' ) ; }
Create a java package name out of an XML namespace .