public static String encode(final String input) {
        try {
            final StringBuilder b = new StringBuilder();
            final StringTokenizer t = new StringTokenizer(input, "/");
            if(!t.hasMoreTokens()) {
                return input;
            }
            if(StringUtils.startsWith(input, String.valueOf(Path.DELIMITER))) {
                b.append(Path.DELIMITER);
            }
            while(t.hasMoreTokens()) {
                b.append(URLEncoder.encode(t.nextToken(), StandardCharsets.UTF_8.name()));
                if(t.hasMoreTokens()) {
                    b.append(Path.DELIMITER);
                }
            }
            if(StringUtils.endsWith(input, String.valueOf(Path.DELIMITER))) {
                b.append(Path.DELIMITER);
            }
            // Because URLEncoder uses <code>application/x-www-form-urlencoded</code> we have to replace these
            // for proper URI percented encoding.
            return StringUtils.replaceEach(b.toString(),
                new String[]{"+", "*", "%7E", "%40"},
                new String[]{"%20", "%2A", "~", "@"});
        }
        catch(UnsupportedEncodingException e) {
            log.warn(String.format("Failure %s encoding input %s", e, input));
            return input;
        }
    }
@Test
    public void testEncodeTrailingDelimiter() {
        assertEquals("/a/p/", URIEncoder.encode("/a/p/"));
        assertEquals("/p%20d/", URIEncoder.encode("/p d/"));
    }