View Javadoc
1   /*
2    *    Copyright 2010-2026 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.apache.ibatis.migration.io;
17  
18  import java.io.IOException;
19  import java.lang.reflect.InvocationTargetException;
20  import java.lang.reflect.Method;
21  import java.net.URL;
22  import java.util.ArrayList;
23  import java.util.Arrays;
24  import java.util.Collections;
25  import java.util.List;
26  import java.util.logging.Level;
27  import java.util.logging.Logger;
28  
29  /**
30   * Provides a very simple API for accessing resources within an application server.
31   */
32  public abstract class VFS {
33    private static final Logger log = Logger.getLogger(VFS.class.getName());
34  
35    /** The built-in implementations. */
36    protected static final Class<?>[] IMPLEMENTATIONS = { JBoss6VFS.class, DefaultVFS.class };
37  
38    /**
39     * The list to which implementations are added by {@link #addImplClass(Class)}.
40     */
41    protected static final List<Class<? extends VFS>> USER_IMPLEMENTATIONS = new ArrayList<>();
42  
43    /** Singleton instance holder. */
44    private static class VFSHolder {
45      static final VFS INSTANCE = createVFS();
46  
47      @SuppressWarnings("unchecked")
48      static VFS createVFS() {
49        // Try the user implementations first, then the built-ins
50        List<Class<? extends VFS>> impls = new ArrayList<>(USER_IMPLEMENTATIONS);
51        impls.addAll(Arrays.asList((Class<? extends VFS>[]) IMPLEMENTATIONS));
52  
53        // Try each implementation class until a valid one is found
54        VFS vfs = null;
55        for (int i = 0; vfs == null || !vfs.isValid(); i++) {
56          Class<? extends VFS> impl = impls.get(i);
57          try {
58            vfs = impl.getDeclaredConstructor().newInstance();
59            if (!vfs.isValid() && log.isLoggable(Level.FINER)) {
60              log.log(Level.FINER, "VFS implementation " + impl.getName() + " is not valid in this environment.");
61            }
62          } catch (InstantiationException | IllegalAccessException | NoSuchMethodException
63              | InvocationTargetException e) {
64            log.log(Level.SEVERE, "Failed to instantiate " + impl, e);
65            return null;
66          }
67        }
68  
69        if (log.isLoggable(Level.FINER)) {
70          log.log(Level.FINER, "Using VFS adapter " + vfs.getClass().getName());
71        }
72  
73        return vfs;
74      }
75    }
76  
77    /**
78     * Get the singleton {@link VFS} instance. If no {@link VFS} implementation can be found for the current environment,
79     * then this method returns null.
80     *
81     * @return single instance of VFS
82     */
83    public static VFS getInstance() {
84      return VFSHolder.INSTANCE;
85    }
86  
87    /**
88     * Adds the specified class to the list of {@link VFS} implementations. Classes added in this manner are tried in the
89     * order they are added and before any of the built-in implementations.
90     *
91     * @param clazz
92     *          The {@link VFS} implementation class to add.
93     */
94    public static void addImplClass(Class<? extends VFS> clazz) {
95      if (clazz != null) {
96        USER_IMPLEMENTATIONS.add(clazz);
97      }
98    }
99  
100   /**
101    * Get a class by name. If the class is not found then return null.
102    *
103    * @param className
104    *          the class name
105    *
106    * @return the class
107    */
108   protected static Class<?> getClass(String className) {
109     try {
110       return Thread.currentThread().getContextClassLoader().loadClass(className);
111       // return ReflectUtil.findClass(className);
112     } catch (ClassNotFoundException e) {
113       if (log.isLoggable(Level.FINER)) {
114         log.log(Level.FINER, "Class not found: " + className);
115       }
116       return null;
117     }
118   }
119 
120   /**
121    * Get a method by name and parameter types. If the method is not found then return null.
122    *
123    * @param clazz
124    *          The class to which the method belongs.
125    * @param methodName
126    *          The name of the method.
127    * @param parameterTypes
128    *          The types of the parameters accepted by the method.
129    *
130    * @return the method
131    */
132   protected static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
133     if (clazz == null) {
134       return null;
135     }
136     try {
137       return clazz.getMethod(methodName, parameterTypes);
138     } catch (SecurityException e) {
139       log.log(Level.SEVERE,
140           "Security exception looking for method " + clazz.getName() + "." + methodName + ".  Cause: " + e);
141       return null;
142     } catch (NoSuchMethodException e) {
143       log.log(Level.SEVERE,
144           "Method not found " + clazz.getName() + "." + methodName + "." + methodName + ".  Cause: " + e);
145       return null;
146     }
147   }
148 
149   /**
150    * Invoke a method on an object and return whatever it returns.
151    *
152    * @param <T>
153    *          the generic type
154    * @param method
155    *          The method to invoke.
156    * @param object
157    *          The instance or class (for static methods) on which to invoke the method.
158    * @param parameters
159    *          The parameters to pass to the method.
160    *
161    * @return Whatever the method returns.
162    *
163    * @throws IOException
164    *           If I/O errors occur
165    * @throws RuntimeException
166    *           If anything else goes wrong
167    */
168   @SuppressWarnings("unchecked")
169   protected static <T> T invoke(Method method, Object object, Object... parameters)
170       throws IOException, RuntimeException {
171     try {
172       return (T) method.invoke(object, parameters);
173     } catch (IllegalArgumentException | IllegalAccessException e) {
174       throw new RuntimeException(e);
175     } catch (InvocationTargetException e) {
176       if (e.getTargetException() instanceof IOException) {
177         throw (IOException) e.getTargetException();
178       }
179       throw new RuntimeException(e);
180     }
181   }
182 
183   /**
184    * Get a list of {@link URL}s from the context classloader for all the resources found at the specified path.
185    *
186    * @param path
187    *          The resource path.
188    *
189    * @return A list of {@link URL}s, as returned by {@link ClassLoader#getResources(String)}.
190    *
191    * @throws IOException
192    *           If I/O errors occur
193    */
194   protected static List<URL> getResources(String path) throws IOException {
195     return Collections.list(Thread.currentThread().getContextClassLoader().getResources(path));
196   }
197 
198   /**
199    * Return true if the {@link VFS} implementation is valid for the current environment.
200    *
201    * @return true, if is valid
202    */
203   public abstract boolean isValid();
204 
205   /**
206    * Recursively list the full resource path of all the resources that are children of the resource identified by a URL.
207    *
208    * @param url
209    *          The URL that identifies the resource to list.
210    * @param forPath
211    *          The path to the resource that is identified by the URL. Generally, this is the value passed to
212    *          {@link #getResources(String)} to get the resource URL.
213    *
214    * @return A list containing the names of the child resources.
215    *
216    * @throws IOException
217    *           If I/O errors occur
218    */
219   protected abstract List<String> list(URL url, String forPath) throws IOException;
220 
221   /**
222    * Recursively list the full resource path of all the resources that are children of all the resources found at the
223    * specified path.
224    *
225    * @param path
226    *          The path of the resource(s) to list.
227    *
228    * @return A list containing the names of the child resources.
229    *
230    * @throws IOException
231    *           If I/O errors occur
232    */
233   public List<String> list(String path) throws IOException {
234     List<String> names = new ArrayList<>();
235     for (URL url : getResources(path)) {
236       names.addAll(list(url, path));
237     }
238     return names;
239   }
240 }