Create wt-odlux directory
[ccsdk/features.git] / sdnr / wt-odlux / helpserver / provider / src / main / java / org / onap / ccsdk / features / sdnr / wt / helpserver / HelpServlet.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.helpserver;
19
20 import java.io.BufferedReader;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileReader;
24 import java.io.IOException;
25 import java.io.OutputStream;
26 import java.net.URISyntaxException;
27 import java.net.URLDecoder;
28 import java.nio.file.Path;
29 import javax.servlet.Servlet;
30 import javax.servlet.ServletException;
31 import javax.servlet.http.HttpServlet;
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34 import org.onap.ccsdk.features.sdnr.wt.helpserver.data.HelpInfrastructureObject;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 public class HelpServlet extends HttpServlet implements AutoCloseable {
39
40     private static Logger LOG = LoggerFactory.getLogger(HelpServlet.class);
41     private static final long serialVersionUID = -4285072760648493461L;
42
43     private static final String BASEURI = "/help";
44
45     private final Path basePath;
46
47     public HelpServlet() {
48         LOG.info("Starting HelpServlet instance {}", this.hashCode());
49 //        HelpInfrastructureObject.createFilesFromResources();
50 //        this.basePath = HelpInfrastructureObject.getHelpDirectoryBase();
51         this.basePath = Path.of("bitnami/nginx/help");
52     }
53
54     @Override
55     public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
56         resp.addHeader("Access-Control-Allow-Origin", "*");
57         resp.addHeader("Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE");
58         resp.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Content-Length");
59     }
60
61     @Override
62     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
63         String query = req.getQueryString();
64         resp.addHeader("Access-Control-Allow-Origin", "*");
65         resp.addHeader("Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE");
66         resp.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Content-Length");
67 //        if (query != null && query.contains("meta")) {
68 //
69 //            File f = new File(HelpInfrastructureObject.KARAFHELPDIRECTORY, "meta.json");
70 //            if (f.exists()) {
71 //                LOG.debug("found local meta file");
72 //                try (BufferedReader rd = new BufferedReader(new FileReader(f));) {
73 //                    String line = rd.readLine();
74 //                    while (line != null) {
75 //                        resp.getOutputStream().println(line);
76 //                        line = rd.readLine();
77 //                    }
78 //                    rd.close();
79 //                } catch (IOException e) {
80 //                    LOG.debug("Can not read meta file", e);
81 //                }
82 //            } else {
83 //                LOG.debug("start walking from path=" + basePath.toAbsolutePath().toString());
84 //                HelpInfrastructureObject o = null;
85 //                try {
86 //                    o = new HelpInfrastructureObject(this.basePath);
87 //                } catch (URISyntaxException e) {
88 //                    LOG.debug("Can not relsolve URI. ", e);
89 //                }
90 //                resp.getOutputStream().println(o != null ? o.toString() : "");
91 //            }
92 //            resp.setHeader("Content-Type", "application/json");
93 //        } else 
94         {
95             LOG.debug("received get with uri=" + req.getRequestURI());
96             String uri = URLDecoder.decode(req.getRequestURI().substring(BASEURI.length()), "UTF-8");
97             if (uri.startsWith("/")) {
98                 uri = uri.substring(1);
99             }
100             Path p = basePath.resolve(uri);
101             File f = p.toFile();
102             if (f.isFile() && f.exists()) {
103                 LOG.debug("found file for request");
104                 if (this.isTextFile(f)) {
105                     resp.setHeader("Content-Type", "application/text");
106                     resp.setHeader("charset", "utf-8");
107                 } else if (this.isImageFile(f)) {
108                     resp.setHeader("Content-Type", "image/*");
109                 } else if (this.ispdf(f)) {
110                     resp.setHeader("Content-Type", "application/pdf");
111                 } else {
112                     LOG.debug("file is not allowed to deliver");
113                     resp.setStatus(404);
114                     return;
115                 }
116                 LOG.debug("delivering file");
117                 try (OutputStream out = resp.getOutputStream()) {
118                     try (FileInputStream in = new FileInputStream(f)) {
119
120                         byte[] buffer = new byte[1024];
121                         int len;
122                         while ((len = in.read(buffer)) != -1) {
123                             out.write(buffer, 0, len);
124                         }
125                         in.close();
126                         out.flush();
127                         out.close();
128                     }
129                 } catch (IOException e) {
130                     LOG.warn("Can not write meta file", e);
131                     resp.setStatus(500);
132                 }
133             } else {
134                 LOG.debug("found not file for request");
135                 resp.setStatus(404);
136             }
137         }
138     }
139
140     private boolean ispdf(File f) {
141         return f != null && this.ispdf(f.getName());
142     }
143
144     private boolean ispdf(String name) {
145         return name != null && name.toLowerCase().endsWith("pdf");
146     }
147
148     private boolean isImageFile(File f) {
149         return f != null && this.isImageFile(f.getName());
150     }
151
152     private boolean isImageFile(String name) {
153
154         return name != null
155                 ? name.toLowerCase().endsWith("png") || name.toLowerCase().endsWith("jpg")
156                         || name.toLowerCase().endsWith("jpeg") || name.toLowerCase().endsWith("svg")
157                         || name.toLowerCase().endsWith("eps")
158                 : false;
159     }
160
161     private boolean isTextFile(File f) {
162         return f != null && this.isTextFile(f.getName());
163
164     }
165
166     private boolean isTextFile(String name) {
167         return name != null
168                 ? name.toLowerCase().endsWith("md") || name.toLowerCase().endsWith("txt")
169                         || name.toLowerCase().endsWith("html") || name.toLowerCase().endsWith("htm")
170                         || name.toLowerCase().endsWith("js") || name.toLowerCase().endsWith("css")
171                 : false;
172     }
173
174         @Override
175         public void close() throws Exception {
176
177         }
178
179 }