Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 64 additions & 1 deletion core/src/main/java/org/apache/struts2/util/ConfigParseUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@
*/
package org.apache.struts2.util;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.apache.struts2.config.ConfigurationException;
import org.apache.struts2.ognl.OgnlUtil;

import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
Expand All @@ -33,6 +36,13 @@
import static org.apache.commons.lang3.StringUtils.strip;

public class ConfigParseUtil {
// Size the cache to prevent excessive memory usage in environments with many classloaders and/or large numbers of classes being validated.
// While still providing a reasonable caching benefit for common cases (e.g. multiple Struts instances in the same container, or multiple calls to validate the same class across different containers).
private static final int MAX_CLASS_CACHE_SIZE = 50;

private static final Cache<ClassLookupKey, Class<?>> VALIDATED_CLASS_CACHE = Caffeine.newBuilder()
.maximumSize(MAX_CLASS_CACHE_SIZE)
.build();

private ConfigParseUtil() {
}
Expand Down Expand Up @@ -73,14 +83,67 @@ public static Set<Class<?>> validateClasses(Set<String> classNames, ClassLoader
Set<Class<?>> classes = new HashSet<>();
for (String className : classNames) {
try {
classes.add(validatingClassLoader.loadClass(className));
classes.add(loadAndCacheClass(validatingClassLoader, className));
} catch (ClassNotFoundException e) {
throw new ConfigurationException("Cannot load class for exclusion/exemption configuration: " + className, e);
}
}
return classes;
}

private static Class<?> loadAndCacheClass(ClassLoader validatingClassLoader, String className) throws ClassNotFoundException {
ClassLookupKey lookupKey = new ClassLookupKey(classLoaderName(validatingClassLoader), className);

try {
return VALIDATED_CLASS_CACHE.get(lookupKey, key -> {
try {
return validatingClassLoader.loadClass(key.className);
} catch (ClassNotFoundException e) {
throw new ClassLookupException(e);
}
});
} catch (ClassLookupException e) {
throw (ClassNotFoundException) e.getCause();
}
}

private static String classLoaderName(ClassLoader classLoader) {
return String.valueOf(classLoader);
}

private static final class ClassLookupKey {
private final String classLoaderName;
private final String className;

private ClassLookupKey(String classLoaderName, String className) {
this.classLoaderName = classLoaderName;
this.className = className;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ClassLookupKey that = (ClassLookupKey) o;
return Objects.equals(classLoaderName, that.classLoaderName) && Objects.equals(className, that.className);
}

@Override
public int hashCode() {
return Objects.hash(classLoaderName, className);
}
}

private static final class ClassLookupException extends RuntimeException {
private ClassLookupException(ClassNotFoundException cause) {
super(cause);
}
}

public static Set<String> toPackageNamesSet(String newDelimitedPackageNames) throws ConfigurationException {
Set<String> packageNames = commaDelimitedStringToSet(newDelimitedPackageNames)
.stream().map(s -> strip(s, ".")).collect(toSet());
Expand Down
161 changes: 161 additions & 0 deletions core/src/test/java/org/apache/struts2/util/ConfigParseUtilTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.util;

import com.github.benmanes.caffeine.cache.Cache;
import junit.framework.TestCase;
import org.apache.struts2.config.ConfigurationException;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Set;

public class ConfigParseUtilTest extends TestCase {

@Override
protected void setUp() throws Exception {
super.setUp();
validatedClassCache().invalidateAll();
}

@Override
protected void tearDown() throws Exception {
validatedClassCache().invalidateAll();
super.tearDown();
}

public void testValidateClassesCachesByClassLoaderAndClassName() {
CountingClassLoader loader = new CountingClassLoader(getClass().getClassLoader(), "loader-one");
Set<String> classNames = Collections.singleton(String.class.getName());

ConfigParseUtil.validateClasses(classNames, loader);
ConfigParseUtil.validateClasses(classNames, loader);

assertEquals(1, loader.getStringClassLoads());
}

public void testValidateClassesCachesAcrossMultipleRepeatedCallsWithSameClassLoader() {
CountingClassLoader loader = new CountingClassLoader(getClass().getClassLoader(), "loader-one");
Set<String> classNames = Collections.singleton(String.class.getName());

for (int i = 0; i < 10; i++) {
ConfigParseUtil.validateClasses(classNames, loader);
}

assertEquals(1, loader.getStringClassLoads());
}

public void testValidateClassesSeparatesEntriesAcrossDifferentClassLoaders() {
CountingClassLoader firstLoader = new CountingClassLoader(getClass().getClassLoader(), "loader-one");
CountingClassLoader secondLoader = new CountingClassLoader(getClass().getClassLoader(), "loader-two");
Set<String> classNames = Collections.singleton(String.class.getName());

ConfigParseUtil.validateClasses(classNames, firstLoader);
ConfigParseUtil.validateClasses(classNames, secondLoader);

assertEquals(1, firstLoader.getStringClassLoads());
assertEquals(1, secondLoader.getStringClassLoads());
}

public void testValidateClassesCacheIsLimitedTo50Entries() {
Set<String> classNames = Collections.singleton(String.class.getName());

for (int i = 0; i < 60; i++) {
CountingClassLoader loader = new CountingClassLoader(getClass().getClassLoader(), "loader-" + i);
ConfigParseUtil.validateClasses(classNames, loader);
}

Cache<Object, Object> cache = validatedClassCache();
cache.cleanUp();

assertTrue(cache.estimatedSize() <= 50);
}

public void testValidateClassesThrowsForNonExistingClassNameOnEachCall() {
String missingClassName = "org.apache.struts2.util.NonExistingClassForValidationTest";
Set<String> classNames = Collections.singleton(missingClassName);
int[] missingClassLoads = new int[1];
ClassLoader loader = new ClassLoader(getClass().getClassLoader()) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (missingClassName.equals(name)) {
missingClassLoads[0]++;
throw new ClassNotFoundException(name);
}
return super.loadClass(name);
}

@Override
public String toString() {
return "missing-class-loader";
}
};

for (int i = 0; i < 2; i++) {
try {
ConfigParseUtil.validateClasses(classNames, loader);
fail("Expected ConfigurationException for class: " + missingClassName);
} catch (ConfigurationException e) {
assertTrue(e.getMessage().contains(missingClassName));
assertNotNull(e.getCause());
assertEquals(ClassNotFoundException.class, e.getCause().getClass());
}
}

assertEquals(2, missingClassLoads[0]);
}

@SuppressWarnings("unchecked")
private static Cache<Object, Object> validatedClassCache() {
try {
Field cacheField = ConfigParseUtil.class.getDeclaredField("VALIDATED_CLASS_CACHE");
cacheField.setAccessible(true);
return (Cache<Object, Object>) cacheField.get(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new AssertionError("Cannot access ConfigParseUtil cache field", e);
}
}

private static final class CountingClassLoader extends ClassLoader {
private final String loaderName;
private int stringClassLoads;

private CountingClassLoader(ClassLoader parent, String loaderName) {
super(parent);
this.loaderName = loaderName;
}

@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (String.class.getName().equals(name)) {
stringClassLoads++;
}
return super.loadClass(name);
}

private int getStringClassLoads() {
return stringClassLoads;
}

@Override
public String toString() {
return loaderName;
}
}
}