Add data-provider
[ccsdk/features.git] / sdnr / wt / data-provider / provider / src / main / java / org / onap / ccsdk / features / sdnr / wt / dataprovider / http / AboutHttpServlet.java
1 /*******************************************************************************
2  * ============LICENSE_START========================================================================
3  * ONAP : ccsdk feature sdnr wt
4  * =================================================================================================
5  * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6  * =================================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8  * in compliance with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License
13  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14  * or implied. See the License for the specific language governing permissions and limitations under
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.dataprovider.http;
19
20 import java.io.IOException;
21 import java.net.URL;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.jar.Attributes;
26 import java.util.jar.Manifest;
27
28 import javax.servlet.ServletException;
29 import javax.servlet.http.HttpServlet;  
30 import javax.servlet.http.HttpServletRequest;
31 import javax.servlet.http.HttpServletResponse;
32
33 import org.onap.ccsdk.features.sdnr.wt.common.Resources;
34 import org.onap.ccsdk.features.sdnr.wt.common.file.PomFile;
35 import org.onap.ccsdk.features.sdnr.wt.common.file.PomPropertiesFile;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 public class AboutHttpServlet extends HttpServlet {
40
41         /**
42          * 
43          */
44         private static final long serialVersionUID = 1L;
45         private static final Logger LOG = LoggerFactory.getLogger(AboutHttpServlet.class);
46
47         private static final String URI_PRE = "/about";
48         private static final String RES_BASEPATH = "about/";
49
50         private static final String PLACEHOLDER_ONAP_RELEASENAME = "{release-name}";
51         private static final String PLACEHOLDER_ODL_RELEASENAME = "{odl-version}";
52         private static final String PLACEHOLDER_BUILD_TIMESTAMP = "{build-time}";
53         private static final String PLACEHOLDER_ODLUX_REVISION = "{odlux-revision}";
54         private static final String PLACEHOLDER_PACAKGE_VERSION = "{package-version}";
55         private static final String README_FILE = "README.md";
56
57         private final String groupId="org.onap.ccsdk.features.sdnr.wt";
58         private final String artifactId="sdnr-wt-data-provider-provider";
59         
60 //      private final ConfigurationFileRepresentation configuration;
61         //private final ExtRestClient dbClient;
62         private final Map<String, String> data;
63         private final String readmeContent;
64         
65         
66
67         public AboutHttpServlet() {
68 //              this.configuration = new ConfigurationFileRepresentation(DataProviderServiceImpl.CONFIGURATIONFILE);
69 //              EsConfig esConfig = new EsConfig(configuration);
70                 //this.dbClient = ExtRestClient.createInstance(esConfig.getHosts());
71                 this.data = new HashMap<>();
72                 this.collectStaticData();
73                 this.readmeContent = this.render(this.getFileContent(README_FILE));
74         }
75
76         private void collectStaticData() {
77                 PomPropertiesFile props = this.getPomProperties();
78                 this.data.put(PLACEHOLDER_ONAP_RELEASENAME, this.getPomProperty("onap.distname"));
79                 this.data.put(PLACEHOLDER_ODL_RELEASENAME,  this.getPomProperty("odl.distname") );
80                 this.data.put(PLACEHOLDER_BUILD_TIMESTAMP, props!=null?props.getBuildDate().toString():"");
81                 this.data.put(PLACEHOLDER_ODLUX_REVISION, this.getPomProperty("odlux.buildno"));
82                 this.data.put(PLACEHOLDER_PACAKGE_VERSION, this.getManifestValue("Bundle-Version"));
83         }
84
85         @Override
86         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
87
88                 String uri = req.getRequestURI().substring(URI_PRE.length());
89                 LOG.debug("request for {}",uri);
90                 if (uri.length() <= 0 || uri.equals("/")) {
91                         // collect data
92                         this.collectData();
93                         // render readme
94                         String content = this.render();
95                         byte[] output = content!=null?content.getBytes():new byte[0];
96                         // output
97                         resp.setStatus(HttpServletResponse.SC_OK);
98                         resp.setContentLength(output.length);
99                         resp.setContentType("text/plain");
100                         resp.getOutputStream().write(output);
101
102                 } else {
103                         this.doGetFile(uri, resp);
104                 }
105         }
106
107         private String getFileContent(String filename) {
108                 LOG.debug("try ti get content of {}",filename);
109                 return Resources.getFileContent(AboutHttpServlet.class,RES_BASEPATH + filename);
110         }
111
112         private void collectData() {
113                 // TODO Auto-generated method stub
114
115         }
116
117         private String getManifestValue(String key) {
118                 URL url = Resources.getUrlForRessource(AboutHttpServlet.class, "/META-INF/MANIFEST.MF");
119                 if(url==null) {
120                         return null;
121                 }
122                 Manifest manifest;
123                 try {
124                         manifest = new Manifest(url.openStream());
125                         Attributes attr = manifest.getMainAttributes();
126                         return attr.getValue(key);
127                 } catch (IOException e) {
128                         LOG.warn("problem reading manifest: {}",e);
129                 }
130                 return null;
131
132         }
133         private PomPropertiesFile getPomProperties() {
134                 URL url = Resources.getUrlForRessource(AboutHttpServlet.class, "/META-INF/maven/"+groupId+"/"+artifactId+"/pom.properties");
135                 PomPropertiesFile propfile;
136                 if(url==null) {
137                         return null;
138                 }
139                 try {
140                         propfile = new PomPropertiesFile(url.openStream());
141                         return propfile;
142                 } catch (Exception e) {
143                         LOG.warn("unable to read inner pom file: {}",e);
144                 }
145                 return null;
146         }
147         private String getPomProperty(String key) {
148                 LOG.info("try to get pom property for {}",key);
149                 URL url = Resources.getUrlForRessource(AboutHttpServlet.class,"/META-INF/maven/"+groupId+"/"+artifactId+"/pom.xml");
150                 if(url==null) {
151                         return null;
152                 }
153                 PomFile pomfile;
154                 try {
155                         pomfile = new PomFile(url.openStream());
156                         return pomfile.getProperty(key);
157                 } catch (Exception e) {
158                         LOG.warn("unable to read inner pom file: {}",e);
159                 }
160                 return null;
161         }
162         private void doGetFile(String uri, HttpServletResponse resp) {
163                 String content = this.getFileContent(uri);
164                 if (content == null) {
165                         try {
166                                 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
167                         } catch (IOException e) {
168                                 LOG.debug("unable to send error response : {}",e);
169                         }
170                 } else {
171                         byte[] data = content.getBytes();
172                         resp.setStatus(HttpServletResponse.SC_OK);
173                         resp.setContentType(this.getContentType(uri));
174                         try {
175                                 resp.getOutputStream().write(data);
176                         } catch (IOException e) {
177                                 LOG.debug("unable to send data : {}",e);
178                         }
179                 }
180
181         }
182
183         private String getContentType(String filename) {
184                 String ext = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();
185                 switch (ext) {
186                 case "jpg":
187                 case "jpeg":
188                 case "svg":
189                 case "png":
190                 case "gif":
191                 case "bmp":
192                         return "image/" + ext;
193                 case "json":
194                         return "application/json";
195                 case "html":
196                 case "htm":
197                         return "text/html";
198                 case "txt":
199                 case "md":
200                 default:
201                         return "text/plain";
202                 }
203         }
204
205         private String render() {
206                 return this.render(null);
207         }
208
209         private String render(String content) {
210                 if (content == null) {
211                         content = this.readmeContent;
212                 }
213                 if(content==null) {
214                         return null;
215                 }
216                 for (Entry<String, String> entry : this.data.entrySet()) {
217                         if (entry.getValue() != null && content.contains(entry.getKey())) {
218                                 content = content.replace(entry.getKey(), entry.getValue());
219                         }
220                 }
221
222                 return content;
223         }
224 }