Merge "Fixed Sonar Blocker in StatisticsServlet"
[dmaap/datarouter.git] / datarouter-subscriber / src / main / java / org / onap / dmaap / datarouter / subscriber / SubscriberServlet.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24 package org.onap.dmaap.datarouter.subscriber;
25
26 import org.apache.commons.codec.binary.Base64;
27 import org.apache.log4j.Logger;
28
29 import javax.servlet.ServletConfig;
30 import javax.servlet.http.HttpServlet;
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33 import java.io.*;
34 import java.net.URLEncoder;
35 import java.nio.file.Files;
36 import java.nio.file.Paths;
37 import java.nio.file.StandardCopyOption;
38 import java.nio.file.attribute.PosixFilePermissions;
39
40 import static org.onap.dmaap.datarouter.subscriber.Subscriber.props;
41
42 public class SubscriberServlet extends HttpServlet {
43
44         private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.subscriber.SubscriberServlet");
45         private String outputDirectory;
46         private String basicAuth;
47
48         /**
49          *      Configure this subscriberservlet.  Configuration parameters from config.getInitParameter() are:
50          *      <ul>
51          *      <li>Login - The login expected in the Authorization header (default "LOGIN").
52          *      <li>Password - The password expected in the Authorization header (default "PASSWORD").
53          *      <li>outputDirectory - The directory where files are placed (default "tmp").
54          *      </ul>
55          */
56         @Override
57     public void init(ServletConfig config) {
58         String login = props.getProperty("org.onap.dmaap.datarouter.subscriber.auth.user", "LOGIN");
59                 String password = props.getProperty("org.onap.dmaap.datarouter.subscriber.auth.password", "PASSWORD");
60         outputDirectory = props.getProperty("org.onap.dmaap.datarouter.subscriber.delivery.dir", "/tmp");
61         try {
62             Files.createDirectory(Paths.get(outputDirectory), PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")));
63         } catch (IOException e) {
64             logger.info("SubServlet: Failed to create delivery dir: " + e.getMessage());
65             e.printStackTrace();
66         }
67                 basicAuth = "Basic " + Base64.encodeBase64String((login + ":" + password).getBytes());
68         }
69
70         @Override
71         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
72                 File filesPath = new File(outputDirectory);
73                 File[] filesArr = filesPath.listFiles();
74         assert filesArr != null;
75         for (File file: filesArr) {
76             try (BufferedReader in = new BufferedReader(new FileReader(file))) {
77                 String line = in.readLine();
78                 while (line != null) {
79                     line = in.readLine();
80                 }
81             }
82                 }
83         }
84         /**
85          *      Invoke common(req, resp, false).
86          */
87         @Override
88         protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
89         try {
90             common(req, resp, false);
91         } catch (IOException e) {
92             logger.info("SubServlet: Failed to doPut: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
93         }
94     }
95         /**
96          *      Invoke common(req, resp, true).
97          */
98         @Override
99         protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
100         try {
101             common(req, resp, true);
102         } catch (IOException e) {
103             logger.info("SubServlet: Failed to doDelete: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
104         }
105     }
106         /**
107          *      Process a PUT or DELETE request.
108          *      <ol>
109          *      <li>Verify that the request contains an Authorization header
110          *      or else UNAUTHORIZED.
111          *      <li>Verify that the Authorization header matches the configured
112          *      Login and Password or else FORBIDDEN.
113          *      <li>If the request is PUT, store the message body as a file
114          *      in the configured outputDirectory directory protecting against
115          *      evil characters in the received FileID.  The file is created
116          *      initially with its name prefixed with a ".", and once it is complete, it is
117          *      renamed to remove the leading "." character.
118          *      <li>If the request is DELETE, instead delete the file (if it exists) from the configured outputDirectory directory.
119          *      <li>Respond with NO_CONTENT.
120          *      </ol>
121          */
122     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete) throws IOException {
123                 String authHeader = req.getHeader("Authorization");
124                 if (authHeader == null) {
125                         logger.info("Rejecting request with no Authorization header from " + req.getRemoteAddr() + ": " + req.getPathInfo());
126                         resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
127                         return;
128                 }
129                 if (!basicAuth.equals(authHeader)) {
130                         logger.info("Rejecting request with incorrect Authorization header from " + req.getRemoteAddr() + ": " + req.getPathInfo());
131                         resp.sendError(HttpServletResponse.SC_FORBIDDEN);
132                         return;
133                 }
134                 String fileid = req.getPathInfo();
135                 fileid = fileid.substring(fileid.lastIndexOf('/') + 1);
136                 String queryString = req.getQueryString();
137                 if (queryString != null) {
138                         fileid = fileid + "?" + queryString;
139                 }
140                 String publishid = req.getHeader("X-ATT-DR-PUBLISH-ID");
141                 String filename = URLEncoder.encode(fileid, "UTF-8").replaceAll("^\\.", "%2E").replaceAll("\\*", "%2A");
142                 String fullPath = outputDirectory + "/" + filename;
143                 String tmpPath = outputDirectory + "/." + filename;
144                 try {
145                         if (isdelete) {
146                             Files.deleteIfExists(Paths.get(fullPath));
147                                 logger.info("Received delete for file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + fullPath);
148                         } else {
149                 new File(tmpPath).createNewFile();
150                 try (InputStream is = req.getInputStream(); OutputStream os = new FileOutputStream(tmpPath)) {
151                     byte[] buf = new byte[65536];
152                     int i;
153                     while ((i = is.read(buf)) > 0) {
154                         os.write(buf, 0, i);
155                     }
156                 }
157                 Files.move(Paths.get(tmpPath), Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
158                                 logger.info("Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + fullPath);
159                                 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
160                         }
161                         resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
162                 } catch (IOException ioe) {
163             Files.deleteIfExists(Paths.get(tmpPath));
164                         logger.info("Failed to process file " + fullPath + " from " + req.getRemoteAddr() + ": " + req.getPathInfo());
165                         throw ioe;
166                 }
167         }
168 }