683311e8afaf471e343b3566bc762e191b10135a
[ccsdk/features.git] /
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.ServletException;
30 import javax.servlet.http.HttpServlet;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33 import org.onap.ccsdk.features.sdnr.wt.helpserver.data.HelpInfrastructureObject;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 public class HelpServlet extends HttpServlet implements AutoCloseable {
38
39     private static Logger LOG = LoggerFactory.getLogger(HelpServlet.class);
40     private static final long serialVersionUID = -4285072760648493461L;
41
42     private static final String BASEURI = "/help";
43
44     private static final boolean REDIRECT_LINKS = true;
45
46     private final Path basePath;
47
48     public HelpServlet() {
49         LOG.info("Starting HelpServlet instance {}", this.hashCode());
50         HelpInfrastructureObject.createFilesFromResources();
51         this.basePath = HelpInfrastructureObject.getHelpDirectoryBase();
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             LOG.debug("received get with uri=" + req.getRequestURI());
95             String uri = URLDecoder.decode(req.getRequestURI().substring(BASEURI.length()), "UTF-8");
96             if (uri.startsWith("/")) {
97                 uri = uri.substring(1);
98             }
99             Path p = basePath.resolve(uri);
100             File f = p.toFile();
101             if (f.isFile() && f.exists()) {
102                 LOG.debug("found file for request");
103                 if (this.isTextFile(f)) {
104                     resp.setHeader("Content-Type", "application/text");
105                     resp.setHeader("charset", "utf-8");
106                 } else if (this.isImageFile(f)) {
107                     resp.setHeader("Content-Type", "image/*");
108                 } else if (this.ispdf(f)) {
109                     resp.setHeader("Content-Type", "application/pdf");
110                 } else {
111                     LOG.debug("file is not allowed to deliver");
112                     resp.setStatus(404);
113                     return;
114                 }
115                 LOG.debug("delivering file");
116                 OutputStream out = resp.getOutputStream();
117                 //                if (this.isTextFile(f) && REDIRECT_LINKS) {
118                 //                    String line;
119                 //                    try (BufferedReader br = new BufferedReader(new FileReader(f))) {
120                 //                        line = br.readLine();
121                 //                        while (line != null) {
122                 //                              out.write((line + "\n").getBytes());
123                 //                            line = br.readLine();
124                 //                        }
125                 //                        out.flush();
126                 //                        out.close();
127                 //                        br.close();
128                 //                    }
129                 //                } else
130                 {
131                     try (FileInputStream in = new FileInputStream(f)) {
132
133                         byte[] buffer = new byte[1024];
134                         int len;
135                         while ((len = in.read(buffer)) != -1) {
136                             out.write(buffer, 0, len);
137                         }
138                         in.close();
139                         out.flush();
140                         out.close();
141                     }
142                 }
143             } else {
144                 LOG.debug("found not file for request");
145                 resp.setStatus(404);
146             }
147         }
148     }
149
150     private boolean ispdf(File f) {
151         return f != null ? this.ispdf(f.getName()) : false;
152     }
153
154     private boolean ispdf(String name) {
155         return name != null ? name.toLowerCase().endsWith("pdf") : false;
156     }
157
158     private boolean isImageFile(File f) {
159         return f != null ? this.isImageFile(f.getName()) : false;
160     }
161
162     private boolean isImageFile(String name) {
163
164         return name != null
165                 ? name.toLowerCase().endsWith("png") || name.toLowerCase().endsWith("jpg")
166                         || name.toLowerCase().endsWith("jpeg") || name.toLowerCase().endsWith("svg")
167                         || name.toLowerCase().endsWith("eps")
168                 : false;
169     }
170
171     private boolean isTextFile(File f) {
172         return f != null ? this.isTextFile(f.getName()) : false;
173
174     }
175
176     private boolean isTextFile(String name) {
177         return name != null
178                 ? name.toLowerCase().endsWith("md") || name.toLowerCase().endsWith("txt")
179                         || name.toLowerCase().endsWith("html") || name.toLowerCase().endsWith("htm")
180                         || name.toLowerCase().endsWith("js") || name.toLowerCase().endsWith("css")
181                 : false;
182     }
183
184     @Override
185     public void close() throws Exception {}
186 }