View Javadoc
1   /*
2    *  Copyright 2012 Chris Pheby
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    *      http://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.jadira.scanner.file.locator;
17  
18  import java.io.File;
19  import java.net.MalformedURLException;
20  import java.net.URL;
21  import java.util.ArrayList;
22  import java.util.List;
23  import java.util.Set;
24  
25  import javax.servlet.ServletContext;
26  
27  import org.jadira.scanner.core.api.Locator;
28  import org.jadira.scanner.core.exception.ClasspathAccessException;
29  
30  /**
31   * Utilities for resolving urls against the classpath of a Web Archive
32   */
33  public class WebappClasspathUrlLocator implements Locator<URL> {
34  
35  	private final ServletContext servletContext;
36  
37  	public WebappClasspathUrlLocator(ServletContext servletContext) {
38  		this.servletContext = servletContext;
39  	}
40  	
41  	@Override
42  	public List<URL> locate() {
43  
44          List<URL> list = new ArrayList<URL>();
45          @SuppressWarnings("unchecked") Set<String> libJars = servletContext.getResourcePaths("/WEB-INF/lib");
46          for (String jar : libJars) {
47              try {
48                  list.add(servletContext.getResource(jar));
49              } catch (MalformedURLException e) {
50                  throw new ClasspathAccessException(e);
51              }
52          }
53          list.add(findWebInfClassesPath(servletContext));
54          return list;
55      }
56  
57      /**
58       * Find the URL pointing to "/WEB-INF/classes" This method may not work in conjunction with
59       * IteratorFactory if your servlet container does not extract the /WEB-INF/classes into a real
60       * file-based directory
61       * @param servletContext
62       * @return null if cannot determin /WEB-INF/classes
63       */
64      private static URL findWebInfClassesPath(ServletContext servletContext) {
65          String path = servletContext.getRealPath("/WEB-INF/classes");
66          if (path == null) {
67              return null;
68          }
69          File fp = new File(path);
70          if (!fp.exists()) {
71              return null;
72          }
73          try {
74              return fp.toURI().toURL();
75          } catch (MalformedURLException e) {
76              throw new ClasspathAccessException(e);
77          }
78      }
79  }