Enable spotbugs in mdsal-binding-dom-codec-osgi
[mdsal.git] / binding / mdsal-binding-dom-codec-osgi / src / main / java / org / opendaylight / mdsal / binding / dom / codec / osgi / impl / ModuleInfoBundleTracker.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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 package org.opendaylight.mdsal.binding.dom.codec.osgi.impl;
9
10 import static com.google.common.base.Preconditions.checkNotNull;
11
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.io.Resources;
14 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.io.IOException;
16 import java.net.URL;
17 import java.nio.charset.StandardCharsets;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.List;
21 import java.util.regex.Pattern;
22 import org.opendaylight.yangtools.concepts.ObjectRegistration;
23 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
24 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
25 import org.osgi.framework.Bundle;
26 import org.osgi.framework.BundleEvent;
27 import org.osgi.util.tracker.BundleTrackerCustomizer;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * Tracks bundles and attempts to retrieve YangModuleInfo, which is then fed into ModuleInfoRegistry.
33  */
34 final class ModuleInfoBundleTracker implements BundleTrackerCustomizer<Collection<ObjectRegistration<YangModuleInfo>>> {
35     private static final Logger LOG = LoggerFactory.getLogger(ModuleInfoBundleTracker.class);
36     // FIXME: this should be in a place shared with maven-sal-api-gen-plugin
37     private static final String MODULE_INFO_PROVIDER_PATH_PREFIX = "META-INF/services/";
38
39     private static final String YANG_MODLE_BINDING_PROVIDER_SERVICE = MODULE_INFO_PROVIDER_PATH_PREFIX
40             + YangModelBindingProvider.class.getName();
41
42     private static final Pattern BRACE_PATTERN = Pattern.compile("{}", Pattern.LITERAL);
43
44     private final OsgiModuleInfoRegistry moduleInfoRegistry;
45
46     private volatile boolean starting = true;
47
48     ModuleInfoBundleTracker(final OsgiModuleInfoRegistry moduleInfoRegistry) {
49         this.moduleInfoRegistry = checkNotNull(moduleInfoRegistry);
50     }
51
52     void finishStart() {
53         starting = false;
54         moduleInfoRegistry.updateService();
55     }
56
57     @Override
58     @SuppressWarnings("checkstyle:illegalCatch")
59     public Collection<ObjectRegistration<YangModuleInfo>> addingBundle(final Bundle bundle, final BundleEvent event) {
60         final URL resource = bundle.getEntry(YANG_MODLE_BINDING_PROVIDER_SERVICE);
61         if (resource == null) {
62             LOG.debug("Bundle {} does not have an entry for {}", bundle, YANG_MODLE_BINDING_PROVIDER_SERVICE);
63             return ImmutableList.of();
64         }
65
66         LOG.debug("Got addingBundle({}) with YangModelBindingProvider resource {}", bundle, resource);
67         final List<String> lines;
68         try {
69             lines = Resources.readLines(resource, StandardCharsets.UTF_8);
70         } catch (IOException e) {
71             LOG.error("Error while reading {} from bundle {}", resource, bundle, e);
72             return ImmutableList.of();
73         }
74
75         if (lines.isEmpty()) {
76             LOG.debug("Bundle {} has empty services for {}", bundle, YANG_MODLE_BINDING_PROVIDER_SERVICE);
77             return ImmutableList.of();
78         }
79
80         final List<ObjectRegistration<YangModuleInfo>> registrations = new ArrayList<>(lines.size());
81         for (String moduleInfoName : lines) {
82             LOG.trace("Retrieve ModuleInfo({}, {})", moduleInfoName, bundle);
83             final YangModuleInfo moduleInfo;
84             try {
85                 moduleInfo = retrieveModuleInfo(moduleInfoName, bundle);
86             } catch (RuntimeException e) {
87                 LOG.warn("Failed to acquire {} from bundle {}, ignoring it", moduleInfoName, bundle, e);
88                 continue;
89             }
90
91             registrations.add(moduleInfoRegistry.registerModuleInfo(moduleInfo));
92         }
93
94         if (!starting) {
95             moduleInfoRegistry.updateService();
96         }
97
98         LOG.trace("Bundle {} resultend in registrations {}", bundle, registrations);
99         return registrations;
100     }
101
102     @Override
103     public void modifiedBundle(final Bundle bundle, final BundleEvent event,
104             final Collection<ObjectRegistration<YangModuleInfo>> object) {
105         // No-op
106     }
107
108     @Override
109     @SuppressWarnings("checkstyle:illegalCatch")
110     public void removedBundle(final Bundle bundle, final BundleEvent event,
111             final Collection<ObjectRegistration<YangModuleInfo>> regs) {
112         if (regs == null) {
113             return;
114         }
115
116         for (ObjectRegistration<YangModuleInfo> reg : regs) {
117             try {
118                 reg.close();
119             } catch (Exception e) {
120                 LOG.warn("Unable to unregister YangModuleInfo {}", reg.getInstance(), e);
121             }
122         }
123     }
124
125     private static YangModuleInfo retrieveModuleInfo(final String moduleInfoClass, final Bundle bundle) {
126         final Class<?> clazz = loadClass(moduleInfoClass, bundle);
127         if (!YangModelBindingProvider.class.isAssignableFrom(clazz)) {
128             String errorMessage = logMessage("Class {} does not implement {} in bundle {}", clazz,
129                 YangModelBindingProvider.class, bundle);
130             throw new IllegalStateException(errorMessage);
131         }
132
133         final YangModelBindingProvider instance;
134         try {
135             Object instanceObj = clazz.newInstance();
136             instance = YangModelBindingProvider.class.cast(instanceObj);
137         } catch (InstantiationException e) {
138             String errorMessage = logMessage("Could not instantiate {} in bundle {}, reason {}", moduleInfoClass,
139                 bundle, e);
140             throw new IllegalStateException(errorMessage, e);
141         } catch (IllegalAccessException e) {
142             String errorMessage = logMessage("Illegal access during instantiation of class {} in bundle {}, reason {}",
143                     moduleInfoClass, bundle, e);
144             throw new IllegalStateException(errorMessage, e);
145         }
146
147         try {
148             return instance.getModuleInfo();
149         } catch (NoClassDefFoundError | ExceptionInInitializerError e) {
150             throw new IllegalStateException("Error while executing getModuleInfo on " + instance, e);
151         }
152     }
153
154     private static Class<?> loadClass(final String moduleInfoClass, final Bundle bundle) {
155         try {
156             return bundle.loadClass(moduleInfoClass);
157         } catch (ClassNotFoundException e) {
158             String errorMessage = logMessage("Could not find class {} in bundle {}, reason {}", moduleInfoClass, bundle,
159                 e);
160             throw new IllegalStateException(errorMessage);
161         }
162     }
163
164     @SuppressFBWarnings("SLF4J_UNKNOWN_ARRAY")
165     private static String logMessage(final String slfMessage, final Object... params) {
166         LOG.info(slfMessage, params);
167         return String.format(BRACE_PATTERN.matcher(slfMessage).replaceAll("%s"), params);
168     }
169 }