Add subscriber docker image for client testing
[dmaap/datarouter.git] / datarouter-subscriber / src / main / java / org / onap / dmaap / datarouter / subscriber / SubscriberServlet.java
@@ -7,9 +7,9 @@
  * * Licensed under the Apache License, Version 2.0 (the "License");
  * * you may not use this file except in compliance with the License.
  * * You may obtain a copy of the License at
- * * 
+ * *
  *  *      http://www.apache.org/licenses/LICENSE-2.0
- * * 
+ * *
  *  * Unless required by applicable law or agreed to in writing, software
  * * distributed under the License is distributed on an "AS IS" BASIS,
  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * *
  ******************************************************************************/
 
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URLEncoder;
+package org.onap.dmaap.datarouter.subscriber;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
 
 import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.net.URLEncoder;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.PosixFilePermissions;
 
-import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
+import static org.onap.dmaap.datarouter.subscriber.Subscriber.props;
 
-/**
- *     Example stand alone subscriber servlet with Authorization header checking
- */
-public class SubscriberServlet extends HttpServlet     {
-       private static Logger logger = Logger.getLogger("com.att.datarouter.pubsub.ssasubscribe.SubscriberServlet");
-       private String Login = "LOGIN";
-       private String Password = "PASSWORD";
-       private String OutputDirectory = "/root/sub/received";
+public class SubscriberServlet extends HttpServlet {
 
-       private String auth;
+       private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.subscriber.SubscriberServlet");
+       private String outputDirectory;
+       private String basicAuth;
 
-       private static String gp(ServletConfig config, String param, String deflt) {
-               param = config.getInitParameter(param);
-               if (param == null || param.length() == 0) {
-                       param = deflt;
-               }
-               return(param);
-       }
        /**
         *      Configure this subscriberservlet.  Configuration parameters from config.getInitParameter() are:
         *      <ul>
         *      <li>Login - The login expected in the Authorization header (default "LOGIN").
         *      <li>Password - The password expected in the Authorization header (default "PASSWORD").
-        *      <li>OutputDirectory - The directory where files are placed (default "received").
+        *      <li>outputDirectory - The directory where files are placed (default "tmp").
         *      </ul>
         */
-       public void init(ServletConfig config) throws ServletException {
-               Login = gp(config, "Login", Login);
-               Password = gp(config, "Password", Password);
-               OutputDirectory = gp(config, "OutputDirectory", OutputDirectory);
-               (new File(OutputDirectory)).mkdirs();
-               auth = "Basic " + Base64.encodeBase64String((Login + ":" + Password).getBytes());
+       @Override
+    public void init(ServletConfig config) {
+        String login = props.getProperty("org.onap.dmaap.datarouter.subscriber.auth.user", "LOGIN");
+               String password = props.getProperty("org.onap.dmaap.datarouter.subscriber.auth.password", "PASSWORD");
+        outputDirectory = props.getProperty("org.onap.dmaap.datarouter.subscriber.delivery.dir", "/tmp");
+        try {
+            Files.createDirectory(Paths.get(outputDirectory), PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx")));
+        } catch (IOException e) {
+            logger.info("SubServlet: Failed to create delivery dir: " + e.getMessage());
+            e.printStackTrace();
+        }
+               basicAuth = "Basic " + Base64.encodeBase64String((login + ":" + password).getBytes());
+       }
+
+       @Override
+       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+               File filesPath = new File(outputDirectory);
+               File[] filesArr = filesPath.listFiles();
+        assert filesArr != null;
+        for (File file: filesArr) {
+            try (BufferedReader in = new BufferedReader(new FileReader(file))) {
+                String line = in.readLine();
+                while (line != null) {
+                    line = in.readLine();
+                }
+            }
+               }
        }
        /**
         *      Invoke common(req, resp, false).
         */
-       protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-               common(req, resp, false);
-       }
+       @Override
+       protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
+        try {
+            common(req, resp, false);
+        } catch (IOException e) {
+            logger.info("SubServlet: Failed to doPut: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
+        }
+    }
        /**
         *      Invoke common(req, resp, true).
         */
-       protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-               common(req, resp, true);
-       }
+       @Override
+       protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
+        try {
+            common(req, resp, true);
+        } catch (IOException e) {
+            logger.info("SubServlet: Failed to doDelete: " + req.getRemoteAddr() + " : " + req.getPathInfo(), e);
+        }
+    }
        /**
         *      Process a PUT or DELETE request.
         *      <ol>
@@ -90,59 +111,57 @@ public class SubscriberServlet extends HttpServlet {
         *      <li>Verify that the Authorization header matches the configured
         *      Login and Password or else FORBIDDEN.
         *      <li>If the request is PUT, store the message body as a file
-        *      in the configured OutputDirectory directory protecting against
+        *      in the configured outputDirectory directory protecting against
         *      evil characters in the received FileID.  The file is created
         *      initially with its name prefixed with a ".", and once it is complete, it is
         *      renamed to remove the leading "." character.
-        *      <li>If the request is DELETE, instead delete the file (if it exists) from the configured OutputDirectory directory.
+        *      <li>If the request is DELETE, instead delete the file (if it exists) from the configured outputDirectory directory.
         *      <li>Respond with NO_CONTENT.
         *      </ol>
         */
-       protected void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete) throws ServletException, IOException {
-               String ah = req.getHeader("Authorization");
-               if (ah == null) {
+    private void common(HttpServletRequest req, HttpServletResponse resp, boolean isdelete) throws IOException {
+               String authHeader = req.getHeader("Authorization");
+               if (authHeader == null) {
                        logger.info("Rejecting request with no Authorization header from " + req.getRemoteAddr() + ": " + req.getPathInfo());
                        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                        return;
                }
-               if (!auth.equals(ah)) {
+               if (!basicAuth.equals(authHeader)) {
                        logger.info("Rejecting request with incorrect Authorization header from " + req.getRemoteAddr() + ": " + req.getPathInfo());
                        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                        return;
                }
                String fileid = req.getPathInfo();
                fileid = fileid.substring(fileid.lastIndexOf('/') + 1);
-               String qs = req.getQueryString();
-               if (qs != null) {
-                       fileid = fileid + "?" + qs;
+               String queryString = req.getQueryString();
+               if (queryString != null) {
+                       fileid = fileid + "?" + queryString;
                }
                String publishid = req.getHeader("X-ATT-DR-PUBLISH-ID");
                String filename = URLEncoder.encode(fileid, "UTF-8").replaceAll("^\\.", "%2E").replaceAll("\\*", "%2A");
-               String finalname = OutputDirectory + "/" + filename;
-               String tmpname = OutputDirectory + "/." + filename;
+               String fullPath = outputDirectory + "/" + filename;
+               String tmpPath = outputDirectory + "/." + filename;
                try {
                        if (isdelete) {
-                               (new File(finalname)).delete();
-                               logger.info("Received delete for file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + finalname);
+                           Files.deleteIfExists(Paths.get(fullPath));
+                               logger.info("Received delete for file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + fullPath);
                        } else {
-                               InputStream is = req.getInputStream();
-                               OutputStream os = new FileOutputStream(tmpname);
-                               byte[] buf = new byte[65536];
-                               int i;
-                               while ((i = is.read(buf)) > 0) {
-                                       os.write(buf, 0, i);
-                               }
-                               is.close();
-                               os.close();
-                               (new File(tmpname)).renameTo(new File(finalname));
-                               logger.info("Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + finalname);
+                new File(tmpPath).createNewFile();
+                try (InputStream is = req.getInputStream(); OutputStream os = new FileOutputStream(tmpPath)) {
+                    byte[] buf = new byte[65536];
+                    int i;
+                    while ((i = is.read(buf)) > 0) {
+                        os.write(buf, 0, i);
+                    }
+                }
+                Files.move(Paths.get(tmpPath), Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
+                               logger.info("Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + fullPath);
                                resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
-                               logger.info("Received file id " + fileid + " from " + req.getRemoteAddr() + " publish id " + publishid + " as " + finalname);
                        }
                        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
                } catch (IOException ioe) {
-                       (new File(tmpname)).delete();
-                       logger.info("Failure to save file " + finalname + " from " + req.getRemoteAddr() + ": " + req.getPathInfo(), ioe);
+            Files.deleteIfExists(Paths.get(tmpPath));
+                       logger.info("Failed to process file " + fullPath + " from " + req.getRemoteAddr() + ": " + req.getPathInfo());
                        throw ioe;
                }
        }