public static String canonical ( String url ) { String [ ] urlPath = toSegments ( url ) ; Stack < String > canonical = new Stack <> ( ) ; for ( String comp : urlPath ) { if ( comp . isEmpty ( ) || comp . equals ( CURRENT_DIR ) ) continue ; if ( ! comp . equals ( PARENT_DIR ) || ( ! canonical . empty ( ) && canonical . peek ( ) . equals ( PARENT_DIR ) ) ) canonical . push ( comp ) ; else canonical . pop ( ) ; } String prefixSep = url . startsWith ( SEPARATOR ) ? SEPARATOR : "" ; String trailingSep = url . endsWith ( SEPARATOR ) ? SEPARATOR : "" ; return prefixSep + canonical . stream ( ) . collect ( Collectors . joining ( SEPARATOR ) ) + trailingSep ; }
Create a canonical path that does not contain parent directories current directories or superfluous directory separators .