|
| 1 | +package com.launchdarkly.sdk; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +import com.google.gson.annotations.JsonAdapter; |
| 7 | +import com.launchdarkly.sdk.json.JsonSerializable; |
| 8 | + |
| 9 | +/** |
| 10 | + * An attribute name or path expression identifying a value within an {@link LDContext}. |
| 11 | + * <p> |
| 12 | + * Applications are unlikely to need to use the AttributeRef type directly, but see below |
| 13 | + * for details of the string attribute reference syntax used by methods like |
| 14 | + * {@link ContextBuilder#privateAttributes(String...)}. |
| 15 | + * <p> |
| 16 | + * The reason to use this type directly is to avoid repetitive string parsing in code where |
| 17 | + * efficiency is a priority; AttributeRef parses its contents once when it is created, and |
| 18 | + * is immutable afterward. If an AttributeRef instance was created from an invalid string, |
| 19 | + * it is considered invalid and its {@link #getError()} method will return a non-null error. |
| 20 | + * <p> |
| 21 | + * The string representation of an attribute reference in LaunchDarkly JSON data uses the |
| 22 | + * following syntax: |
| 23 | + * <ul> |
| 24 | + * <li> If the first character is not a slash, the string is interpreted literally as an |
| 25 | + * attribute name. An attribute name can contain any characters, but must not be empty. </li> |
| 26 | + * <li> If the first character is a slash, the string is interpreted as a slash-delimited |
| 27 | + * path where the first path component is an attribute name, and each subsequent path |
| 28 | + * component is the name of a property in a JSON object. Any instances of the characters "/" |
| 29 | + * or "~" in a path component are escaped as "~1" or "~0" respectively. This syntax |
| 30 | + * deliberately resembles JSON Pointer, but no JSON Pointer behaviors other than those |
| 31 | + * mentioned here are supported. </li> |
| 32 | + * </ul> |
| 33 | + */ |
| 34 | +@JsonAdapter(AttributeRefTypeAdapter.class) |
| 35 | +public final class AttributeRef implements JsonSerializable, Comparable<AttributeRef> { |
| 36 | + private static final Map<String, AttributeRef> COMMON_LITERALS = makeLiteralsMap( |
| 37 | + "kind", "key", "name", "anonymous", // built-ins |
| 38 | + "email", "firstName", "lastName", "country", "ip", "avatar" // frequently used custom attributes |
| 39 | + ); |
| 40 | + |
| 41 | + private final String error; |
| 42 | + private final String rawPath; |
| 43 | + private final String singlePathComponent; |
| 44 | + private final String[] components; |
| 45 | + |
| 46 | + private AttributeRef(String rawPath, String singlePathComponent, String[] components) { |
| 47 | + this.error = null; |
| 48 | + this.rawPath = rawPath == null ? "" : rawPath; |
| 49 | + this.singlePathComponent = singlePathComponent; |
| 50 | + this.components = components; |
| 51 | + } |
| 52 | + |
| 53 | + private AttributeRef(String error, String rawPath) { |
| 54 | + this.error = error; |
| 55 | + this.rawPath = rawPath == null ? "" : rawPath; |
| 56 | + this.singlePathComponent = null; |
| 57 | + this.components = null; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Creates an AttributeRef from a string. For the supported syntax and examples, see |
| 62 | + * comments on the {@link AttributeRef} type. |
| 63 | + * <p> |
| 64 | + * This method always returns an AttributeRef that preserves the original string, even if |
| 65 | + * validation fails, so that calling {@link #toString()} (or serializing the AttributeRef |
| 66 | + * to JSON) will produce the original string. If validation fails, {@link #getError()} will |
| 67 | + * return a non-null error and any SDK method that takes this AttributeRef as a parameter |
| 68 | + * will consider it invalid. |
| 69 | + * |
| 70 | + * @param refPath an attribute name or path |
| 71 | + * @return an AttributeRef |
| 72 | + * @see #fromLiteral(String) |
| 73 | + */ |
| 74 | + public static AttributeRef fromPath(String refPath) { |
| 75 | + if (refPath == null || refPath.isEmpty() || refPath.equals("/")) { |
| 76 | + return new AttributeRef(Errors.ATTR_EMPTY, refPath); |
| 77 | + } |
| 78 | + if (refPath.charAt(0) != '/') { |
| 79 | + // When there is no leading slash, this is a simple attribute reference with no character escaping. |
| 80 | + return new AttributeRef(refPath, refPath, null); |
| 81 | + } |
| 82 | + if (refPath.indexOf('/', 1) < 0) { |
| 83 | + // There's only one segment, so this is still a simple attribute reference. However, we still may |
| 84 | + // need to unescape special characters. |
| 85 | + String unescaped = unescapePath(refPath.substring(1)); |
| 86 | + if (unescaped == null) { |
| 87 | + return new AttributeRef(Errors.ATTR_INVALID_ESCAPE, refPath); |
| 88 | + } |
| 89 | + return new AttributeRef(refPath, unescaped, null); |
| 90 | + } |
| 91 | + if (refPath.endsWith("/")) { |
| 92 | + // String.split won't behave properly in this case |
| 93 | + return new AttributeRef(Errors.ATTR_EXTRA_SLASH, refPath); |
| 94 | + } |
| 95 | + String[] parsed = refPath.substring(1).split("/"); |
| 96 | + for (int i = 0; i < parsed.length; i++) { |
| 97 | + String p = parsed[i]; |
| 98 | + if (p.isEmpty()) { |
| 99 | + return new AttributeRef(Errors.ATTR_EXTRA_SLASH, refPath); |
| 100 | + } |
| 101 | + String unescaped = unescapePath(p); |
| 102 | + if (unescaped == null) { |
| 103 | + return new AttributeRef(Errors.ATTR_INVALID_ESCAPE, refPath); |
| 104 | + } |
| 105 | + parsed[i] = unescaped; |
| 106 | + } |
| 107 | + return new AttributeRef(refPath, null, parsed); |
| 108 | + } |
| 109 | + |
| 110 | + /** |
| 111 | + * Similar to {@link #fromPath(String)}, except that it always interprets the string as a literal |
| 112 | + * attribute name, never as a slash-delimited path expression. |
| 113 | + * <p> |
| 114 | + * There is no escaping or unescaping, even if the name contains literal '/' or '~' characters. |
| 115 | + * Since an attribute name can contain any characters, this method always returns a valid |
| 116 | + * AttributeRef unless the name is empty. |
| 117 | + * <p> |
| 118 | + * For example: {@code AttributeRef.fromLiteral("name")} is exactly equivalent to |
| 119 | + * {@code AttributeRef.fromPath("name")}. {@code AttributeRef.fromLiteral("a/b")} is exactly |
| 120 | + * equivalent to {@code AttributeRef.fromPath("a/b")} (since the syntax used by |
| 121 | + * {@link #fromPath(String)} treats the whole string as a literal as long as it does not start |
| 122 | + * with a slash), or to {@code AttributeRef.fromPath("/a~1b")}. |
| 123 | + * |
| 124 | + * @param attributeName an attribute name |
| 125 | + * @return an AttributeRef |
| 126 | + * @see #fromPath(String) |
| 127 | + */ |
| 128 | + public static AttributeRef fromLiteral(String attributeName) { |
| 129 | + if (attributeName == null || attributeName.isEmpty()) { |
| 130 | + return new AttributeRef(Errors.ATTR_EMPTY, ""); |
| 131 | + } |
| 132 | + if (attributeName.charAt(0) != '/') { |
| 133 | + // When there is no leading slash, this is a simple attribute reference with no character escaping. |
| 134 | + AttributeRef internedInstance = COMMON_LITERALS.get(attributeName); |
| 135 | + return internedInstance == null ? new AttributeRef(attributeName, attributeName, null) : internedInstance; |
| 136 | + } |
| 137 | + // If there is a leading slash, then the attribute name actually starts with a slash. To represent it |
| 138 | + // as an AttributeRef, it'll need to be escaped. |
| 139 | + String escapedPath = "/" + attributeName.replace("~", "~0").replace("/", "~1"); |
| 140 | + return new AttributeRef(escapedPath, attributeName, null); |
| 141 | + } |
| 142 | + |
| 143 | + /** |
| 144 | + * True for a valid AttributeRef, false for an invalid AttributeRef. |
| 145 | + * <p> |
| 146 | + * An AttributeRef can only be invalid for the following reasons: |
| 147 | + * <ul> |
| 148 | + * <li> The input string was empty, or consisted only of "/". </li> |
| 149 | + * <li> A slash-delimited string had a double slash causing one component to be empty, such as "/a//b". </li> |
| 150 | + * <li> A slash-delimited string contained a "~" character that was not followed by "0" or "1". </li> |
| 151 | + * </ul> |
| 152 | + * <p> |
| 153 | + * Otherwise, the AttributeRef is valid, but that does not guarantee that such an attribute exists |
| 154 | + * in any given {@link LDContext}. For instance, {@code fromLiteral("name")} is a valid AttributeRef, |
| 155 | + * but a specific {@link LDContext} might or might not have a name. |
| 156 | + * <p> |
| 157 | + * See comments on the {@link AttributeRef} type for more details of the attribute reference synax. |
| 158 | + * |
| 159 | + * @return true if the instance is valid |
| 160 | + * @see #getError() |
| 161 | + */ |
| 162 | + public boolean isValid() { |
| 163 | + return error == null; |
| 164 | + } |
| 165 | + |
| 166 | + /** |
| 167 | + * Null for a valid AttributeRef, or a non-null error message for an invalid AttributeRef. |
| 168 | + * <p> |
| 169 | + * If this is null, then {@link #isValid()} is true. If it is non-null, then {@link #isValid()} is false. |
| 170 | + * |
| 171 | + * @return an error string or null |
| 172 | + * @see #isValid() |
| 173 | + */ |
| 174 | + public String getError() { |
| 175 | + return error; |
| 176 | + } |
| 177 | + |
| 178 | + /** |
| 179 | + * The number of path components in the AttributeRef. |
| 180 | + * <p> |
| 181 | + * For a simple attribute reference such as "name" with no leading slash, this returns 1. |
| 182 | + * <p> |
| 183 | + * For an attribute reference with a leading slash, it is the number of slash-delimited path |
| 184 | + * components after the initial slash. For instance, {@code AttributeRef.fromPath("/a/b").getDepth()} |
| 185 | + * returns 2. |
| 186 | + * <p> |
| 187 | + * For an invalid attribute reference, it returns zero |
| 188 | + * |
| 189 | + * @return the number of path components |
| 190 | + */ |
| 191 | + public int getDepth() { |
| 192 | + if (error != null) { |
| 193 | + return 0; |
| 194 | + } |
| 195 | + return components == null ? 1 : components.length; |
| 196 | + } |
| 197 | + |
| 198 | + /** |
| 199 | + * Retrieves a single path component from the attribute reference. |
| 200 | + * <p> |
| 201 | + * For a simple attribute reference such as "name" with no leading slash, getComponent returns the |
| 202 | + * attribute name if index is zero, and null otherwise. |
| 203 | + * <p> |
| 204 | + * For an attribute reference with a leading slash, if index is non-negative and less than |
| 205 | + * {@link #getDepth()}, getComponent returns the path component string at that position. |
| 206 | + * |
| 207 | + * @param index the zero-based index of the desired path component |
| 208 | + * @return the path component, or null if not available |
| 209 | + */ |
| 210 | + public String getComponent(int index) { |
| 211 | + if (components == null) { |
| 212 | + return index == 0 ? singlePathComponent : null; |
| 213 | + } |
| 214 | + return index < 0 || index >= components.length ? null : components[index]; |
| 215 | + } |
| 216 | + |
| 217 | + /** |
| 218 | + * Returns the attribute reference as a string, in the same format used by |
| 219 | + * {@link #fromPath(String)}. |
| 220 | + * <p> |
| 221 | + * If the AttributeRef was created with {@link #fromPath(String)}, this value is identical to |
| 222 | + * to the original string. If it was created with {@link #fromLiteral(String)}, the value may |
| 223 | + * be different due to unescaping (for instance, an attribute whose name is "/a" would be |
| 224 | + * represented as "~1a"). |
| 225 | + * |
| 226 | + * @return the attribute reference string (guaranteed non-null) |
| 227 | + */ |
| 228 | + @Override |
| 229 | + public String toString() { |
| 230 | + return rawPath; |
| 231 | + } |
| 232 | + |
| 233 | + @Override |
| 234 | + public boolean equals(Object other) { |
| 235 | + if (other instanceof AttributeRef) { |
| 236 | + AttributeRef o = (AttributeRef)other; |
| 237 | + return rawPath.equals(o.rawPath); |
| 238 | + } |
| 239 | + return false; |
| 240 | + } |
| 241 | + |
| 242 | + @Override |
| 243 | + public int hashCode() { |
| 244 | + return rawPath.hashCode(); |
| 245 | + } |
| 246 | + |
| 247 | + @Override |
| 248 | + public int compareTo(AttributeRef o) { |
| 249 | + return rawPath.compareTo(o.rawPath); |
| 250 | + } |
| 251 | + |
| 252 | + private static String unescapePath(String path) { |
| 253 | + // If there are no tildes then there's definitely nothing to do |
| 254 | + if (path.indexOf('~') < 0) { |
| 255 | + return path; |
| 256 | + } |
| 257 | + StringBuilder ret = new StringBuilder(100); // arbitrary initial capacity |
| 258 | + for (int i = 0; i < path.length(); i++) { |
| 259 | + char ch = path.charAt(i); |
| 260 | + if (ch != '~') |
| 261 | + { |
| 262 | + ret.append(ch); |
| 263 | + continue; |
| 264 | + } |
| 265 | + i++; |
| 266 | + if (i >= path.length()) |
| 267 | + { |
| 268 | + return null; |
| 269 | + } |
| 270 | + switch (path.charAt(i)) { |
| 271 | + case '0': |
| 272 | + ret.append('~'); |
| 273 | + break; |
| 274 | + case '1': |
| 275 | + ret.append('/'); |
| 276 | + break; |
| 277 | + default: |
| 278 | + return null; |
| 279 | + } |
| 280 | + } |
| 281 | + return ret.toString(); |
| 282 | + } |
| 283 | + |
| 284 | + private static Map<String, AttributeRef> makeLiteralsMap(String... names) { |
| 285 | + Map<String, AttributeRef> ret = new HashMap<>(); |
| 286 | + for (String name: names) { |
| 287 | + ret.put(name, new AttributeRef(name, name, null)); |
| 288 | + } |
| 289 | + return ret; |
| 290 | + } |
| 291 | +} |
0 commit comments