e97a562620771ddf8d1a9bab0e873a89a58dc0b2
[controller.git] / opendaylight / northbound / commons / src / main / java / org / opendaylight / controller / northbound / commons / NorthboundApplication.java
1 /**
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.northbound.commons;
10
11 import java.util.Dictionary;
12 import java.util.HashSet;
13 import java.util.List;
14 import java.util.Set;
15
16 import javax.ws.rs.core.Application;
17 import javax.ws.rs.ext.ContextResolver;
18 import javax.xml.bind.JAXBContext;
19 import javax.xml.bind.JAXBException;
20 import javax.xml.bind.annotation.XmlRootElement;
21
22 import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
23 import org.codehaus.jackson.map.DeserializationConfig;
24 import org.opendaylight.controller.northbound.bundlescanner.IBundleScanService;
25 import org.osgi.framework.Bundle;
26 import org.osgi.framework.BundleContext;
27 import org.osgi.framework.BundleReference;
28 import org.osgi.framework.FrameworkUtil;
29 import org.osgi.framework.ServiceException;
30 import org.osgi.framework.ServiceReference;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * Instance of javax.ws.rs.core.Application used to return the classes
36  * that will be instantiated for JAXRS processing. This hooks onto the
37  * bundle scanner service to provide JAXB classes to JAX-RS for prorcessing.
38  */
39 @SuppressWarnings("unchecked")
40 public class NorthboundApplication extends Application {
41     public static final String JAXRS_RESOURCES_MANIFEST_NAME = "Jaxrs-Resources";
42     public static final String JAXRS_EXCLUDES_MANIFEST_NAME = "Jaxrs-Exclude-Types";
43     private static final Logger LOGGER = LoggerFactory.getLogger(NorthboundApplication.class);
44     private final Set<Object> _singletons;
45
46     public NorthboundApplication() {
47         _singletons = new HashSet<Object>();
48         _singletons.add(new ContextResolver<JAXBContext>() {
49             JAXBContext jaxbContext = newJAXBContext();
50             @Override
51             public JAXBContext getContext(Class<?> type) {
52                 return jaxbContext;
53             }
54
55         } );
56         _singletons.add(getJsonProvider());
57         _singletons.add(new JacksonJsonProcessingExceptionMapper());
58     }
59
60     ////////////////////////////////////////////////////////////////
61     //  Application overrides
62     ////////////////////////////////////////////////////////////////
63
64     @Override
65     public Set<Object> getSingletons() {
66         return _singletons;
67     }
68
69     @Override
70     public Set<Class<?>> getClasses() {
71         Set<Class<?>> result = new HashSet<Class<?>>();
72         result.addAll(findJAXRSResourceClasses());
73         return result;
74     }
75
76     private static final JacksonJaxbJsonProvider getJsonProvider() {
77         JacksonJaxbJsonProvider jsonProvider = new JacksonJaxbJsonProvider();
78         jsonProvider.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
79                 false);
80         return jsonProvider;
81     }
82
83     private BundleContext getBundleContext() {
84         ClassLoader tlcl = Thread.currentThread().getContextClassLoader();
85         Bundle bundle = null;
86
87         if (tlcl instanceof BundleReference) {
88             bundle = ((BundleReference) tlcl).getBundle();
89         } else {
90             LOGGER.warn("Unable to determine the bundle context based on " +
91                         "thread context classloader.");
92             bundle = FrameworkUtil.getBundle(this.getClass());
93         }
94         return (bundle == null ? null : bundle.getBundleContext());
95     }
96
97     private static final IBundleScanService lookupBundleScanner(BundleContext ctx) {
98         ServiceReference svcRef = ctx.getServiceReference(IBundleScanService.class);
99         if (svcRef == null) {
100             throw new ServiceException("Unable to lookup IBundleScanService");
101         }
102         return IBundleScanService.class.cast(ctx.getService(svcRef));
103     }
104
105     private final JAXBContext newJAXBContext() {
106         BundleContext ctx = getBundleContext();
107         IBundleScanService svc = lookupBundleScanner(ctx);
108         try {
109             List<Class<?>> cls = svc.getAnnotatedClasses(ctx,
110                     new String[] { XmlRootElement.class.getPackage().getName() },
111                     parseManifestEntry(ctx, JAXRS_EXCLUDES_MANIFEST_NAME),
112                     true);
113             return JAXBContext.newInstance(cls.toArray(new Class[cls.size()]));
114         } catch (JAXBException je) {
115             LOGGER.error("Error creating JAXBContext", je);
116             return null;
117         }
118     }
119
120     private final Set<Class<?>> findJAXRSResourceClasses() {
121         BundleContext ctx = getBundleContext();
122         String bundleName = ctx.getBundle().getSymbolicName();
123         Set<Class<?>> result = new HashSet<Class<?>>();
124         ServiceException recordException = null;
125         try {
126             IBundleScanService svc = lookupBundleScanner(ctx);
127             result.addAll(svc.getAnnotatedClasses(ctx,
128                     new String[] { javax.ws.rs.Path.class.getName() },
129                     null, false));
130         } catch (ServiceException se) {
131             recordException = se;
132             LOGGER.debug("Error finding JAXRS resource annotated classes in " +
133                     "bundle: {} error: {}.", bundleName, se.getMessage());
134             // the bundle scan service cannot be lookedup. Lets attempt to
135             // lookup the resources from the bundle manifest header
136             for (String c : parseManifestEntry(ctx, JAXRS_RESOURCES_MANIFEST_NAME)) {
137                 try {
138                     result.add(ctx.getBundle().loadClass(c));
139                 } catch (ClassNotFoundException cnfe) {
140                     LOGGER.error("Cannot load class: {} in bundle: {} " +
141                             "defined as MANIFEST JAX-RS resource", c, bundleName, cnfe);
142                 }
143             }
144         }
145
146         if (result.size() == 0) {
147             if (recordException != null) {
148                 throw recordException;
149             } else {
150                 throw new ServiceException("No resource classes found in bundle:" +
151                         ctx.getBundle().getSymbolicName());
152             }
153         }
154         return result;
155     }
156
157     private final Set<String> parseManifestEntry(BundleContext ctx, String name) {
158         Set<String> result = new HashSet<String>();
159         Dictionary<String,String> headers = ctx.getBundle().getHeaders();
160         String header = headers.get(name);
161         if (header != null) {
162             for (String s : header.split(",")) {
163                 s = s.trim();
164                 if (s.length() > 0) {
165                     result.add(s);
166                 }
167             }
168         }
169         return result;
170     }
171
172 }