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