1 /*******************************************************************************
2 * ============LICENSE_START==================================================
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
11 * * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
24 package org.onap.dmaap.datarouter.subscriber;
26 import jakarta.servlet.http.HttpServlet;
27 import jakarta.servlet.http.HttpServletRequest;
28 import jakarta.servlet.http.HttpServletResponse;
30 import java.io.FileOutputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.io.PrintWriter;
35 import java.net.URLEncoder;
36 import java.nio.charset.StandardCharsets;
37 import java.nio.file.Files;
38 import java.nio.file.Paths;
39 import java.nio.file.StandardCopyOption;
40 import org.apache.commons.codec.binary.Base64;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
44 public class SampleSubscriberServlet extends HttpServlet {
46 private final Logger logger = LoggerFactory.getLogger(SampleSubscriberServlet.class);
48 private static String outputDirectory;
49 private static String basicAuth;
52 * Configure the SampleSubscriberServlet.
55 * <li>Login - The login expected in the Authorization header (default "LOGIN").
56 * <li>Password - The password expected in the Authorization header (default "PASSWORD").
57 * <li>outputDirectory - The directory where files are placed (default
58 * "/opt/app/subscriber/delivery").
63 SubscriberProps props = SubscriberProps.getInstance();
64 String login = props.getValue("org.onap.dmaap.datarouter.subscriber.auth.user", "LOGIN");
65 String password = props.getValue("org.onap.dmaap.datarouter.subscriber.auth.password", "PASSWORD");
67 props.getValue("org.onap.dmaap.datarouter.subscriber.delivery.dir", "/opt/app/subscriber/delivery");
69 Files.createDirectory(Paths.get(outputDirectory));
70 } catch (IOException e) {
71 logger.error("SubServlet: Failed to create delivery dir: " + e.getMessage(), e);
73 basicAuth = "Basic " + Base64.encodeBase64String((login + ":" + password).getBytes());
77 protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
79 common(req, resp, false);
80 } catch (IOException e) {
81 logger.error("SampleSubServlet: Failed to doPut: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
86 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
88 common(req, resp, true);
89 } catch (IOException e) {
90 logger.error("SampleSubServlet: Failed to doDelete: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
95 * Process a PUT or DELETE request.
98 * <li>Verify that the request contains an Authorization header or else UNAUTHORIZED.
99 * <li>Verify that the Authorization header matches the configured Login and Password or else
101 * <li>If the request is PUT, store the message body as a file in the configured outputDirectory
102 * directory protecting against evil characters in the received FileID. The file is created
103 * initially with its name prefixed with a ".", and once it is complete, it is renamed to
104 * remove the leading "." character.
105 * <li>If the request is DELETE, instead delete the file (if it exists) from the configured
106 * outputDirectory directory.
107 * <li>Respond with NO_CONTENT.
110 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete) throws IOException {
111 String authHeader = req.getHeader("Authorization");
112 if (authHeader == null) {
113 logger.info("SampleSubServlet: Rejecting request with no Authorization header from " + req.getRemoteAddr()
114 + ": " + req.getPathInfo());
115 resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
118 if (!basicAuth.equals(authHeader)) {
119 logger.error("SampleSubServlet: Rejecting request with incorrect Authorization header from "
120 + req.getRemoteAddr() + ": " + req.getPathInfo());
121 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
124 String fileid = req.getPathInfo();
125 fileid = fileid.substring(fileid.lastIndexOf('/') + 1);
126 String queryString = req.getQueryString();
127 if (queryString != null) {
128 fileid = fileid + "?" + queryString;
130 String publishid = req.getHeader("X-DMAAP-DR-PUBLISH-ID");
131 String filename = URLEncoder.encode(fileid, StandardCharsets.UTF_8).replaceAll("^\\.", "%2E").replaceAll("\\*", "%2A");
132 String fullPath = outputDirectory + "/" + filename;
133 String tmpPath = outputDirectory + "/." + filename;
134 String fullMetaDataPath = outputDirectory + "/" + filename + ".M";
135 String tmpMetaDataPath = outputDirectory + "/." + filename + ".M";
138 Files.deleteIfExists(Paths.get(fullPath));
139 Files.deleteIfExists(Paths.get(fullMetaDataPath));
140 logger.info("SampleSubServlet: Received delete for file id " + fileid + " from " + req.getRemoteAddr()
141 + " publish id " + publishid + " as " + fullPath);
143 new File(tmpPath).createNewFile();
144 new File(tmpMetaDataPath).createNewFile();
145 try (InputStream is = req.getInputStream(); OutputStream os = new FileOutputStream(tmpPath)) {
146 byte[] buf = new byte[65536];
148 while ((bufferSize = is.read(buf)) > 0) {
149 os.write(buf, 0, bufferSize);
152 Files.move(Paths.get(tmpPath), Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
153 try (PrintWriter writer = new PrintWriter(new FileOutputStream(tmpMetaDataPath))) {
154 String metaData = req.getHeader("X-DMAAP-DR-META");
155 writer.print(metaData);
157 Files.move(Paths.get(tmpMetaDataPath), Paths.get(fullMetaDataPath),
158 StandardCopyOption.REPLACE_EXISTING);
160 "SampleSubServlet: Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id "
161 + publishid + " as " + fullPath);
162 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
164 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
165 } catch (IOException ioe) {
166 Files.deleteIfExists(Paths.get(tmpPath));
167 Files.deleteIfExists(Paths.get(tmpMetaDataPath));
168 logger.error("SampleSubServlet: Failed to process file " + fullPath + " from " + req.getRemoteAddr() + ": "
169 + req.getPathInfo());