01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing,
13: * software distributed under the License is distributed on an
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: */package org.apache.cxf.transport.servlet;
19:
20: import java.io.IOException;
21: import java.io.InputStream;
22: import java.net.MalformedURLException;
23: import java.net.URL;
24: import java.util.Map;
25: import java.util.concurrent.ConcurrentHashMap;
26:
27: import javax.naming.InitialContext;
28: import javax.naming.NamingException;
29: import javax.servlet.ServletContext;
30:
31: import org.apache.cxf.resource.ResourceResolver;
32:
33: public class ServletContextResourceResolver implements ResourceResolver {
34: ServletContext servletContext;
35: Map<String, URL> urlMap = new ConcurrentHashMap<String, URL>();
36:
37: public ServletContextResourceResolver(ServletContext sc) {
38: servletContext = sc;
39: }
40:
41: public final InputStream getAsStream(final String string) {
42: if (urlMap.containsKey(string)) {
43: try {
44: return urlMap.get(string).openStream();
45: } catch (IOException e) {
46: //ignore
47: }
48: }
49: return servletContext.getResourceAsStream(string);
50: }
51:
52: public final <T> T resolve(final String entryName,
53: final Class<T> clz) {
54:
55: Object obj = null;
56: try {
57: InitialContext ic = new InitialContext();
58: obj = ic.lookup(entryName);
59: } catch (NamingException e) {
60: //do nothing
61: }
62:
63: if (obj != null && clz.isInstance(obj)) {
64: return clz.cast(obj);
65: }
66:
67: if (clz.isAssignableFrom(URL.class)) {
68: if (urlMap.containsKey(entryName)) {
69: return clz.cast(urlMap.get(entryName));
70: }
71: try {
72: URL url = servletContext.getResource(entryName);
73: if (url != null) {
74: urlMap.put(url.toString(), url);
75: return clz.cast(url);
76: }
77: } catch (MalformedURLException e) {
78: //fallthrough
79: }
80: try {
81: URL url = servletContext.getResource("/" + entryName);
82: if (url != null) {
83: urlMap.put(url.toString(), url);
84: return clz.cast(url);
85: }
86: } catch (MalformedURLException e1) {
87: //ignore
88: }
89: } else if (clz.isAssignableFrom(InputStream.class)) {
90: return clz.cast(getAsStream(entryName));
91: }
92: return null;
93: }
94: }
|