1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.amber.oauth2.rsfilter;
23
24 import javax.servlet.ServletContext;
25 import javax.servlet.ServletException;
26
27
28
29
30
31
32 public class OAuthUtils {
33
34 public static <T> T initiateServletContext(ServletContext context, String key, Class<T> expectedClass)
35 throws ServletException {
36
37 T provider = (T)context.getAttribute(key);
38
39 if (provider != null) {
40 return provider;
41 }
42
43 provider = (T)loadObject(context, key, expectedClass);
44
45
46 context.setAttribute(key, provider);
47
48 return provider;
49 }
50
51 public static Object loadObject(ServletContext context, String classParamName, Class expectedClass)
52 throws ServletException {
53
54 Object ob = null;
55
56 String providerClassName = context.getInitParameter(classParamName);
57 if (isEmpty(providerClassName)) {
58 throw new ServletException(classParamName + " context param required");
59 }
60 try {
61 Class<?> clazz = Class.forName(providerClassName);
62 if (!expectedClass.isAssignableFrom(clazz)) {
63 throw new ServletException(classParamName + " class: " + providerClassName
64 + " must be an instance of: " + expectedClass.getName());
65 }
66 ob = createObjectFromClassName(clazz);
67 } catch (ClassNotFoundException e) {
68 throw new ServletException(classParamName + " class " + providerClassName + " not found");
69 } catch (Exception e) {
70 throw new ServletException("Cannot instantiate: " + providerClassName);
71 }
72 return ob;
73 }
74
75 public static Object createObjectFromClassName(Class clazz)
76 throws IllegalAccessException, InstantiationException {
77 return clazz.newInstance();
78 }
79
80 public static boolean isEmpty(String value) {
81 return value == null || "".equals(value);
82 }
83 }