2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.http.about;
24 import java.io.IOException;
26 import java.util.Date;
27 import java.util.HashMap;
29 import java.util.Map.Entry;
30 import java.util.jar.Attributes;
31 import java.util.jar.Manifest;
32 import javax.servlet.ServletException;
33 import javax.servlet.ServletOutputStream;
34 import javax.servlet.http.HttpServlet;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
37 import org.apache.http.HttpHeaders;
38 import org.onap.ccsdk.features.sdnr.wt.common.Resources;
39 import org.onap.ccsdk.features.sdnr.wt.common.file.PomFile;
40 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.types.NetconfTimeStampImpl;
41 import org.osgi.framework.Bundle;
42 import org.osgi.framework.BundleContext;
43 import org.osgi.framework.FrameworkUtil;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 public class AboutHttpServlet extends HttpServlet {
52 private static final long serialVersionUID = 1L;
53 private static final Logger LOG = LoggerFactory.getLogger(AboutHttpServlet.class);
54 private static final String UNKNOWN = "unknown";
55 private static final String METAINF_MAVEN = "/META-INF/maven/";
56 private static final String EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE = "unable to read inner pom file: {}";
58 public static final String URI_PRE = "/about";
59 private static final String RES_BASEPATH = "about/";
61 private static final String PLACEHOLDER_ONAP_RELEASENAME = "{release-name}";
62 private static final String PLACEHOLDER_ONAP_RELEASEVERSION = "{release-version}";
63 private static final String PLACEHOLDER_ODL_RELEASENAME = "{odl-version}";
64 private static final String PLACEHOLDER_BUILD_TIMESTAMP = "{build-time}";
65 private static final String PLACEHOLDER_PACKAGE_GITHASH = "{package-githash}";
66 private static final String PLACEHOLDER_PACAKGE_VERSION = "{package-version}";
67 private static final String PLACEHOLDER_CCSDK_VERSION = "{ccsdk-version}";
68 private static final String PLACEHOLDER_CLUSTER_SIZE = "{cluster-size}";
69 private static final String PLACEHOLDER_MDSAL_VERSION = "{mdsal-version}";
70 private static final String PLACEHOLDER_YANGTOOLS_VERSION = "{yangtools-version}";
71 private static final String PLACEHOLDER_KARAF_INFO = "{karaf-info}";
72 private static final String PLACEHOLDER_DEVICEMANAGER_TABLE = "{devicemanagers}";
73 private static final String README_FILE = "README.md";
74 private static final String JSON_FILE = "README.json";
75 private static final String NO_DEVICEMANAGERS_RUNNING_MESSAGE = null;
76 private static final String MIMETYPE_JSON = "application/json";
77 private static final String MIMETYPE_MARKDOWN = "text/markdown";
79 private final String groupId = this.getGroupIdOrDefault("org.onap.ccsdk.features.sdnr.wt");
80 private final String artifactId = "sdnr-wt-data-provider-provider";
82 private final Map<Integer, String> BUNDLESTATE_LUT;
83 private final Map<String, String> data;
84 private final String readmeContent;
85 private final String jsonContent;
88 public AboutHttpServlet() {
90 this.data = new HashMap<>();
91 this.collectStaticData();
92 this.readmeContent = this.render(ContentType.MARKDOWN, this.getResourceFileContent(README_FILE));
93 this.jsonContent = this.render(ContentType.MARKDOWN, this.getResourceFileContent(JSON_FILE));
94 this.BUNDLESTATE_LUT = new HashMap<>();
95 this.BUNDLESTATE_LUT.put(Bundle.UNINSTALLED, "uninstalled");
96 this.BUNDLESTATE_LUT.put(Bundle.INSTALLED, "installed");
97 this.BUNDLESTATE_LUT.put(Bundle.RESOLVED, "resolved");
98 this.BUNDLESTATE_LUT.put(Bundle.STARTING, "starting");
99 this.BUNDLESTATE_LUT.put(Bundle.STOPPING, "stopping");
100 this.BUNDLESTATE_LUT.put(Bundle.ACTIVE, "active");
103 protected String getGroupIdOrDefault(String def) {
104 String symbolicName = this.getManifestValue("Bundle-SymbolicName");
105 if (symbolicName != null) {
106 int idx = symbolicName.indexOf(this.artifactId);
108 return symbolicName.substring(0, idx - 1);
115 * collect static versioning data
117 private void collectStaticData() {
118 final String ccsdkVersion = this.getPomParentVersion();
119 final String mdsalVersion = SystemInfo.getMdSalVersion(UNKNOWN);
120 this.data.put(PLACEHOLDER_ONAP_RELEASENAME, ODLVersionLUT.getONAPReleaseName(ccsdkVersion, UNKNOWN));
121 this.data.put(PLACEHOLDER_ODL_RELEASENAME, ODLVersionLUT.getOdlVersion(mdsalVersion, UNKNOWN));
122 this.data.put(PLACEHOLDER_BUILD_TIMESTAMP, getDate(this.getManifestValue("Bnd-LastModified"), UNKNOWN));
123 this.data.put(PLACEHOLDER_PACAKGE_VERSION, this.getManifestValue("Bundle-Version"));
124 this.data.put(PLACEHOLDER_CCSDK_VERSION, ccsdkVersion);
125 this.data.put(PLACEHOLDER_ONAP_RELEASEVERSION, SystemInfo.getOnapVersion(UNKNOWN));
126 this.data.put(PLACEHOLDER_MDSAL_VERSION, mdsalVersion);
127 this.data.put(PLACEHOLDER_YANGTOOLS_VERSION, SystemInfo.getYangToolsVersion(UNKNOWN));
128 this.data.put(PLACEHOLDER_PACKAGE_GITHASH, this.getGitHash(UNKNOWN));
131 private String getDate(String value, String defaultValue) {
136 long x = Long.parseLong(value);
137 return NetconfTimeStampImpl.getConverter().getTimeStampAsNetconfString(new Date(x));
139 catch(NumberFormatException e) {
140 LOG.debug("date value is not a numeric one");
146 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
148 String uri = req.getRequestURI().substring(URI_PRE.length());
149 LOG.debug("request for {}", uri);
150 if (uri.length() <= 0 || uri.equals("/")) {
151 ContentType ctype = this.detectContentType(req, ContentType.MARKDOWN);
153 this.collectData(ctype);
155 String content = this.render(ctype);
156 byte[] output = content != null ? content.getBytes() : new byte[0];
158 resp.setStatus(HttpServletResponse.SC_OK);
159 resp.setContentLength(output.length);
160 resp.setContentType(ctype.getMimeType());
161 try (ServletOutputStream os = resp.getOutputStream()) {
163 } catch (IOException e) {
164 LOG.warn("problem writing response for {}: {}", uri, e);
167 this.doGetFile(uri, resp);
172 * load git.commit.id from jar /META-INF/git.properties
176 private String getGitHash(String def) {
177 String content = Resources.getFileContent(AboutHttpServlet.class, "/META-INF/git.properties");
178 if (content == null) {
181 String[] lines = content.split("\n");
182 for (String line : lines) {
183 if (line.startsWith("git.commit.id")) {
184 def = line.substring("git.commit.id=".length());
191 private String getResourceFileContent(String filename) {
192 LOG.debug("try ti get content of {}", filename);
193 return Resources.getFileContent(AboutHttpServlet.class, RES_BASEPATH + filename);
197 * collect dynamic data for about.md
199 private void collectData(ContentType ctype) {
200 LOG.info("collecting dynamic data with content-type {}", ctype);
202 this.data.put(PLACEHOLDER_KARAF_INFO, SystemInfo.get());
203 this.data.put(PLACEHOLDER_DEVICEMANAGER_TABLE, this.getDevicemanagerBundles(ctype));
204 } catch (Exception e) {
205 LOG.warn("problem collecting system data: ", e);
210 * get value for key out of /META-INF/MANIFEST.MF
215 protected String getManifestValue(String key) {
216 URL url = Resources.getUrlForRessource(AboutHttpServlet.class, "/META-INF/MANIFEST.MF");
222 manifest = new Manifest(url.openStream());
223 Attributes attr = manifest.getMainAttributes();
224 return attr.getValue(key);
225 } catch (IOException e) {
226 LOG.warn("problem reading manifest: ", e);
233 * get parent pom version out of /META-INF/maven/groupId/artifactId/pom.xml
237 private String getPomParentVersion() {
238 LOG.info("try to get pom parent version");
239 URL url = Resources.getUrlForRessource(AboutHttpServlet.class,
240 METAINF_MAVEN + groupId + "/" + artifactId + "/pom.xml");
246 pomfile = new PomFile(url.openStream());
247 return pomfile.getParentVersion();
248 } catch (Exception e) {
249 LOG.warn(EXCEPTION_FORMAT_UNABLE_TO_READ_INNER_POMFILE, e);
254 private String getDevicemanagerBundles(ContentType ctype) {
255 Bundle thisbundle = FrameworkUtil.getBundle(this.getClass());
256 BundleContext context = thisbundle == null ? null : thisbundle.getBundleContext();
257 if (context == null) {
258 LOG.debug("no bundle context available");
259 return ctype == ContentType.MARKDOWN ? "" : "[]";
261 Bundle[] bundles = context.getBundles();
262 if (bundles == null || bundles.length <= 0) {
263 LOG.debug("no bundles found");
264 return ctype == ContentType.MARKDOWN ? NO_DEVICEMANAGERS_RUNNING_MESSAGE : "[]";
266 LOG.debug("found {} bundles", bundles.length);
267 MarkdownTable table = new MarkdownTable();
268 table.setHeader(new String[] {"Bundle-Id", "Version", "Symbolic-Name", "Status"});
270 for (Bundle bundle : bundles) {
271 name = bundle.getSymbolicName();
272 if (!(name.contains("devicemanager") && name.contains("provider"))) {
275 if (name.equals("org.onap.ccsdk.features.sdnr.wt.sdnr-wt-devicemanager-provider")) {
278 table.addRow(new String[] {String.valueOf(bundle.getBundleId()), bundle.getVersion().toString(), name,
279 BUNDLESTATE_LUT.getOrDefault(bundle.getState(), UNKNOWN)});
282 return ctype == ContentType.MARKDOWN ? table.toMarkDown() : table.toJson();
286 * get file by uri from resources and write out to response stream
291 private void doGetFile(String uri, HttpServletResponse resp) {
292 String content = this.getResourceFileContent(uri);
293 if (content == null) {
295 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
296 } catch (IOException e) {
297 LOG.debug("unable to send error response : {}", e);
300 byte[] data = content.getBytes();
301 resp.setStatus(HttpServletResponse.SC_OK);
302 resp.setContentType(this.getContentType(uri));
304 resp.getOutputStream().write(data);
305 } catch (IOException e) {
306 LOG.debug("unable to send data: ", e);
313 * create http response contentType by filename
318 private String getContentType(String filename) {
319 String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
327 return "image/" + ext;
329 return MIMETYPE_JSON;
341 * render this.readmeContent with this.data
347 private String render(ContentType ctype) {
348 return this.render(ctype, null);
352 * render content with this.data
357 private String render(ContentType ctype, String content) {
358 if (content == null) {
359 content = ctype == ContentType.MARKDOWN ? this.readmeContent : this.jsonContent;
361 if (content == null) {
364 for (Entry<String, String> entry : this.data.entrySet()) {
365 if (entry.getValue() != null && content.contains(entry.getKey())) {
366 content = content.replace(entry.getKey(), entry.getValue());
373 public void setClusterSize(String value) {
374 this.data.put(PLACEHOLDER_CLUSTER_SIZE, value);
377 private ContentType detectContentType(HttpServletRequest req, ContentType def) {
378 String accept = req.getHeader(HttpHeaders.ACCEPT);
379 if (accept != null) {
380 if (accept.equals(MIMETYPE_JSON)) {
381 return ContentType.JSON;
382 } else if (accept.equals(MIMETYPE_MARKDOWN)) {
383 return ContentType.MARKDOWN;
389 private enum ContentType {
390 MARKDOWN(MIMETYPE_MARKDOWN), JSON(MIMETYPE_JSON);
392 private String mimeType;
394 ContentType(String mimeType) {
395 this.mimeType = mimeType;
398 String getMimeType() {
399 return this.mimeType;