Support for FIQL queries on REST retreive operations
[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.opendaylight.controller.northbound.bundlescanner.IBundleScanService;
23 import org.opendaylight.controller.northbound.commons.query.QueryContextProvider;
24 import org.osgi.framework.Bundle;
25 import org.osgi.framework.BundleContext;
26 import org.osgi.framework.BundleReference;
27 import org.osgi.framework.FrameworkUtil;
28 import org.osgi.framework.ServiceException;
29 import org.osgi.framework.ServiceReference;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import com.fasterxml.jackson.databind.DeserializationFeature;
34 import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
35
36 /**
37  * Instance of javax.ws.rs.core.Application used to return the classes
38  * that will be instantiated for JAXRS processing. This hooks onto the
39  * bundle scanner service to provide JAXB classes to JAX-RS for prorcessing.
40  */
41 public class NorthboundApplication extends Application {
42     public static final String JAXRS_RESOURCES_MANIFEST_NAME = "Jaxrs-Resources";
43     public static final String JAXRS_EXCLUDES_MANIFEST_NAME = "Jaxrs-Exclude-Types";
44     private static final Logger LOGGER = LoggerFactory.getLogger(NorthboundApplication.class);
45     private final Set<Object> _singletons;
46
47     public NorthboundApplication() {
48         _singletons = new HashSet<Object>();
49         _singletons.add(new ContextResolver<JAXBContext>() {
50             JAXBContext jaxbContext;
51             @Override
52             public synchronized JAXBContext getContext(Class<?> type) {
53                 if (jaxbContext == null) {
54                     jaxbContext = newJAXBContext();
55                 }
56                 return jaxbContext;
57             }
58
59         } );
60         _singletons.add(getJsonProvider());
61         _singletons.add(new JacksonJsonProcessingExceptionMapper());
62         _singletons.add(new QueryContextProvider());
63     }
64
65     ////////////////////////////////////////////////////////////////
66     //  Application overrides
67     ////////////////////////////////////////////////////////////////
68
69     @Override
70     public Set<Object> getSingletons() {
71         return _singletons;
72     }
73
74     @Override
75     public Set<Class<?>> getClasses() {
76         Set<Class<?>> result = new HashSet<Class<?>>();
77         result.addAll(findJAXRSResourceClasses());
78         return result;
79     }
80
81     private static final JacksonJaxbJsonProvider getJsonProvider() {
82         JacksonJaxbJsonProvider jsonProvider = new JacksonJaxbJsonProvider();
83         jsonProvider.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
84                 false);
85         return jsonProvider;
86     }
87
88     private BundleContext getBundleContext() {
89         ClassLoader tlcl = Thread.currentThread().getContextClassLoader();
90         Bundle bundle = null;
91
92         if (tlcl instanceof BundleReference) {
93             bundle = ((BundleReference) tlcl).getBundle();
94         } else {
95             LOGGER.warn("Unable to determine the bundle context based on " +
96                         "thread context classloader.");
97             bundle = FrameworkUtil.getBundle(this.getClass());
98         }
99         return (bundle == null ? null : bundle.getBundleContext());
100     }
101
102     private static final IBundleScanService lookupBundleScanner(BundleContext ctx) {
103         ServiceReference<?> svcRef = ctx.getServiceReference(IBundleScanService.class);
104         if (svcRef == null) {
105             throw new ServiceException("Unable to lookup IBundleScanService");
106         }
107         return IBundleScanService.class.cast(ctx.getService(svcRef));
108     }
109
110     private final JAXBContext newJAXBContext() {
111         BundleContext ctx = getBundleContext();
112         IBundleScanService svc = lookupBundleScanner(ctx);
113         try {
114             List<Class<?>> cls = svc.getAnnotatedClasses(ctx,
115                     new String[] { XmlRootElement.class.getPackage().getName() },
116                     parseManifestEntry(ctx, JAXRS_EXCLUDES_MANIFEST_NAME),
117                     true);
118             return JAXBContext.newInstance(cls.toArray(new Class[cls.size()]));
119         } catch (JAXBException je) {
120             LOGGER.error("Error creating JAXBContext", je);
121             return null;
122         }
123     }
124
125     private final Set<Class<?>> findJAXRSResourceClasses() {
126         BundleContext ctx = getBundleContext();
127         String bundleName = ctx.getBundle().getSymbolicName();
128         Set<Class<?>> result = new HashSet<Class<?>>();
129         ServiceException recordException = null;
130         try {
131             IBundleScanService svc = lookupBundleScanner(ctx);
132             result.addAll(svc.getAnnotatedClasses(ctx,
133                     new String[] { javax.ws.rs.Path.class.getName() },
134                     null, false));
135         } catch (ServiceException se) {
136             recordException = se;
137             LOGGER.debug("Error finding JAXRS resource annotated classes in " +
138                     "bundle: {} error: {}.", bundleName, se.getMessage());
139             // the bundle scan service cannot be lookedup. Lets attempt to
140             // lookup the resources from the bundle manifest header
141             for (String c : parseManifestEntry(ctx, JAXRS_RESOURCES_MANIFEST_NAME)) {
142                 try {
143                     result.add(ctx.getBundle().loadClass(c));
144                 } catch (ClassNotFoundException cnfe) {
145                     LOGGER.error("Cannot load class: {} in bundle: {} " +
146                             "defined as MANIFEST JAX-RS resource", c, bundleName, cnfe);
147                 }
148             }
149         }
150
151         if (result.size() == 0) {
152             if (recordException != null) {
153                 throw recordException;
154             } else {
155                 throw new ServiceException("No resource classes found in bundle:" +
156                         ctx.getBundle().getSymbolicName());
157             }
158         }
159         return result;
160     }
161
162     private final Set<String> parseManifestEntry(BundleContext ctx, String name) {
163         Set<String> result = new HashSet<String>();
164         Dictionary<String,String> headers = ctx.getBundle().getHeaders();
165         String header = headers.get(name);
166         if (header != null) {
167             for (String s : header.split(",")) {
168                 s = s.trim();
169                 if (s.length() > 0) {
170                     result.add(s);
171                 }
172             }
173         }
174         return result;
175     }
176
177 }