001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.commons.svl.functions; 018 019import static org.apache.juneau.commons.utils.Shorts.*; 020import static org.apache.juneau.commons.utils.StringUtils.*; 021 022import java.util.*; 023 024import org.apache.juneau.commons.svl.*; 025 026/** 027 * String-manipulation functions for the {@code #{...}} script catalog. 028 * 029 * <p> 030 * Each public static nested class is a {@link TypedFunction} registered under the function name 031 * shown in its {@link VarFunction#name()} method. The {@code Replaces} annotation in each 032 * nested-class Javadoc names the legacy {@code Var} class that was retired in 10.0.0 in favor of 033 * the function form. 034 */ 035public final class StringFunctions { 036 037 /** Maximum length of a string produced by {@code repeat} or {@code randString}. */ 038 static final int MAX_RESULT_LENGTH = 1 << 20; 039 040 private StringFunctions() {} 041 042 /** All function classes in this category, in registration order. */ 043 @SuppressWarnings({ 044 "java:S2386", // ALL is an immutable compile-time registry; exposed as an array for the cross-package/varargs functions(...) API, so visibility cannot be reduced. 045 "unchecked" // Array initializer with parameterized element type; class literals are always erased at runtime. 046 }) 047 public static final Class<? extends VarFunction>[] ALL = new Class[] { 048 Substring.class, Upper.class, Lower.class, Trim.class, StripLeading.class, 049 StripTrailing.class, StripSlashes.class, PathToken.class, Len.class, Replace.class, 050 Contains.class, StartsWith.class, EndsWith.class, Concat.class, Repeat.class, 051 Reverse.class, Format.class, Split.class, Join.class 052 }; 053 054 /** 055 * {@code #{substring(s, start)}} / {@code #{substring(s, start, end)}} — replacement for the 056 * legacy {@code ST} {@code SubstringVar}. 057 * 058 * <p> 059 * Both endpoints are clamped to {@code [0, len(s)]} so out-of-range arguments don't throw — 060 * matches the legacy {@code SubstringVar} behavior. 061 */ 062 public static class Substring extends TypedFunction { 063 @Override public String name() { return "substring"; } 064 public String invoke(String s, int start) { 065 if (s == null) return ""; 066 var len = s.length(); 067 var a = Math.max(0, Math.min(start, len)); 068 return s.substring(a); 069 } 070 public String invoke(String s, int start, int end) { 071 if (s == null) return ""; 072 var len = s.length(); 073 var a = Math.max(0, Math.min(start, len)); 074 var b = Math.max(a, Math.min(end, len)); 075 return s.substring(a, b); 076 } 077 } 078 079 /** {@code #{upper(s)}} — replacement for the legacy {@code UC} variable. */ 080 public static class Upper extends TypedFunction { 081 @Override public String name() { return "upper"; } 082 public String invoke(String s) { return s == null ? "" : s.toUpperCase(); } 083 } 084 085 /** {@code #{lower(s)}} — replacement for the legacy {@code LC} variable. */ 086 public static class Lower extends TypedFunction { 087 @Override public String name() { return "lower"; } 088 public String invoke(String s) { return s == null ? "" : s.toLowerCase(); } 089 } 090 091 /** {@code #{trim(s)}} — strips leading and trailing whitespace. */ 092 public static class Trim extends TypedFunction { 093 @Override public String name() { return "trim"; } 094 public String invoke(String s) { return s == null ? "" : s.trim(); } 095 } 096 097 /** {@code #{stripLeading(s)}} — strips leading whitespace. */ 098 public static class StripLeading extends TypedFunction { 099 @Override public String name() { return "stripLeading"; } 100 public String invoke(String s) { return s == null ? "" : s.stripLeading(); } 101 } 102 103 /** {@code #{stripTrailing(s)}} — strips trailing whitespace. */ 104 public static class StripTrailing extends TypedFunction { 105 @Override public String name() { return "stripTrailing"; } 106 public String invoke(String s) { return s == null ? "" : s.stripTrailing(); } 107 } 108 109 /** {@code #{stripSlashes(s)}} — strips leading and trailing {@code /} characters. */ 110 public static class StripSlashes extends TypedFunction { 111 @Override public String name() { return "stripSlashes"; } 112 public String invoke(String s) { 113 if (s == null) return ""; 114 var start = 0; 115 var end = s.length(); 116 while (start < end && s.charAt(start) == '/') start++; 117 while (end > start && s.charAt(end - 1) == '/') end--; 118 return s.substring(start, end); 119 } 120 } 121 122 /** 123 * {@code #{pathToken(s)}} — normalize a user-supplied path token for safe interpolation 124 * into a {@code path=} template. 125 * 126 * <p> 127 * Strips leading and trailing {@code /}, plus a trailing {@code /*} (or {@code *} that 128 * sits immediately after a {@code /}). Multi-segment paths are preserved. 129 * 130 * <h2 class='section'>Edge cases:</h2> 131 * <ul> 132 * <li>{@code ""} → {@code ""} 133 * <li>{@code "/"} → {@code ""} 134 * <li>{@code "/*"} → {@code ""} 135 * <li>{@code "jsp"} → {@code "jsp"} 136 * <li>{@code "/jsp"} → {@code "jsp"} 137 * <li>{@code "/jsp/"} → {@code "jsp"} 138 * <li>{@code "/jsp/*"} → {@code "jsp"} 139 * <li>{@code "jsp/*"} → {@code "jsp"} 140 * <li>{@code "/api/v1/*"} → {@code "api/v1"} 141 * </ul> 142 * 143 * <p> 144 * Used in SVL-configurable mixin paths so users can supply 145 * {@code "jsp"}, {@code "/jsp"}, {@code "/jsp/"}, {@code "/jsp/*"}, or {@code "jsp/*"} and 146 * the template {@code /#{pathToken(${juneau.jsp.path:jsp})}/*} always resolves to a clean 147 * {@code /jsp/*}. 148 */ 149 public static class PathToken extends TypedFunction { 150 @Override public String name() { return "pathToken"; } 151 public String invoke(String s) { 152 if (isEmpty(s)) return ""; 153 var t = s; 154 // Strip a trailing /* or trailing * (when sitting right after a /). 155 if (t.endsWith("/*")) 156 t = t.substring(0, t.length() - 2); 157 else if (t.endsWith("*") && t.length() >= 2 && t.charAt(t.length() - 2) == '/') 158 t = t.substring(0, t.length() - 1); 159 // Strip leading and trailing slashes. 160 var start = 0; 161 var end = t.length(); 162 while (start < end && t.charAt(start) == '/') start++; 163 while (end > start && t.charAt(end - 1) == '/') end--; 164 return t.substring(start, end); 165 } 166 } 167 168 /** 169 * {@code #{len(s)}} / {@code #{len(s, delimiter)}} — replacement for the legacy 170 * {@code LN} variable. 171 * 172 * <p> 173 * Single-arg form returns the character count. Two-arg form splits on the literal 174 * {@code delimiter} (after trimming leading/trailing whitespace, matching the legacy 175 * {@code LenVar} behavior) and returns the part count. 176 */ 177 public static class Len extends TypedFunction { 178 @Override public String name() { return "len"; } 179 public String invoke(String s) { return s == null ? "0" : String.valueOf(s.length()); } 180 public String invoke(String s, String delimiter) { 181 if (s == null) return "0"; 182 if (ie(delimiter)) return String.valueOf(s.length()); 183 return String.valueOf(s.trim().split(java.util.regex.Pattern.quote(delimiter)).length); 184 } 185 } 186 187 /** 188 * {@code #{replace(s, target, replacement)}} — literal (non-regex) string replacement. 189 * 190 * <p> 191 * For regex replacement use {@code #{replaceRegex(s, regex, replacement)}}. 192 */ 193 public static class Replace extends TypedFunction { 194 @Override public String name() { return "replace"; } 195 public String invoke(String s, String target, String replacement) { 196 if (s == null) return ""; 197 return s.replace(target, replacement == null ? "" : replacement); 198 } 199 } 200 201 /** {@code #{contains(s, substr)}} — returns {@code "true"} or {@code "false"}. */ 202 public static class Contains extends TypedFunction { 203 @Override public String name() { return "contains"; } 204 public String invoke(String s, String substr) { 205 return String.valueOf(s != null && substr != null && s.contains(substr)); 206 } 207 } 208 209 /** {@code #{startsWith(s, prefix)}} — returns {@code "true"} or {@code "false"}. */ 210 public static class StartsWith extends TypedFunction { 211 @Override public String name() { return "startsWith"; } 212 public String invoke(String s, String prefix) { 213 return String.valueOf(s != null && prefix != null && s.startsWith(prefix)); 214 } 215 } 216 217 /** {@code #{endsWith(s, suffix)}} — returns {@code "true"} or {@code "false"}. */ 218 public static class EndsWith extends TypedFunction { 219 @Override public String name() { return "endsWith"; } 220 public String invoke(String s, String suffix) { 221 return String.valueOf(s != null && suffix != null && s.endsWith(suffix)); 222 } 223 } 224 225 /** {@code #{concat(s1, s2, ...)}} — variadic string concatenation. */ 226 public static class Concat extends TypedFunction { 227 @Override public String name() { return "concat"; } 228 public String invoke(String[] parts) { 229 var sb = new StringBuilder(); 230 for (var p : parts) 231 if (p != null) sb.append(p); 232 return sb.toString(); 233 } 234 } 235 236 /** {@code #{repeat(s, n)}} — repeats {@code s} {@code n} times. */ 237 public static class Repeat extends TypedFunction { 238 @Override public String name() { return "repeat"; } 239 public String invoke(String s, int n) { 240 if (s == null || n <= 0) return ""; 241 if ((long)s.length() * n > MAX_RESULT_LENGTH) throw iaex("repeat: result would exceed %s characters", MAX_RESULT_LENGTH); 242 return s.repeat(n); 243 } 244 } 245 246 /** {@code #{reverse(s)}} — reverses the characters of {@code s}. */ 247 public static class Reverse extends TypedFunction { 248 @Override public String name() { return "reverse"; } 249 public String invoke(String s) { 250 return s == null ? "" : new StringBuilder(s).reverse().toString(); 251 } 252 } 253 254 /** 255 * {@code #{format(pattern, args...)}} — {@link String#format Java formatter-style 256 * formatting}. Pattern uses Java {@link Formatter} syntax (e.g. {@code %s}, 257 * {@code %d}, {@code %.2f}). Variadic args; coerced per Java {@code Formatter} rules at 258 * invocation. 259 * 260 * <h2 class='section'>Example:</h2> 261 * <p> 262 * {@code #{format("%s-%03d", ${prefix}, ${counter})}} 263 * 264 * <p> 265 * All args are passed as raw {@link String} values; format specifiers like {@code %d} will 266 * convert numeric strings via {@link Integer#parseInt} / {@link Long#parseLong} as needed. 267 * {@code %s} accepts any string verbatim. 268 */ 269 public static class Format extends TypedFunction { 270 @Override public String name() { return "format"; } 271 public String invoke(String pattern, String[] args) { 272 if (pattern == null) return ""; 273 var coerced = new Object[args.length]; 274 for (var i = 0; i < args.length; i++) 275 coerced[i] = coerceArgForFormat(args[i]); 276 return String.format(pattern, coerced); 277 } 278 279 /** 280 * Best-effort numeric coercion for {@code %d}/{@code %f}-style specifiers — strings 281 * that parse as long/double are passed as the typed value, otherwise as the raw 282 * string. This keeps {@code %s} as the safe default while letting numeric specifiers 283 * work without a separate {@code numericFormat(...)} entry point. 284 */ 285 @SuppressWarnings({ 286 "java:S1166" // Exception swallowed — coercion is best-effort. 287 }) 288 private static Object coerceArgForFormat(String s) { 289 if (s == null) return ""; 290 var t = s.trim(); 291 try { return Long.parseLong(t); } catch (@SuppressWarnings("unused") NumberFormatException e) { /* fall through */ } 292 try { return Double.parseDouble(t); } catch (@SuppressWarnings("unused") NumberFormatException e) { /* fall through */ } 293 return s; 294 } 295 } 296 297 /** 298 * {@code #{split(s, separator)}} — splits {@code s} on the literal {@code separator} 299 * substring. Returns a JSON-array-shortcut string (e.g. {@code ["a","b","c"]}) so the 300 * result composes with other functions that accept {@code String[]}. Trailing empty fields 301 * dropped. 302 */ 303 public static class Split extends TypedFunction { 304 @Override public String name() { return "split"; } 305 public String invoke(String s, String separator) { 306 if (isEmpty(s)) return "[]"; 307 var parts = new ArrayList<String>(); 308 if (isEmpty(separator)) { 309 parts.add(s); 310 } else { 311 var i = 0; 312 while (true) { 313 var hit = s.indexOf(separator, i); 314 if (hit < 0) { parts.add(s.substring(i)); break; } 315 parts.add(s.substring(i, hit)); 316 i = hit + separator.length(); 317 } 318 } 319 // Drop trailing empties. 320 while (!parts.isEmpty() && parts.get(parts.size() - 1).isEmpty()) 321 parts.remove(parts.size() - 1); 322 return JsonShortcut.encodeArray(parts); 323 } 324 } 325 326 /** 327 * {@code #{join(separator, parts...)}} — concatenates {@code parts} with {@code separator} 328 * between each pair. 329 * 330 * <h2 class='section'>Example:</h2> 331 * <p> 332 * {@code #{join("/", ${tenant}, ${id})}} → {@code acme/42} 333 * 334 * <p> 335 * A single {@link Collection} argument supplies the parts. Each part is rendered with {@code toString()} (doubles 336 * without a trailing {@code .0}), so a nested {@link Map} or {@link List} part prints as its Java {@code toString()}, 337 * not as JSON like the value formatter does; this inconsistency is known and intentional for now. 338 */ 339 public static class Join implements VarFunction { 340 @Override public String name() { return "join"; } 341 @Override public int minArity() { return 1; } 342 @Override public int maxArity() { return Integer.MAX_VALUE; } 343 @Override public String invoke(VarResolverSession session, List<Object> args) { 344 var sep = args.get(0) == null ? "" : args.get(0).toString(); 345 // A single collection argument supplies the parts. 346 List<?> parts = args.size() == 2 && args.get(1) instanceof Collection<?> c ? CollectionFunctions.bounded(session, "join", c) : args.subList(1, args.size()); 347 var sb = new StringBuilder(); 348 for (var i = 0; i < parts.size(); i++) { 349 if (i > 0) sb.append(sep); 350 var p = parts.get(i); 351 if (p instanceof Double || p instanceof Float) 352 sb.append(ArithmeticFunctions.render(((Number)p).doubleValue())); 353 else 354 sb.append(p == null ? "" : p.toString()); 355 } 356 return sb.toString(); 357 } 358 } 359}