From bc9f6a12a3bd068f1b9f781539c41d8d86b7e409 Mon Sep 17 00:00:00 2001
From: ulrich <not disclosed>
Date: Thu, 28 Dec 2017 16:21:19 +0000
Subject: [PATCH] Generischen Filtermechanismus zur Veraenderung von Server-Antworten hinzugefuegt.

---
 /dev/null                                             |   94 -------------
 src/logging.properties                                |    4 
 src/de/uhilger/wbx/web/GenericResponseWrapper.java    |   69 +++++++++
 src/de/uhilger/wbx/web/MyGenericFilter.java           |   48 ++++++
 src/de/uhilger/wbx/web/ViewServlet.java               |   46 +++++-
 src/de/uhilger/wbx/web/FilterServletOutputStream.java |   49 +++++++
 src/de/uhilger/wbx/web/PrePostFilter.java             |   71 ++++++++++
 7 files changed, 277 insertions(+), 104 deletions(-)

diff --git a/src/de/uhilger/wbx/web/CustomResponseWrapper.java b/src/de/uhilger/wbx/web/CustomResponseWrapper.java
deleted file mode 100644
index bc765c3..0000000
--- a/src/de/uhilger/wbx/web/CustomResponseWrapper.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
-    WebBox - Dein Server.
-    Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
-
-    This program is free software: you can redistribute it and/or modify
-    it under the terms of the GNU Affero General Public License as
-    published by the Free Software Foundation, either version 3 of the
-    License, or (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU Affero General Public License for more details.
-
-    You should have received a copy of the GNU Affero General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-package de.uhilger.wbx.web;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
-
-/**
- * Die Klasse CustomResponseWrapper faengt den Inhalt einer HttpServletResponse
- * in einem StringWriter auf. Dieser kann mit der Methode getResponseContent 
- * gelesen werden.
- *
- * @author ulrich
- */
-public class CustomResponseWrapper extends HttpServletResponseWrapper {
-
-  private StringWriter stringWriter;
-  private boolean isOutputStreamCalled;
-
-  public CustomResponseWrapper(HttpServletResponse response) {
-    super(response);
-  }
-
-  @Override
-  public ServletOutputStream getOutputStream() throws IOException {
-    if (this.stringWriter != null) {
-      throw new IllegalStateException("The getWriter() is already called.");
-    }
-    isOutputStreamCalled = true;
-    return super.getOutputStream();
-  }
-
-  @Override
-  public PrintWriter getWriter() throws IOException {
-    if (isOutputStreamCalled) {
-      throw new IllegalStateException("The getOutputStream() is already called.");
-    }
-
-    this.stringWriter = new StringWriter();
-
-    return new PrintWriter(this.stringWriter);
-  }
-
-  public String getResponseContent() {
-    if (this.stringWriter != null) {
-      return this.stringWriter.toString();
-    }
-    return "";
-  }
-
-}
diff --git a/src/de/uhilger/wbx/web/FilterServletOutputStream.java b/src/de/uhilger/wbx/web/FilterServletOutputStream.java
new file mode 100644
index 0000000..b4e450e
--- /dev/null
+++ b/src/de/uhilger/wbx/web/FilterServletOutputStream.java
@@ -0,0 +1,49 @@
+/*
+    WebBox - Dein Server.
+    Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as
+    published by the Free Software Foundation, either version 3 of the
+    License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package de.uhilger.wbx.web;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import javax.servlet.ServletOutputStream;
+
+/**
+ *
+ * @author ulrich
+ */
+public class FilterServletOutputStream extends ServletOutputStream {
+ 
+  private DataOutputStream stream; 
+ 
+  public FilterServletOutputStream(OutputStream output) { 
+    stream = new DataOutputStream(output); 
+  }
+ 
+  public void write(int b) throws IOException  { 
+    stream.write(b); 
+  }
+ 
+  public void write(byte[] b) throws IOException  { 
+    stream.write(b); 
+  }
+ 
+  public void write(byte[] b, int off, int len) throws IOException  { 
+    stream.write(b,off,len); 
+  } 
+ 
+}
\ No newline at end of file
diff --git a/src/de/uhilger/wbx/web/GenericResponseWrapper.java b/src/de/uhilger/wbx/web/GenericResponseWrapper.java
new file mode 100644
index 0000000..99f6503
--- /dev/null
+++ b/src/de/uhilger/wbx/web/GenericResponseWrapper.java
@@ -0,0 +1,69 @@
+/*
+    WebBox - Dein Server.
+    Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as
+    published by the Free Software Foundation, either version 3 of the
+    License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package de.uhilger.wbx.web;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintWriter;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletResponseWrapper;
+
+/**
+ *
+ * @author ulrich
+ */
+public class GenericResponseWrapper extends HttpServletResponseWrapper { 
+  private ByteArrayOutputStream output;
+  private int contentLength;
+  private String contentType;
+ 
+  public GenericResponseWrapper(HttpServletResponse response) { 
+    super(response);
+    output=new ByteArrayOutputStream();
+  } 
+ 
+  public byte[] getData() { 
+    return output.toByteArray(); 
+  } 
+ 
+  public ServletOutputStream getOutputStream() { 
+    return new FilterServletOutputStream(output); 
+  } 
+  
+  public PrintWriter getWriter() { 
+    return new PrintWriter(getOutputStream(),true); 
+  } 
+ 
+  public void setContentLength(int length) { 
+    this.contentLength = length;
+    super.setContentLength(length); 
+  } 
+ 
+  public int getContentLength() { 
+    return contentLength; 
+  } 
+ 
+  public void setContentType(String type) { 
+    this.contentType = type;
+    super.setContentType(type); 
+  } 
+ 
+  public String getContentType() { 
+    return contentType; 
+  } 
+} 
\ No newline at end of file
diff --git a/src/de/uhilger/wbx/web/MarkdownServlet.java b/src/de/uhilger/wbx/web/MarkdownServlet.java
deleted file mode 100644
index 46082d8..0000000
--- a/src/de/uhilger/wbx/web/MarkdownServlet.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
-    WebBox - Dein Server.
-    Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
-
-    This program is free software: you can redistribute it and/or modify
-    it under the terms of the GNU Affero General Public License as
-    published by the Free Software Foundation, either version 3 of the
-    License, or (at your option) any later version.
-
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU Affero General Public License for more details.
-
-    You should have received a copy of the GNU Affero General Public License
-    along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-package de.uhilger.wbx.web;
-
-import java.io.IOException;
-import javax.servlet.ServletException;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import org.markdownj.MarkdownProcessor;
-
-/**
- *
- * @author ulrich
- */
-public class MarkdownServlet extends WbxServlet {
-  
-  
-  @Override
-  protected void seiteAusgeben(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
-    
-    CustomResponseWrapper wrapper = new CustomResponseWrapper(response);
-    super.doGet(request, wrapper);
-    String responseContent = wrapper.getResponseContent();
-    ServletOutputStream out = response.getOutputStream();
-    MarkdownProcessor p = new MarkdownProcessor();
-    out.print(p.markdown(responseContent));
-  }
-  
-}
diff --git a/src/de/uhilger/wbx/web/MyGenericFilter.java b/src/de/uhilger/wbx/web/MyGenericFilter.java
new file mode 100644
index 0000000..34b2c1e
--- /dev/null
+++ b/src/de/uhilger/wbx/web/MyGenericFilter.java
@@ -0,0 +1,48 @@
+/*
+    WebBox - Dein Server.
+    Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as
+    published by the Free Software Foundation, either version 3 of the
+    License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package de.uhilger.wbx.web;
+
+import java.util.logging.Logger;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ *
+ * @author ulrich
+ */
+public class MyGenericFilter implements javax.servlet.Filter {
+  private static final Logger logger = Logger.getLogger(MyGenericFilter.class.getName());
+  public FilterConfig filterConfig;
+ 
+  public void doFilter(final ServletRequest request,
+                       final ServletResponse response,
+                       FilterChain chain)
+      throws java.io.IOException, javax.servlet.ServletException { 
+    chain.doFilter(request,response);
+  } 
+ 
+  public void init(final FilterConfig filterConfig) {
+    this.filterConfig = filterConfig;
+    logger.info("   initialisiert.");
+  } 
+ 
+  public void destroy() {
+  }
+}
\ No newline at end of file
diff --git a/src/de/uhilger/wbx/web/PrePostFilter.java b/src/de/uhilger/wbx/web/PrePostFilter.java
new file mode 100644
index 0000000..bb06f39
--- /dev/null
+++ b/src/de/uhilger/wbx/web/PrePostFilter.java
@@ -0,0 +1,71 @@
+/*
+    WebBox - Dein Server.
+    Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as
+    published by the Free Software Foundation, either version 3 of the
+    License, or (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+package de.uhilger.wbx.web;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.logging.Logger;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * Dieser Filter ist dem Beispiel auf 
+ * http://otndnld.oracle.co.jp/document/products/as10g/101300/B25221_03/web.1013/b14426/filters.htm#BCFIAAAH
+ * entnommen und kann zum Testen von Filter-Konfigurationen oder als Ausgangsbasis 
+ * fuer komplexere Filter-Funktionen verwendet werden.
+ * 
+ * Das Beispiel umschliesst eine beliebige Antwort vom Server mit 
+ * <HR>PRE</HR> <HR>POST</HR>
+ * 
+ * @author ulrich
+ */
+public class PrePostFilter extends MyGenericFilter { 
+  
+  private static final Logger logger = Logger.getLogger(PrePostFilter.class.getName());
+ 
+  public void doFilter(final ServletRequest request,
+                       final ServletResponse response,
+                       FilterChain chain)
+       throws IOException, ServletException { 
+  HttpServletRequest hr = (HttpServletRequest) request;
+  logger.info("requestURL: " + hr.getRequestURL().toString());
+  logger.info("ContextPath: " + hr.getContextPath());
+  logger.info("ServletPath: " + hr.getServletPath());
+  logger.info("PathInfo: " + hr.getPathInfo());
+  OutputStream out = response.getOutputStream();
+  out.write(new String("<HR>PRE<HR>").getBytes());
+  GenericResponseWrapper wrapper = 
+         new GenericResponseWrapper((HttpServletResponse) response); 
+  chain.doFilter(request,wrapper);
+  out.write(wrapper.getData());
+  out.write(new String("<HR>POST<HR>").getBytes());
+  out.close(); 
+  } 
+  
+  
+  /*
+  
+  MarkdownProcessor p = new MarkdownProcessor();
+    response.getWriter().write(p.markdown(responseContent));
+  
+  */
+} 
\ No newline at end of file
diff --git a/src/de/uhilger/wbx/web/ViewServlet.java b/src/de/uhilger/wbx/web/ViewServlet.java
index 4b3119c..76e1a04 100644
--- a/src/de/uhilger/wbx/web/ViewServlet.java
+++ b/src/de/uhilger/wbx/web/ViewServlet.java
@@ -18,11 +18,14 @@
 package de.uhilger.wbx.web;
 
 import java.io.IOException;
+import java.security.Principal;
+import java.util.logging.Level;
 import java.util.logging.Logger;
 import javax.servlet.ServletException;
 import javax.servlet.ServletOutputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import org.apache.catalina.servlets.DefaultServlet;
 
 /**
  * Das ViewServlet f&uuml;gt dem DefaultServlet von Tomcat 
@@ -33,12 +36,13 @@
  * 
  * TODO: Stylesheets dynamisch einbinden
  */
-public class ViewServlet extends WbxServlet {
+public class ViewServlet extends DefaultServlet {
   
   private static final Logger logger = Logger.getLogger(ViewServlet.class.getName());
-  //private static final String HOME_CTX = "/home";
+  private static final String HOME_CTX = "/home";
 
-  protected void seiteAusgeben(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
+
+  private void seiteAusgeben(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
     ServletOutputStream out = response.getOutputStream();
     printHeader(out);
     super.doGet(request, response);
@@ -60,8 +64,35 @@
     out.print("</body></html>");
   }
   
-  /*
-  private String getUrlUser(HttpServletRequest request, String userName) throws IOException {
+  /**
+   * Handles the HTTP <code>GET</code> method.
+   *
+   * @param request servlet request
+   * @param response servlet response
+   * @throws ServletException if a servlet-specific error occurs
+   * @throws IOException if an I/O error occurs
+   */
+  @Override
+  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
+    String contextPath = request.getContextPath();
+    if(HOME_CTX.equals(contextPath)) {
+      String userName = getUserName(request);
+      if (userName != null) {
+        String urlUser = getUrlUser(request, userName);
+        if(userName.equals(urlUser)) {
+          seiteAusgeben(request, response);
+        } else {
+          logger.fine("Wrong user.");
+        }
+      } else {
+        logger.fine("Missing login.");
+      }
+    } else {
+      seiteAusgeben(request, response);
+    }
+  }
+  
+  protected String getUrlUser(HttpServletRequest request, String userName) {
     String result = "";
     String requestUrlStr = request.getRequestURL().toString();
     String contextPath = request.getContextPath();
@@ -79,7 +110,7 @@
     return result;
   }
   
-  private String getUserName(HttpServletRequest hr) {
+  protected String getUserName(HttpServletRequest hr) {
     String userName = null;
     Object p = hr.getUserPrincipal();
     if (p instanceof Principal) {
@@ -87,8 +118,7 @@
     }
     return userName;
   }
-  */
-
+  
   /**
    * Returns a short description of the servlet.
    *
diff --git a/src/de/uhilger/wbx/web/WbxServlet.java b/src/de/uhilger/wbx/web/WbxServlet.java
deleted file mode 100644
index fa7f661..0000000
--- a/src/de/uhilger/wbx/web/WbxServlet.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package de.uhilger.wbx.web;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import org.apache.catalina.servlets.DefaultServlet;
-
-/**
- * Das WbxServlet prueft fuer alle HTTP GET Anfragen den Conetxt Path. Wenn 
- * er /home enthaelt, muss der angemeldete Benutzer mit dem Benutzernamen 
- * im Pfad uebereinstimmen. Stimmt er nicht ueberein oder ist kein Nutzer 
- * angemeldet, wird ein Fehler ausgegeben.
- * 
- * Alle anderen Pfade als /home werden ohne Anmeldung ausgegeben.
- * 
- * Die Ausgabe des Inhalts wird auf die abstrakte Methode seiteAusgeben 
- * umgeleitet. Serlvets, die von WbxServlet abgeleitet werden, koennen 
- * die Methode seiteAusgeben so implementieren, dass sie z.B. den 
- * Inhalt der Ausgabe nach Wunsch veraendern.
- * 
- * @author ulrich
- */
-public abstract class WbxServlet extends DefaultServlet {
-  
-  protected static final Logger logger = Logger.getLogger(WbxServlet.class.getName());
-  protected static final String HOME_CTX = "/home";
-  
-  /**
-   * Handles the HTTP <code>GET</code> method.
-   *
-   * @param request servlet request
-   * @param response servlet response
-   * @throws ServletException if a servlet-specific error occurs
-   * @throws IOException if an I/O error occurs
-   */
-  @Override
-  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
-    String contextPath = request.getContextPath();
-    if(HOME_CTX.equals(contextPath)) {
-      String userName = getUserName(request);
-      if (userName != null) {
-        String urlUser = getUrlUser(request, userName);
-        if(userName.equals(urlUser)) {
-          seiteAusgeben(request, response);
-        } else {
-          logger.fine("Wrong user.");
-        }
-      } else {
-        logger.fine("Missing login.");
-      }
-    } else {
-      seiteAusgeben(request, response);
-    }
-  }
-  
-  protected String getUrlUser(HttpServletRequest request, String userName) {
-    String result = "";
-    String requestUrlStr = request.getRequestURL().toString();
-    String contextPath = request.getContextPath();
-    if(contextPath != null && requestUrlStr != null && userName != null) {
-      int start = requestUrlStr.indexOf(contextPath);
-      start += contextPath.length();
-      start++;
-      int end = start + userName.length();
-      try {
-        result = requestUrlStr.substring(start, end);
-      } catch(Exception ex) {
-        logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
-      }
-    }
-    return result;
-  }
-  
-  protected String getUserName(HttpServletRequest hr) {
-    String userName = null;
-    Object p = hr.getUserPrincipal();
-    if (p instanceof Principal) {
-      userName = ((Principal) p).getName();
-    }
-    return userName;
-  }
-  
-  protected abstract void seiteAusgeben(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
-
-}
diff --git a/src/logging.properties b/src/logging.properties
index e64a0a7..fd8857a 100644
--- a/src/logging.properties
+++ b/src/logging.properties
@@ -27,7 +27,7 @@
 # Note that the ConsoleHandler also has a separate level
 # setting to limit messages printed to the console.
 # .level= FINE
-.level = OFF
+.level = NONE
 
 ############################################################
 # Handler specific properties.
@@ -65,4 +65,4 @@
 # messages:
 # com.xyz.foo.level = SEVERE
 de.uhilger.wbx.handlers = java.util.logging.ConsoleHandler
-de.uhilger.wbx.level = FINER
\ No newline at end of file
+de.uhilger.wbx.level = INFO
\ No newline at end of file

--
Gitblit v1.9.3