You are viewing a plain text version of this content. The canonical link for it is here.
Posted to slide-dev@jakarta.apache.org by re...@locus.apache.org on 2000/11/22 07:22:39 UTC

cvs commit: jakarta-slide/src/manager/org/apache/slide/manager ManagerServlet.java

remm        00/11/21 22:22:39

  Added:       src/manager/org/apache/slide/manager ManagerServlet.java
  Log:
  - Move the manager servlet to src/manager
  
  Revision  Changes    Path
  1.1                  jakarta-slide/src/manager/org/apache/slide/manager/ManagerServlet.java
  
  Index: ManagerServlet.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-slide/src/manager/org/apache/slide/manager/ManagerServlet.java,v 1.1 2000/11/22 06:22:39 remm Exp $
   * $Revision: 1.1 $
   * $Date: 2000/11/22 06:22:39 $
   *
   * ====================================================================
   *
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 1999 The Apache Software Foundation.  All rights 
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer. 
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowlegement:  
   *       "This product includes software developed by the 
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written 
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Group.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */ 
  
  package org.apache.slide.manager;
  
  import java.io.*;
  import java.util.*;
  import java.security.Principal;
  import java.text.DateFormat;
  import java.text.SimpleDateFormat;
  import javax.servlet.*;
  import javax.servlet.http.*;
  import javax.xml.parsers.SAXParser;
  import javax.xml.parsers.SAXParserFactory;
  import org.xml.sax.*;
  import org.xml.sax.helpers.*;
  import org.apache.slide.webdav.method.*;
  import org.apache.slide.webdav.common.*;
  import org.apache.slide.authenticate.*;
  import org.apache.slide.structure.*;
  import org.apache.slide.common.*;
  import org.apache.slide.security.*;
  import org.apache.slide.util.conf.*;
  import org.apache.slide.authenticate.SecurityToken;
  
  /**
   * Manager Servlet.
   * 
   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
   */
  public class ManagerServlet extends HttpServlet {
      
      
      // -------------------------------------------------------------- Constants
      
      
      /**
       * HTTP Date format pattern (RFC 2068, 822, 1123).
       */
      public static final String DATE_FORMAT = "EEE, d MMM yyyy kk:mm:ss z";
      
      
      /**
       * Date formatter.
       */
      protected static final DateFormat formatter = 
          new SimpleDateFormat(DATE_FORMAT);
      
      
      // ----------------------------------------------------- Instance Variables
      
      
      /**
       * ACL editor page (if any).
       */
      protected String permissionEditor = null;
      
      
      /**
       * User editor page (if any).
       */
      protected String userEditor = null;
      
      
      // -------------------------------------------------------- Private Methods
      
      
      /**
       * Show HTTP header information.
       */
      private void showRequestInfo(HttpServletRequest req) {
  	
  	System.out.println();
  	System.out.println("SlideDAV Request Info");
  	System.out.println();
  	
  	// Show generic info
  	System.out.println("Encoding : " + req.getCharacterEncoding());
  	System.out.println("Length : " + req.getContentLength());
  	System.out.println("Type : " + req.getContentType());
  	
  	System.out.println();
  	System.out.println("Parameters");
  	
  	Enumeration parameters = req.getParameterNames();
  	
  	while (parameters.hasMoreElements()) {
  	    String paramName = (String) parameters.nextElement();
  	    String[] values = req.getParameterValues(paramName);
  	    System.out.print(paramName + " : ");
  	    for (int i = 0; i < values.length; i++) {
  		System.out.print(values[i] + ", ");
  	    }
  	    System.out.println();
  	}
  	
  	System.out.println();
  	
  	System.out.println("Protocol : " + req.getProtocol());
  	System.out.println("Address : " + req.getRemoteAddr());
  	System.out.println("Host : " + req.getRemoteHost());
  	System.out.println("Scheme : " + req.getScheme());
  	System.out.println("Server Name : " + req.getServerName());
  	System.out.println("Server Port : " + req.getServerPort());
  	
  	System.out.println();
  	System.out.println("Attributes");
  	
  	Enumeration attributes = req.getAttributeNames();
  	
  	while (attributes.hasMoreElements()) {
  	    String attributeName = (String) attributes.nextElement();
  	    System.out.print(attributeName + " : ");
  	    System.out.println(req.getAttribute(attributeName).toString());
  	}
  	
  	System.out.println();
  	
  	// Show HTTP info
  	System.out.println();
  	System.out.println("HTTP Header Info");
  	System.out.println();
  	
  	System.out.println("Authentication Type : " + req.getAuthType());
  	System.out.println("HTTP Method : " + req.getMethod());
  	System.out.println("Path Info : " + req.getPathInfo());
  	System.out.println("Path translated : " + req.getPathTranslated());
  	System.out.println("Query string : " + req.getQueryString());
  	System.out.println("Remote user : " + req.getRemoteUser());
  	System.out.println("Requested session id : " 
                             + req.getRequestedSessionId());
  	System.out.println("Request URI : " + req.getRequestURI());
  	System.out.println("Context path : " + req.getContextPath());
          System.out.println("Servlet path : " + req.getServletPath());
          System.out.println("User principal : " + req.getUserPrincipal());
          
  	
  	System.out.println();
  	System.out.println("Headers : ");
  	
  	Enumeration headers = req.getHeaderNames();
  	
  	while (headers.hasMoreElements()) {
  	    String headerName = (String) headers.nextElement();
  	    System.out.print(headerName + " : ");
  	    System.out.println(req.getHeader(headerName));
  	}
  	
  	// Show session info
  	HttpSession session = req.getSession(false);
          
  	System.out.println();
  	System.out.println("End Request Info");
  	System.out.println();
  	System.out.println();
  	
      }
      
      
      // -------------------------------------------------------- Servlet Methods
      
      
      /**
       * Process a GET request for the specified resource.
       *
       * @param request The servlet request we are processing
       * @param response The servlet response we are creating
       *
       * @exception IOException if an input/output error occurs
       * @exception ServletException if a servlet-specified error occurs
       */
      protected void doGet(HttpServletRequest request,
                           HttpServletResponse response)
  	throws IOException, ServletException {
          
          response.setStatus(HttpServletResponse.SC_OK);
          
          String command = request.getParameter("command");
          if (command == null) {
              // FIXME : Send a menu page ...
              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
              return;
          }
          
          if (command.equals("addacl")) {
              addACL(request, response);
          } else if (command.equals("removeacl")) {
              removeACL(request, response);
          } else if (command.equals("adduser")) {
              //addUser(request, response);
          } else if (command.equals("removeuser")) {
              //removeUser(request, response);
          } else if (command.equals("addgroup")) {
              //addGroup(request, response);
          } else if (command.equals("removegroup")) {
              //removeGroup(request, response);
          } else {
              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
              return;
          }
          
      }
      
      
      /**
       * Process a POST request for the specified resource.
       *
       * @param request The servlet request we are processing
       * @param response The servlet response we are creating
       *
       * @exception IOException if an input/output error occurs
       * @exception ServletException if a servlet-specified error occurs
       */
      protected void doPost(HttpServletRequest request,
                            HttpServletResponse response)
  	throws IOException, ServletException {
          
          doGet(request, response);
          
      }
  
  
  
      /**
       * Manages some initialization stuff on the server.
       */
      public void init()
          throws ServletException {
          
          String domainConfigFile = "/Domain.xml";
          
          String value = null;
  	try {
  	    value = getServletConfig().getInitParameter("domain");
              if (value != null)
                  domainConfigFile = value;
          } catch (Throwable t) {
  	    ;
  	}
  	try {
              value = getServletConfig().getInitParameter("permissioneditor");
              if (value != null)
                  permissionEditor = value;
          } catch (Throwable t) {
              ;
          }
  	try {
              value = getServletConfig().getInitParameter("usereditor");
              if (value != null)
                  userEditor = value;
          } catch (Throwable t) {
              ;
          }
          
          if (!Domain.isInitialized()) {
              
              try {
                  
                  SAXParserFactory factory = SAXParserFactory.newInstance();
                  factory.setNamespaceAware(false);
                  factory.setValidating(false);
                  SAXParser parser = factory.newSAXParser();
                  
                  InputStream is = 
                      getServletContext().getResourceAsStream(domainConfigFile);
                  if (is == null)
                      throw new ServletException("Can't find init file");
                  Populate pop = new Populate();
                  Configuration slideConfiguration = 
                      new ConfigurationElement(pop.load(new InputSource(is), 
                                                        parser.getParser()));
                  
                  Domain.init(slideConfiguration);
                  
              } catch (Throwable t) {
                  t.printStackTrace();
                  throw new ServletException(t.getMessage());
              }
              
          }
          
      }
      
      
      /**
       * Destroy servlet.
       */
      public void destroy() {
      }
      
      
      // ------------------------------------------------------ Protected Methods
      
      
      /**
       * Removes a permission from an object.
       */
      protected void removeACL(HttpServletRequest request,
                               HttpServletResponse response)
  	throws IOException, ServletException {
          
          // Retrieving request's attributes
          
          String namespaceName = request.getPathInfo();
          if (namespaceName == null) {
              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
              return;
          }
          if (namespaceName.startsWith("/")) {
              namespaceName = namespaceName.substring(1);
          }
          
          String objectUri = request.getParameter("object");
          if (objectUri == null) {
              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
              return;
          }
          
          String subjectUri = request.getParameter("subject");
          if (subjectUri == null) {
              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
              return;
          }
          
          String actionUri = request.getParameter("action");
          if (actionUri == null) {
              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
              return;
          }
          
          try {
              
              NamespaceAccessToken nat = 
                  Domain.accessNamespace(new SecurityToken(this), namespaceName);
              Principal principal = request.getUserPrincipal();
              CredentialsToken token = null;
              if (principal != null) {
                  token = new CredentialsToken(principal);
              } else {
                  token = new CredentialsToken("");
              }
              ObjectNode object = 
                  nat.getStructureHelper().retrieve(token, objectUri);
              SubjectNode subject = (SubjectNode)
                  nat.getStructureHelper().retrieve(token, subjectUri);
              ActionNode action = (ActionNode)
                  nat.getStructureHelper().retrieve(token, actionUri);
              nat.getSecurityHelper().revokePermission(token, object, 
                                                         subject, action);
              
          } catch (AccessDeniedException e) {
              response.setStatus(HttpServletResponse.SC_FORBIDDEN);
              return;
          } catch (ObjectNotFoundException e) {
              response.setStatus(HttpServletResponse.SC_NOT_FOUND);
              return;
          } catch (SlideException e) {
              // FIXME : Can we be more specific ?
              response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
              return;
          }
          
          String contextPath = request.getContextPath();
          if (contextPath != null) {
              response.sendRedirect(contextPath);
          } else {
              response.sendRedirect("/");
          }
          
      }
      
      
      /**
       * Display an acl edit page if params are missing.
       */
      protected void addACL(HttpServletRequest request,
                            HttpServletResponse response)
  	throws IOException, ServletException {
          
          // Retrieving request's attributes
          
          boolean paramMissing = false;
          
          String namespaceName = request.getPathInfo();
          if (namespaceName == null) {
              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
              return;
          }
          if (namespaceName.startsWith("/")) {
              namespaceName = namespaceName.substring(1);
          }
          
          String objectUri = request.getParameter("object");
          if (objectUri == null) {
              paramMissing = true;
          }
          
          String subjectUri = request.getParameter("subject");
          if (subjectUri == null) {
              paramMissing = true;
          }
          
          String actionUri = request.getParameter("action");
          if (actionUri == null) {
              paramMissing = true;
          }
          
          String inheritableValue = request.getParameter("inheritable");
          boolean inheritable = false;
          if (inheritableValue == null) {
              paramMissing = true;
          } else {
              if (inheritableValue.equals("true")) {
                  inheritable = true;
              } else if (inheritableValue.equals("false")) {
                  inheritable = false;
              } else {
                  response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                  return;
              }
          }
          
          String negativeValue = request.getParameter("negative");
          boolean negative = false;
          if (negativeValue == null) {
              paramMissing = true;
          } else {
              if (negativeValue.equals("true")) {
                  negative = true;
              } else if (negativeValue.equals("false")) {
                  negative = false;
              } else {
                  response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                  return;
              }
          }
          
          if (paramMissing) {
              
              // Display the edit page (or redirect to an edit page) ...
              if (permissionEditor != null) {
                  
                  // Redirect to the edit page
                  String editorUrl = permissionEditor + "?namespace=" 
                      + namespaceName;
                  if (objectUri != null) {
                      editorUrl += "&object=" + objectUri;
                  }
                  if (subjectUri != null) {
                      editorUrl += "&subject=" + subjectUri;
                  }
                  if (actionUri != null) {
                      editorUrl += "&action=" + actionUri;
                  }
                  response.sendRedirect(editorUrl);
                  return;
                  
              } else {
                  
                  // Display a simple edit page
                  displayPermissionEditor(request, response, namespaceName, 
                                          objectUri, subjectUri, actionUri);
                  return;
                  
              }
              
          } else {
              
              NodePermission permission = 
                  new NodePermission(objectUri, subjectUri, actionUri, 
                                     inheritable);
              
              try {
                  
                  NamespaceAccessToken nat = 
                      Domain.accessNamespace(new SecurityToken(this), 
                                             namespaceName);
                  Principal principal = request.getUserPrincipal();
                  CredentialsToken token = null;
                  if (principal != null) {
                      token = new CredentialsToken(principal);
                  } else {
                      token = new CredentialsToken("");
                  }
                  if (negative) {
                      nat.getSecurityHelper()
                          .denyPermission(token, permission);
                  } else {
                      nat.getSecurityHelper()
                          .grantPermission(token, permission);
                  }
                  
              } catch (AccessDeniedException e) {
                  response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                  return;
              } catch (ObjectNotFoundException e) {
                  e.printStackTrace();
                  response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                  return;
              } catch (SlideException e) {
                  // FIXME : Can we be more specific ?
                  response.setStatus
                      (HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                  return;
              }
              
          }
          
          String contextPath = request.getContextPath();
          if (contextPath != null) {
              response.sendRedirect(contextPath);
          } else {
              response.sendRedirect("/");
          }
          
      }
      
      
      /**
       * Display an acl edit page if params are missing.
       */
      protected void displayPermissionEditor(HttpServletRequest request,
                                             HttpServletResponse response,
                                             String namespaceName,
                                             String objectUri, String subjectUri,
                                             String actionUri)
          throws IOException, ServletException {
          
          response.setContentType("text/html");
          
          PrintWriter writer = response.getWriter();
          
          writer.print("<html><head></head><body>");
          writer.print("<FORM NAME=\"ACL Editor\" ACTION=\"");
          String contextPath = request.getContextPath();
          if (contextPath != null) {
              writer.print(contextPath);
          }
          writer.print("/manager/" + namespaceName + "\" METHOD=GET>");
          writer.print("Object : <INPUT TYPE=\"text\" NAME=\"object\"");
          if (objectUri != null) {
              writer.print(objectUri);
          }
          writer.print("><br>");
          writer.print("Subject : <INPUT TYPE=\"text\" NAME=\"subject\"");
          if (subjectUri != null) {
              writer.print(subjectUri);
          }
          writer.print("><br>");
          writer.print("Action : <INPUT TYPE=\"text\" NAME=\"action\"");
          if (actionUri != null) {
              writer.print(actionUri);
          }
          writer.print("><br>");
          writer.print("Inheritable : <INPUT TYPE=\"text\" "
                       + "NAME=\"inheritable\" value=\"true\"><br>");
          writer.print("Negative : <INPUT TYPE=\"text\" NAME=\"negative\" " 
                       + "value=\"false\"><br>");
          writer.print("<input type=\"hidden\" name=\"command\" " 
                       + "value=\"addacl\">");
          writer.print("<input type=\"submit\" value=\"Add\">");
          writer.print("</form></body></html>");
          
          writer.close();
          
      }
      
      
  }