/******************************************************************************
* JBoss, a division of Red Hat *
* Copyright 2006, Red Hat Middleware, LLC, and individual *
* contributors as indicated by the @authors tag. See the *
* copyright.txt in the distribution for a full listing of *
* individual contributors. *
* *
* This is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation; either version 2.1 of *
* the License, or (at your option) any later version. *
* *
* This software 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 *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this software; if not, write to the Free *
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
* 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
******************************************************************************/
package org.jboss.portletbridge.context;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.portlet.PortletRequest;
import javax.portlet.faces.BridgeUninitializedException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.portletbridge.PortletBridgePrincipal;
import org.jboss.portletbridge.StateId;
import org.jboss.portletbridge.application.PortletStateHolder;
import org.jboss.portletbridge.application.PortletStateHolder.WindowIDRetriver;
/**
* @author asmirnov
*
*/
public class ServletExternalContextImpl extends AbstractExternalContext {
private static final Log _log = LogFactory
.getLog(ServletExternalContextImpl.class);
private String namespace;
/**
* @param context
* @param request
* @param response
* @param stateId
*/
public ServletExternalContextImpl(ServletContext context,
HttpServletRequest request, HttpServletResponse response,
String stateIdParameter) {
super(context, request, response);
namespace = "";
sessionPrefix = "";
PortletStateHolder portletStateHolder = (PortletStateHolder) context
.getAttribute(PortletStateHolder.STATE_HOLDER);
if (null != portletStateHolder) {
StateId stateId = new StateId(stateIdParameter);
windowState = portletStateHolder.getWindowState(stateId);
if (null != windowState) {
namespace = windowState.getNamespace();
String windowId = windowState.getWindowId();
sessionPrefix = WindowIDRetriver.PORTLET_SCOPE_PREFIX
+ windowId + '?';
portalActionUrl = windowState.getPortalActionURL();
portletBridgeContext = windowState.createBridgeContext();
portletBridgeContext.setInitialRequestAttributeNames(request
.getAttributeNames());
portletBridgeContext.setStateId(stateId);
request.setAttribute(
PortletBridgeContext.REQUEST_PARAMETER_NAME,
portletBridgeContext);
PortletBridgePrincipal portletPrincipal = getPortletPrincipal();
if(null != portletPrincipal){
request.setAttribute(PortletRequest.USER_INFO, portletPrincipal.getUserInfo());
}
} else {
throw new FacesException(
"No saved portlet window state for an id " + stateId);
}
} else {
throw new BridgeUninitializedException(
"JSF Portlet bridge was not initialised before AJAX request");
}
}
public void setResponseCharacterEncoding(String encoding) {
getHttpResponse().setCharacterEncoding(encoding);
}
public String getResponseCharacterEncoding() {
return getHttpResponse().getCharacterEncoding();
}
public String getResponseContentType() {
return getHttpResponse().getContentType();
}
public void setRequestCharacterEncoding(String encoding)
throws UnsupportedEncodingException {
getHttpRequest().setCharacterEncoding(encoding);
}
public String getRequestCharacterEncoding() {
return getHttpRequest().getCharacterEncoding();
}
public String getRequestContentType() {
return getHttpRequest().getContentType();
}
private HttpServletRequest getHttpRequest() {
return (HttpServletRequest) getRequest();
}
private ServletContext getServletContext() {
return (ServletContext) getContext();
}
private HttpServletResponse getHttpResponse() {
return (HttpServletResponse) getResponse();
}
protected String getNamespace() {
return namespace;
}
/*
* (non-Javadoc)
*
* @see
* javax.faces.context.ExternalContext#getInitParameter(java.lang.String)
*/
public String getInitParameter(String name) {
return getServletContext().getInitParameter(name);
}
@SuppressWarnings("unchecked")
protected Enumeration<String> getInitParametersNames() {
return getServletContext().getInitParameterNames();
}
/*
* (non-Javadoc)
*
* @see javax.faces.context.ExternalContext#getResource(java.lang.String)
*/
public URL getResource(String path) throws MalformedURLException {
return getServletContext().getResource(path);
}
/*
* (non-Javadoc)
*
* @see
* javax.faces.context.ExternalContext#getResourceAsStream(java.lang.String)
*/
public InputStream getResourceAsStream(String path) {
return getServletContext().getResourceAsStream(path);
}
/*
* (non-Javadoc)
*
* @see
* javax.faces.context.ExternalContext#getResourcePaths(java.lang.String)
*/
@SuppressWarnings("unchecked")
public Set<String> getResourcePaths(String path) {
return getServletContext().getResourcePaths(path);
}
protected Object getContextAttribute(String name) {
return getServletContext().getAttribute(name);
}
@SuppressWarnings("unchecked")
protected Enumeration<String> getContextAttributeNames() {
return getServletContext().getAttributeNames();
}
protected void setContextAttribute(String name, Object value) {
getServletContext().setAttribute(name, value);
}
public String getAuthType() {
return getHttpRequest().getAuthType();
}
public String getRemoteUser() {
PortletBridgePrincipal userPrincipal = getPortletPrincipal();
if (null != userPrincipal && null != userPrincipal.getName()) {
return userPrincipal.getRemoteUser();
}
return getHttpRequest().getRemoteUser();
}
public String getRequestContextPath() {
return getHttpRequest().getContextPath();
}
public String getRequestPathInfo() {
return getHttpRequest().getPathInfo();
}
public String getRequestServletPath() {
return getHttpRequest().getServletPath();
}
@SuppressWarnings("unchecked")
protected Enumeration<String> enumerateRequestParameterNames() {
return getHttpRequest().getParameterNames();
}
protected Object getRequestAttribute(String name) {
return getHttpRequest().getAttribute(name);
}
@SuppressWarnings("unchecked")
protected Enumeration<String> getRequestAttributeNames() {
return getHttpRequest().getAttributeNames();
}
protected String[] getRequestParameterValues(String name) {
return getHttpRequest().getParameterValues(name);
}
protected String getRequestHeader(String name) {
return getHttpRequest().getHeader(name);
}
@SuppressWarnings("unchecked")
protected Enumeration<String> getRequestHeaderNames() {
return getHttpRequest().getHeaderNames();
}
@SuppressWarnings("unchecked")
protected String[] getRequestHeaderValues(String name) {
Enumeration<String> values = getHttpRequest().getHeaders(name);
ArrayList<String> valuesList = new ArrayList<String>();
while (values.hasMoreElements()) {
valuesList.add(values.nextElement());
}
return (String[]) valuesList.toArray(EMPTY_STRING_ARRAY);
}
protected String getRequestParameter(String name) {
return getHttpRequest().getParameter(name);
}
private String sessionPrefix;
private PortalActionURL portalActionUrl;
private String getSessionPrefix() {
return sessionPrefix;
}
protected Object getSessionAttribute(String name) {
return getHttpRequest().getSession(true).getAttribute(
getSessionPrefix() + name);
}
@SuppressWarnings("unchecked")
protected Enumeration<String> getSessionAttributeNames() {
return new SessionAttributesNames(getHttpRequest().getSession(true)
.getAttributeNames(), getSessionPrefix());
}
protected void removeSessionAttribute(String name) {
getHttpRequest().getSession(true).removeAttribute(
getSessionPrefix() + name);
}
protected void setSessionAttribute(String name, Object value) {
getHttpRequest().getSession(true).setAttribute(
getSessionPrefix() + name, value);
}
protected void removeContextAttribute(String name) {
getHttpRequest().getSession(true).removeAttribute(name);
}
protected void removeRequestAttribute(String name) {
getHttpRequest().removeAttribute(name);
}
protected void setRequestAttribute(String name, Object value) {
getHttpRequest().setAttribute(name, value);
}
public void dispatch(String path) throws IOException {
RequestDispatcher requestDispatcher = getHttpRequest()
.getRequestDispatcher(path);
if (requestDispatcher == null) {
(getHttpResponse()).sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
try {
requestDispatcher.forward(getHttpRequest(), getHttpResponse());
} catch (IOException ioe) {
throw ioe;
} catch (ServletException se) {
throw new FacesException(se);
}
}
@Override
protected String createActionUrl(PortalActionURL url) {
// TODO - detect ViewId
PortalActionURL actionUrl = new PortalActionURL(portalActionUrl);
actionUrl.getParameters().putAll(url.getParameters());
actionUrl.setParameter(VIEW_ID_PARAMETER, getViewIdFromUrl(url));
return actionUrl.toString();
}
protected String getViewIdFromUrl(PortalActionURL url) {
String viewId;
viewId = url.getParameter(VIEW_ID_PARAMETER);
if (null == viewId) {
viewId = url.getPath();
if (viewId.startsWith(getRequestContextPath())) {
viewId = viewId.substring(getRequestContextPath().length());
}
if (null != getRequestServletPath() && null != getRequestPathInfo()) {
// PrefixMapping
if (viewId.startsWith(getRequestServletPath())) {
viewId = viewId.substring(getRequestServletPath().length());
}
} else if (null != getRequestPathInfo()) {
int i = viewId.lastIndexOf('.');
int j = getRequestPathInfo().lastIndexOf('.');
if (i >= 0 && j >= 0) {
viewId = viewId.substring(0, i)
+ getRequestPathInfo().substring(j);
}
}
}
return viewId;
}
/**
* @param url
* @return
*/
protected String encodeURL(String url) {
return getHttpResponse().encodeURL(url);
}
public Locale getRequestLocale() {
Locale locale = windowState.getPortletLocale();
if (null == locale) {
locale = getHttpRequest().getLocale();
}
return locale;
}
@SuppressWarnings("unchecked")
public Iterator<Locale> getRequestLocales() {
return new EnumerationIterator(getHttpRequest().getLocales());
}
public Object getSession(boolean create) {
HttpSession session = getHttpRequest().getSession(create);
if (null != session) {
session = new ServletSessionWrapper(session, getSessionPrefix());
}
return session;
}
public Principal getUserPrincipal() {
PortletBridgePrincipal portletPrincipal = getPortletPrincipal();
if(null == portletPrincipal || null == portletPrincipal.getName()){
//return getHttpRequest().getUserPrincipal();
return null;
}
return portletPrincipal;
}
private PortletBridgePrincipal getPortletPrincipal() {
PortletBridgePrincipal userPrincipal = null;
HttpSession httpSession = getHttpRequest().getSession(false);
if (null != httpSession) {
userPrincipal = (PortletBridgePrincipal) httpSession
.getAttribute(PORTAL_USER_PRINCIPAL);
}
return userPrincipal;
}
public boolean isUserInRole(String role) {
PortletBridgePrincipal portletPrincipal = getPortletPrincipal();
return null != portletPrincipal?portletPrincipal.isUserInRole(role):getHttpRequest().isUserInRole(role);
}
public void log(String message) {
getServletContext().log(message);
}
public void log(String message, Throwable exception) {
getServletContext().log(message, exception);
}
public void redirect(String url) throws IOException {
getHttpResponse().sendRedirect(url);
FacesContext.getCurrentInstance().responseComplete();
}
}