package com.perforce.hws.util; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Arrays; import java.util.stream.Collectors; /** * */ public interface StringUtils { SecureRandom secureRandom = new SecureRandom(); String SIMPLE_ENCODE_ILLEGAL_CHARS[] = {"~", "/", " ", "#", "?", ":"}; /** * Create a secure random string. */ default String randomString() { return new BigInteger(130, secureRandom).toString(32); } /** * Encodes a string in a way that can be reversed, and URI-encoded/decoded * into a single "path component". * <p> * This does *not* perform URI encoding, just ensures that the output can * be URI-encoded, and URI-decoded, then decoded via simpleDecode into * the original string. * <p> * The whole point of this method is to make it easy to have a string that * can be matched in a single path component and not a glob. * * @param s A string to be encoded, might have things like "/" that will * screw up URI parsers. * @param illegalChars The list of naughty characters we don't want. * @return The string with the bits replaced that cause typical problems. */ default String simpleEncode(String s, String[] illegalChars) { return s.chars().mapToObj(ch -> { String chStr = String.valueOf((char)ch); if (Arrays.asList(illegalChars).contains(chStr)) { return "~" + Integer.toHexString(ch); } else { return chStr; } }).collect(Collectors.joining("")); } /** * @see #simpleEncode(String, String[]) */ default String simpleEncode(String s) { return simpleEncode(s, SIMPLE_ENCODE_ILLEGAL_CHARS); } /** * Decodes a string encoded via simpleEncode. * * @param encoded The string already encoded via simpleEncode. * @param illegalChars Our list of characters to replace * @return The decoded string */ default String simpleDecode(String encoded, String[] illegalChars) { return Arrays.stream(illegalChars) .map(ill -> new String[]{ ill, "~" + ill.chars().mapToObj(c -> Integer.toHexString(c)) .collect(Collectors.joining("")) } ) .reduce(encoded, (dec, ill) -> dec.replace(ill[1], ill[0]), (x, y) -> x); } /** * @see #simpleDecode(String, String[]) */ default String simpleDecode(String s) { return simpleDecode(s, SIMPLE_ENCODE_ILLEGAL_CHARS); } }
# | Change | User | Description | Committed | |
---|---|---|---|---|---|
#1 | 19535 | drobins | Refactor package names to hws | ||
//guest/perforce_software/helix-web-services/main/source/jdk_extensions/src/main/java/com/perforce/helix_web_services/jdk_extensions/StringUtils.java | |||||
#1 | 17140 | tjuricek |
Integrating porting work from development branch. This work is now ready for testing/CD integration. |