KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > web > app > servlet > BaseServlet


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.web.app.servlet;
18
19 import java.io.IOException JavaDoc;
20 import java.io.UnsupportedEncodingException JavaDoc;
21 import java.net.URLDecoder JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.HashSet JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.Set JavaDoc;
26
27 import javax.faces.context.FacesContext;
28 import javax.servlet.ServletContext JavaDoc;
29 import javax.servlet.http.HttpServlet JavaDoc;
30 import javax.servlet.http.HttpServletRequest JavaDoc;
31 import javax.servlet.http.HttpServletResponse JavaDoc;
32
33 import org.alfresco.service.ServiceRegistry;
34 import org.alfresco.service.cmr.model.FileFolderService;
35 import org.alfresco.service.cmr.model.FileInfo;
36 import org.alfresco.service.cmr.model.FileNotFoundException;
37 import org.alfresco.service.cmr.repository.NodeRef;
38 import org.alfresco.web.app.Application;
39 import org.alfresco.web.bean.LoginBean;
40 import org.alfresco.web.bean.repository.Repository;
41 import org.apache.commons.logging.Log;
42 import org.apache.commons.logging.LogFactory;
43 import org.springframework.web.context.WebApplicationContext;
44 import org.springframework.web.context.support.WebApplicationContextUtils;
45 import org.springframework.web.jsf.FacesContextUtils;
46
47 /**
48  * Base servlet class containing useful constant values and common methods for Alfresco servlets.
49  *
50  * @author Kevin Roast
51  */

52 public abstract class BaseServlet extends HttpServlet JavaDoc
53 {
54    public static final String JavaDoc FACES_SERVLET = "/faces";
55    
56    /** an existing Ticket can be passed to most servlet for non-session based authentication */
57    private static final String JavaDoc ARG_TICKET = "ticket";
58    
59    /** forcing guess access is available on most servlets */
60    private static final String JavaDoc ARG_GUEST = "guest";
61    
62    /** list of valid JSPs for redirect after a clean login */
63    // TODO: make this list configurable
64
private static Set JavaDoc<String JavaDoc> validRedirectJSPs = new HashSet JavaDoc<String JavaDoc>();
65    static
66    {
67       validRedirectJSPs.add("/jsp/browse/browse.jsp");
68       validRedirectJSPs.add("/jsp/browse/dashboard.jsp");
69       validRedirectJSPs.add("/jsp/admin/admin-console.jsp");
70       validRedirectJSPs.add("/jsp/admin/node-browser.jsp");
71       validRedirectJSPs.add("/jsp/admin/store-browser.jsp");
72       validRedirectJSPs.add("/jsp/categories/categories.jsp");
73       validRedirectJSPs.add("/jsp/dialog/about.jsp");
74       validRedirectJSPs.add("/jsp/dialog/advanced-search.jsp");
75       validRedirectJSPs.add("/jsp/dialog/system-info.jsp");
76       validRedirectJSPs.add("/jsp/forums/forums.jsp");
77       validRedirectJSPs.add("/jsp/users/users.jsp");
78    }
79    
80    private static Log logger = LogFactory.getLog(BaseServlet.class);
81    
82    
83    /**
84     * Return the ServiceRegistry helper instance
85     *
86     * @param sc ServletContext
87     *
88     * @return ServiceRegistry
89     */

90    public static ServiceRegistry getServiceRegistry(ServletContext JavaDoc sc)
91    {
92       WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
93       return (ServiceRegistry)wc.getBean(ServiceRegistry.SERVICE_REGISTRY);
94    }
95    
96    /**
97     * Perform an authentication for the servlet request URI. Processing any "ticket" or
98     * "guest" URL arguments.
99     *
100     * @return AuthenticationStatus
101     *
102     * @throws IOException
103     */

104    public AuthenticationStatus servletAuthenticate(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
105       throws IOException JavaDoc
106    {
107       AuthenticationStatus status;
108       
109       // see if a ticket or a force Guest parameter has been supplied
110
String JavaDoc ticket = req.getParameter(ARG_TICKET);
111       if (ticket != null && ticket.length() != 0)
112       {
113          status = AuthenticationHelper.authenticate(getServletContext(), req, res, ticket);
114       }
115       else
116       {
117          boolean forceGuest = false;
118          String JavaDoc guest = req.getParameter(ARG_GUEST);
119          if (guest != null)
120          {
121             forceGuest = Boolean.parseBoolean(guest);
122          }
123          status = AuthenticationHelper.authenticate(getServletContext(), req, res, forceGuest);
124       }
125       if (status == AuthenticationStatus.Failure)
126       {
127          // authentication failed - now need to display the login page to the user
128
redirectToLoginPage(req, res, getServletContext());
129       }
130       
131       return status;
132    }
133    
134    /**
135     * Redirect to the Login page - saving the current URL which can be redirected back later
136     * once the user has successfully completed the authentication process.
137     */

138    public static void redirectToLoginPage(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res, ServletContext JavaDoc sc)
139       throws IOException JavaDoc
140    {
141       // authentication failed - so end servlet execution and redirect to login page
142
// also save the requested URL so the login page knows where to redirect too later
143
res.sendRedirect(req.getContextPath() + FACES_SERVLET + Application.getLoginPage(sc));
144       String JavaDoc uri = req.getRequestURI();
145       if (uri.indexOf(req.getContextPath() + FACES_SERVLET) != -1)
146       {
147          // if we find a JSF servlet reference in the URI then we need to check if the rest of the
148
// JSP specified is valid for a redirect operation after Login has occured.
149
int jspIndex = uri.indexOf(BaseServlet.FACES_SERVLET) + BaseServlet.FACES_SERVLET.length();
150          if (uri.length() > jspIndex && BaseServlet.validRedirectJSP(uri.substring(jspIndex)))
151          {
152             req.getSession().setAttribute(LoginBean.LOGIN_REDIRECT_KEY, uri);
153          }
154       }
155       else
156       {
157          req.getSession().setAttribute(LoginBean.LOGIN_REDIRECT_KEY, uri);
158       }
159    }
160    
161    /**
162     * Returns true if the specified JSP file is valid for a redirect after login.
163     * Only a specific sub-set of the available JSPs are valid to jump directly too after a
164     * clean login attempt - e.g. those that do not require JSF bean context setup. This is
165     * a limitation of the JSP architecture. The ExternalAccessServlet provides a mechanism to
166     * setup the JSF bean context directly for some specific cases.
167     *
168     * @param jsp Filename of JSP to check, for example "/jsp/browse/browse.jsp"
169     *
170     * @return true if the JSP is in the list of valid direct URLs, false otherwise
171     */

172    public static boolean validRedirectJSP(String JavaDoc jsp)
173    {
174       return validRedirectJSPs.contains(jsp);
175    }
176    
177    /**
178     * Resolves the given path elements to a NodeRef in the current repository
179     *
180     * @param context Faces context
181     * @param args The elements of the path to lookup
182     */

183    public static NodeRef resolveWebDAVPath(FacesContext context, String JavaDoc[] args)
184    {
185       NodeRef nodeRef = null;
186
187       List JavaDoc<String JavaDoc> paths = new ArrayList JavaDoc<String JavaDoc>(args.length-1);
188       
189       FileInfo file = null;
190       try
191       {
192          // create a list of path elements (decode the URL as we go)
193
for (int x = 1; x < args.length; x++)
194          {
195             paths.add(URLDecoder.decode(args[x], "UTF-8"));
196          }
197          
198          if (logger.isDebugEnabled())
199             logger.debug("Attempting to resolve webdav path: " + paths);
200          
201          // get the company home node to start the search from
202
NodeRef companyHome = new NodeRef(Repository.getStoreRef(),
203                Application.getCompanyRootId());
204          
205          WebApplicationContext wc = FacesContextUtils.getRequiredWebApplicationContext(context);
206          FileFolderService ffs = (FileFolderService)wc.getBean("FileFolderService");
207          file = ffs.resolveNamePath(companyHome, paths);
208          nodeRef = file.getNodeRef();
209          
210          if (logger.isDebugEnabled())
211             logger.debug("Resolved webdav path to NodeRef: " + nodeRef);
212       }
213       catch (UnsupportedEncodingException JavaDoc uee)
214       {
215          if (logger.isWarnEnabled())
216             logger.warn("Failed to resolve webdav path", uee);
217          
218          nodeRef = null;
219       }
220       catch (FileNotFoundException fne)
221       {
222          if (logger.isWarnEnabled())
223             logger.warn("Failed to resolve webdav path", fne);
224          
225          nodeRef = null;
226       }
227       
228       return nodeRef;
229    }
230 }
231
Popular Tags