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
10 * http://www.apache.org/licenses/LICENSE-2.0
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
16 * ============LICENSE_END==========================================================================
17 ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.helpserver;
20 import java.io.BufferedReader;
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 java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31 import javax.servlet.ServletException;
32 import javax.servlet.http.HttpServlet;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35 import org.onap.ccsdk.features.sdnr.wt.helpserver.data.HelpInfrastructureObject;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
39 public class HelpServlet extends HttpServlet implements AutoCloseable {
41 private static Logger LOG = LoggerFactory.getLogger(HelpServlet.class);
42 private static final long serialVersionUID = -4285072760648493461L;
44 private static final String BASEURI = "/help";
46 private static final boolean REDIRECT_LINKS = true;
48 private final Path basePath;
50 public HelpServlet() {
51 LOG.info("Starting HelpServlet instance {}", this.hashCode());
52 HelpInfrastructureObject.createFilesFromResources();
53 this.basePath = HelpInfrastructureObject.getHelpDirectoryBase();
57 public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
58 resp.addHeader("Access-Control-Allow-Origin", "*");
59 resp.addHeader("Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE");
60 resp.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Content-Length");
64 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
65 String query = req.getQueryString();
66 resp.addHeader("Access-Control-Allow-Origin", "*");
67 resp.addHeader("Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE");
68 resp.addHeader("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Content-Length");
69 if (query != null && query.contains("meta")) {
71 * LOG.debug("received post with uri="+req.getRequestURI()); String
72 * uri=req.getRequestURI().substring(BASEURI.length()); if(uri.startsWith("/"))
73 * uri=uri.substring(1);
75 File f = new File(HelpInfrastructureObject.KARAFHELPDIRECTORY, "meta.json");
77 LOG.debug("found local meta file");
78 try (BufferedReader rd = new BufferedReader(new FileReader(f));) {
79 String line = rd.readLine();
80 while (line != null) {
81 resp.getOutputStream().println(line);
85 } catch (IOException e) {
86 LOG.debug("Can not read meta file", e);
89 LOG.debug("start walking from path=" + basePath.toAbsolutePath().toString());
90 HelpInfrastructureObject o = null;
92 o = new HelpInfrastructureObject(this.basePath);
93 } catch (URISyntaxException e) {
94 LOG.debug("Can not relsolve URI. ", e);
96 resp.getOutputStream().println(o != null ? o.toString() : "");
98 resp.setHeader("Content-Type", "application/json");
100 LOG.debug("received get with uri=" + req.getRequestURI());
101 String uri = URLDecoder.decode(req.getRequestURI().substring(BASEURI.length()), "UTF-8");
102 if (uri.startsWith("/")) {
103 uri = uri.substring(1);
105 Path p = basePath.resolve(uri);
107 if (f.isFile() && f.exists()) {
108 LOG.debug("found file for request");
109 if (this.isTextFile(f)) {
110 resp.setHeader("Content-Type", "application/text");
111 resp.setHeader("charset", "utf-8");
112 } else if (this.isImageFile(f)) {
113 resp.setHeader("Content-Type", "image/*");
114 } else if (this.ispdf(f)) {
115 resp.setHeader("Content-Type", "application/pdf");
117 LOG.debug("file is not allowed to deliver");
121 LOG.debug("delivering file");
122 OutputStream out = resp.getOutputStream();
123 String version = null;
124 if (REDIRECT_LINKS) {
125 version = getVersionFromRequestedUri(uri);
127 if (this.isTextFile(f) && REDIRECT_LINKS && version != null) {
129 "(!?\\[[^\\]]*?\\])\\(((?:(?!http|www\\.|\\#|\\.com|\\.net|\\.info|\\.org|\\.svg|\\.png|\\.jpg|\\.gif|\\.jpeg|\\.pdf).)*?)\\)";
130 final Pattern pattern = Pattern.compile(regex);
133 try (BufferedReader br = new BufferedReader(new FileReader(f))) {
134 line = br.readLine();
135 while (line != null) {
136 // check line for internal link
137 matcher = pattern.matcher(line);
138 if (matcher.find()) {
139 // extend link with specific version
140 line = line.replace(matcher.group(2),
141 "../" + matcher.group(2) + version + "/README.md");
143 out.write((line + "\n").getBytes());
144 line = br.readLine();
153 try (FileInputStream in = new FileInputStream(f)) {
155 byte[] buffer = new byte[1024];
157 while ((len = in.read(buffer)) != -1) {
158 out.write(buffer, 0, len);
166 LOG.debug("found not file for request");
173 * Extract version from URI string
174 * @param uri = "help/folder1/folder2/version/README.md"
175 * @return version as a string
177 private static String getVersionFromRequestedUri(String uri) {
181 int lastidx = uri.lastIndexOf("/");
185 int slastidx = uri.lastIndexOf("/", lastidx - 1);
189 return uri.substring(slastidx + 1, lastidx);
193 private boolean ispdf(File f) {
194 return f != null ? this.ispdf(f.getName()) : false;
197 private boolean ispdf(String name) {
198 return name != null ? name.toLowerCase().endsWith("pdf") : false;
201 private boolean isImageFile(File f) {
202 return f != null ? this.isImageFile(f.getName()) : false;
205 private boolean isImageFile(String name) {
208 ? name.toLowerCase().endsWith("png") || name.toLowerCase().endsWith("jpg")
209 || name.toLowerCase().endsWith("jpeg") || name.toLowerCase().endsWith("svg")
210 || name.toLowerCase().endsWith("eps")
214 private boolean isTextFile(File f) {
215 return f != null ? this.isTextFile(f.getName()) : false;
219 private boolean isTextFile(String name) {
221 ? name.toLowerCase().endsWith("md") || name.toLowerCase().endsWith("txt")
222 || name.toLowerCase().endsWith("html") || name.toLowerCase().endsWith("htm")
223 || name.toLowerCase().endsWith("js") || name.toLowerCase().endsWith("css")
228 public void close() throws Exception {}