View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.xml.secure;
19  
20  import static org.junit.jupiter.api.Assertions.assertEquals;
21  import static org.junit.jupiter.api.Assertions.assertInstanceOf;
22  import static org.junit.jupiter.api.Assertions.assertNotNull;
23  import static org.junit.jupiter.api.Assertions.assertSame;
24  import static org.junit.jupiter.api.Assertions.assertThrows;
25  
26  import java.io.ByteArrayOutputStream;
27  import java.io.InputStream;
28  import java.lang.reflect.Field;
29  
30  import org.junit.jupiter.api.Test;
31  import org.junit.jupiter.api.condition.DisabledInNativeImage;
32  import org.w3c.dom.bootstrap.DOMImplementationRegistry;
33  
34  /**
35   * Tests resolver initialization using fresh JVM class definitions and the JDK DOM implementation.
36   *
37   * <p>
38   * Excluded from Android compilation because Android does not support this JVM class-loading mechanism.
39   * </p>
40   */
41  @DisabledInNativeImage
42  class FallbackIgnoreLSResourceResolverInitializationTest {
43  
44      private static void checkInitialization(final boolean failRetry) throws Exception {
45          final Thread thread = Thread.currentThread();
46          final ClassLoader original = thread.getContextClassLoader();
47          final String source = failRetry ? "missing.DOMImplementationSource" : "com.sun.org.apache.xerces.internal.dom.DOMXSImplementationSourceImpl";
48          final ClassNotFoundException firstFailure = new ClassNotFoundException("Rejected by test TCCL");
49          final ClassLoader restricted = new ClassLoader(original) {
50  
51              @Override
52              protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
53                  if (source.equals(name)) {
54                      throw firstFailure;
55                  }
56                  return super.loadClass(name, resolve);
57              }
58          };
59          final String previous = System.setProperty(DOMImplementationRegistry.PROPERTY, source);
60          thread.setContextClassLoader(restricted);
61          try {
62              if (failRetry) {
63                  final ExceptionInInitializerError error = assertThrows(ExceptionInInitializerError.class,
64                          FallbackIgnoreLSResourceResolverInitializationTest::initializeResolver);
65                  final Throwable retry = error.getCause();
66                  assertInstanceOf(ClassNotFoundException.class, retry);
67                  assertEquals(1, retry.getSuppressed().length);
68                  assertSame(firstFailure, retry.getSuppressed()[0]);
69              } else {
70                  final Field domLs = initializeResolver().getDeclaredField("DOM_LS");
71                  domLs.setAccessible(true);
72                  assertNotNull(domLs.get(null));
73              }
74              assertSame(restricted, thread.getContextClassLoader(), "Initialization must restore the caller's TCCL");
75          } finally {
76              thread.setContextClassLoader(original);
77              if (previous == null) {
78                  System.clearProperty(DOMImplementationRegistry.PROPERTY);
79              } else {
80                  System.setProperty(DOMImplementationRegistry.PROPERTY, previous);
81              }
82          }
83      }
84  
85      /**
86       * Defines only the resolver in a fresh loader, so each test executes its static initializer independently.
87       */
88      private static Class<?> initializeResolver() throws Exception {
89          final String name = FallbackIgnoreLSResourceResolver.class.getName();
90          final byte[] bytes;
91          try (InputStream input = FallbackIgnoreLSResourceResolver.class.getResourceAsStream("FallbackIgnoreLSResourceResolver.class");
92                  ByteArrayOutputStream output = new ByteArrayOutputStream()) {
93              assertNotNull(input);
94              final byte[] buffer = new byte[4096];
95              int count;
96              while ((count = input.read(buffer)) != -1) {
97                  output.write(buffer, 0, count);
98              }
99              bytes = output.toByteArray();
100         }
101         final ClassLoader isolated = new ClassLoader(FallbackIgnoreLSResourceResolver.class.getClassLoader()) {
102 
103             @Override
104             protected Class<?> loadClass(final String className, final boolean resolve) throws ClassNotFoundException {
105                 if (!name.equals(className)) {
106                     return super.loadClass(className, resolve);
107                 }
108                 synchronized (getClassLoadingLock(className)) {
109                     Class<?> result = findLoadedClass(className);
110                     if (result == null) {
111                         result = defineClass(className, bytes, 0, bytes.length);
112                     }
113                     if (resolve) {
114                         resolveClass(result);
115                     }
116                     return result;
117                 }
118             }
119         };
120         return Class.forName(name, true, isolated);
121     }
122 
123     @Test
124     void initializationRestoresContextLoaderAfterRetry() throws Exception {
125         checkInitialization(false);
126     }
127 
128     @Test
129     void initializationRetainsBothFailuresAndRestoresContextLoader() throws Exception {
130         checkInitialization(true);
131     }
132 }