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 java.util.regex.*; 020 021import org.apache.juneau.commons.collections.*; 022import org.apache.juneau.commons.svl.*; 023 024/** 025 * Regex functions for the {@code #{...}} script catalog. 026 * 027 * <p> 028 * Replacements for {@code PatternMatchVar} ({@code $PM}), {@code PatternExtractVar} 029 * ({@code $PE}), and {@code PatternReplaceVar} ({@code $PR}) per the migration inventory. 030 * 031 * <p> 032 * Note that {@link StringFunctions.Replace} is the literal-string replace; {@link ReplaceRegex} 033 * is the regex form. 034 */ 035public final class RegexFunctions { 036 037 private RegexFunctions() {} 038 039 // User-supplied regexes are compiled once and reused. Bounded (entire cache cleared past maxSize) to guard 040 // against unbounded growth from arbitrary user input. Pattern is immutable/thread-safe; a fresh Matcher is 041 // created per invocation, so behavior is identical to compiling on every call. 042 static final Cache<String,Pattern> PATTERN_CACHE = Cache.of(String.class, Pattern.class).maxSize(1000).supplier(Pattern::compile).build(); 043 044 /** Maximum time, in milliseconds, a single regex evaluation may run before it is aborted. */ 045 static final long REGEX_TIMEOUT_MS = 2000; 046 047 /** Input wrapper that aborts a runaway match once its deadline passes. */ 048 private static final class Deadline implements CharSequence { 049 private final CharSequence s; 050 private final long end = System.nanoTime() + REGEX_TIMEOUT_MS * 1_000_000L; 051 052 Deadline(CharSequence s) { 053 this.s = s; 054 } 055 056 @Override public char charAt(int i) { 057 if ((i & 0xFF) == 0 && System.nanoTime() > end) 058 throw new IllegalStateException("Regular expression evaluation timed out."); 059 return s.charAt(i); 060 } 061 @Override public int length() { return s.length(); } 062 @Override public CharSequence subSequence(int a, int b) { return new Deadline(s.subSequence(a, b)); } 063 @Override public String toString() { return s.toString(); } 064 } 065 066 private static Matcher matcher(String regex, String s) { 067 return PATTERN_CACHE.get(regex).matcher(new Deadline(s)); 068 } 069 070 /** All function classes in this category. */ 071 @SuppressWarnings({ 072 "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. 073 "unchecked" // Cast is safe: type verified by caller context. 074 }) 075 public static final Class<? extends VarFunction>[] ALL = new Class[] { 076 Match.class, Extract.class, ReplaceRegex.class 077 }; 078 079 /** {@code #{match(s, regex)}} — replacement for the legacy {@code PM} variable. Returns {@code "true"} or {@code "false"}. */ 080 public static class Match extends TypedFunction { 081 @Override public String name() { return "match"; } 082 public String invoke(String s, String regex) { 083 if (s == null || regex == null) return "false"; 084 return String.valueOf(matcher(regex, s).find()); 085 } 086 } 087 088 /** 089 * {@code #{extract(s, regex)}} / {@code #{extract(s, regex, group)}} — replacement for the 090 * legacy {@code PE} variable. Returns the first match; if {@code group} is supplied, returns 091 * that capture group from the first match. 092 */ 093 public static class Extract extends TypedFunction { 094 @Override public String name() { return "extract"; } 095 public String invoke(String s, String regex) { return invoke(s, regex, 0); } 096 public String invoke(String s, String regex, int group) { 097 if (s == null || regex == null) return ""; 098 var m = matcher(regex, s); 099 if (!m.find()) return ""; 100 if (group < 0 || group > m.groupCount()) return ""; 101 var v = m.group(group); 102 return v == null ? "" : v; 103 } 104 } 105 106 /** {@code #{replaceRegex(s, regex, replacement)}} — replacement for the legacy {@code PR} variable. */ 107 public static class ReplaceRegex extends TypedFunction { 108 @Override public String name() { return "replaceRegex"; } 109 public String invoke(String s, String regex, String replacement) { 110 if (s == null) return ""; 111 if (regex == null) return s; 112 return matcher(regex, s).replaceAll(replacement == null ? "" : replacement); 113 } 114 } 115}