Remaining checkstyle changes
[dmaap/datarouter.git] / datarouter-subscriber / src / main / java / org / onap / dmaap / datarouter / subscriber / SampleSubscriberServlet.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 java.io.File;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.OutputStream;
31 import java.io.PrintWriter;
32 import java.net.URLEncoder;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.nio.file.StandardCopyOption;
36 import javax.servlet.http.HttpServlet;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
39 import org.apache.commons.codec.binary.Base64;
40 import org.apache.log4j.Logger;
41
42
43 public class SampleSubscriberServlet extends HttpServlet {
44
45     private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.subscriber.SampleSubscriberServlet");
46     private static String outputDirectory;
47     private static String basicAuth;
48
49     /**
50      * Configure the SampleSubscriberServlet.
51      *
52      * <ul>
53      * <li>Login - The login expected in the Authorization header (default "LOGIN").
54      * <li>Password - The password expected in the Authorization header (default "PASSWORD").
55      * <li>outputDirectory - The directory where files are placed (default
56      * "/opt/app/subscriber/delivery").
57      * </ul>
58      */
59     @Override
60     public void init() {
61         SubscriberProps props = SubscriberProps.getInstance();
62         String login = props.getValue("org.onap.dmaap.datarouter.subscriber.auth.user", "LOGIN");
63         String password = props.getValue("org.onap.dmaap.datarouter.subscriber.auth.password", "PASSWORD");
64         outputDirectory =
65                 props.getValue("org.onap.dmaap.datarouter.subscriber.delivery.dir", "/opt/app/subscriber/delivery");
66         try {
67             Files.createDirectory(Paths.get(outputDirectory));
68         } catch (IOException e) {
69             logger.info("SubServlet: Failed to create delivery dir: " + e.getMessage(), e);
70         }
71         basicAuth = "Basic " + Base64.encodeBase64String((login + ":" + password).getBytes());
72     }
73
74     @Override
75     protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
76         try {
77             common(req, resp, false);
78         } catch (IOException e) {
79             logger.info("SampleSubServlet: Failed to doPut: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
80         }
81     }
82
83     @Override
84     protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
85         try {
86             common(req, resp, true);
87         } catch (IOException e) {
88             logger.info("SampleSubServlet: Failed to doDelete: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
89         }
90     }
91
92     /**
93      * Process a PUT or DELETE request.
94      *
95      * <ol>
96      * <li>Verify that the request contains an Authorization header or else UNAUTHORIZED.
97      * <li>Verify that the Authorization header matches the configured Login and Password or else
98      * FORBIDDEN.
99      * <li>If the request is PUT, store the message body as a file in the configured outputDirectory
100      * directory protecting against evil characters in the received FileID. The file is created
101      * initially with its name prefixed with a ".", and once it is complete, it is renamed to
102      * remove the leading "." character.
103      * <li>If the request is DELETE, instead delete the file (if it exists) from the configured
104      * outputDirectory directory.
105      * <li>Respond with NO_CONTENT.
106      * </ol>
107      */
108     private void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete) throws IOException {
109         String authHeader = req.getHeader("Authorization");
110         if (authHeader == null) {
111             logger.info("SampleSubServlet: Rejecting request with no Authorization header from " + req.getRemoteAddr()
112                                 + ": " + req.getPathInfo());
113             resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
114             return;
115         }
116         if (!basicAuth.equals(authHeader)) {
117             logger.info("SampleSubServlet: Rejecting request with incorrect Authorization header from "
118                                 + req.getRemoteAddr() + ": " + req.getPathInfo());
119             resp.sendError(HttpServletResponse.SC_FORBIDDEN);
120             return;
121         }
122         String fileid = req.getPathInfo();
123         fileid = fileid.substring(fileid.lastIndexOf('/') + 1);
124         String queryString = req.getQueryString();
125         if (queryString != null) {
126             fileid = fileid + "?" + queryString;
127         }
128         String publishid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
129         String filename = URLEncoder.encode(fileid, "UTF-8").replaceAll("^\\.", "%2E").replaceAll("\\*", "%2A");
130         String fullPath = outputDirectory + "/" + filename;
131         String tmpPath = outputDirectory + "/." + filename;
132         String fullMetaDataPath = outputDirectory + "/" + filename + ".M";
133         String tmpMetaDataPath = outputDirectory + "/." + filename + ".M";
134         try {
135             if (isdelete) {
136                 Files.deleteIfExists(Paths.get(fullPath));
137                 Files.deleteIfExists(Paths.get(fullMetaDataPath));
138                 logger.info("SampleSubServlet: Received delete for file id " + fileid + " from " + req.getRemoteAddr()
139                                     + " publish id " + publishid + " as " + fullPath);
140             } else {
141                 new File(tmpPath).createNewFile();
142                 new File(tmpMetaDataPath).createNewFile();
143                 try (InputStream is = req.getInputStream(); OutputStream os = new FileOutputStream(tmpPath)) {
144                     byte[] buf = new byte[65536];
145                     int bufferSize;
146                     while ((bufferSize = is.read(buf)) > 0) {
147                         os.write(buf, 0, bufferSize);
148                     }
149                 }
150                 Files.move(Paths.get(tmpPath), Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
151                 try (PrintWriter writer = new PrintWriter(new FileOutputStream(tmpMetaDataPath))) {
152                     String metaData = req.getHeader("X-DMAAP-DR-META");
153                     writer.print(metaData);
154                 }
155                 Files.move(Paths.get(tmpMetaDataPath), Paths.get(fullMetaDataPath),
156                         StandardCopyOption.REPLACE_EXISTING);
157                 logger.info(
158                         "SampleSubServlet: Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id "
159                                 + publishid + " as " + fullPath);
160                 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
161             }
162             resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
163         } catch (IOException ioe) {
164             Files.deleteIfExists(Paths.get(tmpPath));
165             Files.deleteIfExists(Paths.get(tmpMetaDataPath));
166             logger.info("SampleSubServlet: Failed to process file " + fullPath + " from " + req.getRemoteAddr() + ": "
167                                 + req.getPathInfo());
168             throw ioe;
169         }
170     }
171 }