
clime.messadmin.admin.MessAdminServlet Maven / Gradle / Ivy
The newest version!
package clime.messadmin.admin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import clime.messadmin.core.Constants;
import clime.messadmin.core.MessAdmin;
import clime.messadmin.i18n.I18NSupport;
import clime.messadmin.model.Application;
import clime.messadmin.model.IApplicationInfo;
import clime.messadmin.model.IServerInfo;
import clime.messadmin.model.ISessionInfo;
import clime.messadmin.model.Server;
import clime.messadmin.model.Session;
import clime.messadmin.providers.spi.DisplayFormatProvider;
import clime.messadmin.providers.spi.LocaleProvider;
import clime.messadmin.providers.spi.UserNameProvider;
import clime.messadmin.taglib.core.Util;
import clime.messadmin.taglib.fmt.BundleTag;
import clime.messadmin.taglib.jstl.fmt.LocalizationContext;
import clime.messadmin.utils.ComparableBoolean;
import clime.messadmin.utils.ReverseComparator;
import clime.messadmin.utils.SessionUtils;
/**
* Servlet implementation class for Servlet: MessAdminServlet
* IMPLEMENTATION NOTE: always use include() instead of forward(), to get the real name of this servlet in jsp's
* @author Cédrik LIME
*/
public class MessAdminServlet extends HttpServlet implements Servlet {
private static final boolean DEBUG = false;
private static final String I18N_BUNDLE_NAME = "clime.messadmin.admin.i18n.core";//$NON-NLS-1$
private static final String METHOD_POST = "POST";//$NON-NLS-1$
protected String authorizationPassword = null;
/** {@inheritDoc} */
public void log(String message) {
if (DEBUG) {
getServletContext().log(getServletName() + ": " + message);//$NON-NLS-1$
}
}
/** {@inheritDoc} */
public void log(String message, Throwable t) {
if (DEBUG) {
getServletContext().log(getServletName() + ": " + message, t);//$NON-NLS-1$
}
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public MessAdminServlet() {
super();
}
/**
* {@inheritDoc}
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
process(req, resp);
} finally {
I18NSupport.setAdminLocale(null);
}
}
/**
* {@inheritDoc}
*/
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
process(req, resp);
} finally {
I18NSupport.setAdminLocale(null);
}
}
/**
* Dispatcher method which processes the request
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (! HTTPAuthorizationProvider.checkAccess(authorizationPassword, req, resp)) {
return;
}
if (req.getParameter(Constants.APPLICATION_MESSAGE) != null) {
req.setAttribute(Constants.APPLICATION_MESSAGE, req.getParameter(Constants.APPLICATION_MESSAGE));
}
if (req.getParameter(Constants.APPLICATION_ERROR) != null) {
req.setAttribute(Constants.APPLICATION_ERROR, req.getParameter(Constants.APPLICATION_ERROR));
}
DisplayFormatProvider displayFormatProvider = DisplayFormatProvider.Util.getInstance(req);
resp.setContentType(displayFormatProvider.getContentType());
//resp.setCharacterEncoding("UTF-8");//$NON-NLS-1$
// set response locale from client's browser settings.
LocalizationContext l10nContext = BundleTag.findMatch(req, I18N_BUNDLE_NAME);
if (l10nContext != null && l10nContext.getLocale() != null) {
resp.setLocale(l10nContext.getLocale());
} else {
resp.setLocale(I18NSupport.DEFAULT_ADMIN_LOCALE);
}
I18NSupport.setAdminLocale(resp.getLocale()); // necessary for plugins
displayFormatProvider.preProcess(req, resp);
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
String action = req.getParameter("action");//$NON-NLS-1$
// The Big Dispatch(TM), part 1
if ("serverInfos".equals(action)) {//$NON-NLS-1$
displayServerInfosPage(displayFormatProvider, req, resp);
return;
} else if ("webAppsList".equals(action)) {//$NON-NLS-1$
displayWebAppsList(displayFormatProvider, req, resp);
return;
} else if ("injectApplications".equals(action)) {//$NON-NLS-1$
String permanent = req.getParameter("permanent");//$NON-NLS-1$
String[] applicationIds = req.getParameterValues("applicationIds");//$NON-NLS-1$
String message = req.getParameter("message");//$NON-NLS-1$
int i;
if (permanent != null) {
i = MessAdmin.injectApplicationsPermanent(applicationIds, message);
} else {
i = MessAdmin.injectApplicationsOnce(applicationIds, message);
}
req.setAttribute(Constants.APPLICATION_MESSAGE, I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "injectApplications.ok", new Integer[] {new Integer(i)}));//$NON-NLS-1$
displayWebAppsList(displayFormatProvider, req, resp);
return;
}
// Get the WebApp context we want to work with
String context = req.getParameter("context");//$NON-NLS-1$
if (context == null && Server.getInstance().getAllKnownInternalContexts().size() == 1) {
context = (String) Server.getInstance().getAllKnownInternalContexts().toArray()[0];//req.getContextPath();
}
// If no or invalid context, display a list of available WebApps
if (context == null || Server.getInstance().getApplication(context) == null) {
displayWebAppsList(displayFormatProvider, req, resp);
return;
}
req.setAttribute("context", context);//$NON-NLS-1$
// The Big Dispatch(TM), part 2
if ("webAppStats".equals(action)) {//$NON-NLS-1$
displayWebAppStatsPage(displayFormatProvider, req, resp, context);
return;
} else if ("sessionsList".equals(action)) {//$NON-NLS-1$
displaySessionsListPage(displayFormatProvider, req, resp, context);
return;
} else if ("sessionDetail".equals(action)) {//$NON-NLS-1$
String sessionId = req.getParameter("sessionId");//$NON-NLS-1$
displaySessionDetailPage(displayFormatProvider, req, resp, context, sessionId);
return;
} else if ("removeServletContextAttribute".equals(action)) {//$NON-NLS-1$
String name = req.getParameter("attributeName");//$NON-NLS-1$
IApplicationInfo applicationInfo = Server.getInstance().getApplication(context).getApplicationInfo();
boolean removed = (null != applicationInfo.getAttribute(name));
applicationInfo.removeAttribute(name);
if (removed) {
req.setAttribute(Constants.APPLICATION_MESSAGE,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "removeServletContextAttribute.ok", new String[] {name}));//$NON-NLS-1$
} else {
req.setAttribute(Constants.APPLICATION_ERROR,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "removeServletContextAttribute.ko", new String[] {context, name}));//$NON-NLS-1$
}
resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL().append("?action=webAppStats&context=").append(context).toString()));
return;
} else if ("injectApplication".equals(action)) {//$NON-NLS-1$
String message = req.getParameter("message");//$NON-NLS-1$
Application application = Server.getInstance().getApplication(context);
application.injectPermanentMessage(message);
req.setAttribute(Constants.APPLICATION_MESSAGE,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "injectApplication.ok"));//$NON-NLS-1$
displaySessionsListPage(displayFormatProvider, req, resp, context);
return;
} else if ("injectSessions".equals(action)) {//$NON-NLS-1$
String[] sessionIds = req.getParameterValues("sessionIds");//$NON-NLS-1$
String message = req.getParameter("message");//$NON-NLS-1$
int i = MessAdmin.injectSessions(context, sessionIds, message);
req.setAttribute(Constants.APPLICATION_MESSAGE, "" + i + " sessions modified.");
displaySessionsListPage(displayFormatProvider, req, resp, context);
return;
} else if ("invalidateSessions".equals(action)) {//$NON-NLS-1$
String[] sessionIds = req.getParameterValues("sessionIds");//$NON-NLS-1$
int i = MessAdmin.invalidateSessions(context, sessionIds);
req.setAttribute(Constants.APPLICATION_MESSAGE,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "invalidateSessions.ok", new Integer[] {new Integer(i)}));//$NON-NLS-1$
displaySessionsListPage(displayFormatProvider, req, resp, context);
return;
} else if ("setSessionMaxInactiveInterval".equals(action)) {//$NON-NLS-1$
String sessionId = req.getParameter("sessionId");//$NON-NLS-1$
String timeoutStr = req.getParameter("timeout");//$NON-NLS-1$
try {
int timeout = Integer.parseInt(timeoutStr.trim()) * 60;
int oldTimeout = MessAdmin.setSessionMaxInactiveInterval(context, sessionId, timeout);
if (oldTimeout != 0) {
req.setAttribute(Constants.APPLICATION_MESSAGE,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "setSessionMaxInactiveInterval.ok", new Object[] {new Integer(oldTimeout/60), timeoutStr}));//$NON-NLS-1$
} else {
req.setAttribute(Constants.APPLICATION_ERROR,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "setSessionMaxInactiveInterval.ko", new String[] {sessionId}));//$NON-NLS-1$
}
} catch (NumberFormatException nfe) {
req.setAttribute(Constants.APPLICATION_ERROR,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "setSessionMaxInactiveInterval.error"));//$NON-NLS-1$
} catch (NullPointerException npe) {
req.setAttribute(Constants.APPLICATION_ERROR,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "setSessionMaxInactiveInterval.error"));//$NON-NLS-1$
}
resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL().append("?action=sessionDetail&context=").append(context).append("&sessionId=").append(Util.URLEncode(sessionId, resp.getCharacterEncoding())).toString()));
return;
} else if ("removeSessionAttribute".equals(action)) {//$NON-NLS-1$
String sessionId = req.getParameter("sessionId");//$NON-NLS-1$
String name = req.getParameter("attributeName");//$NON-NLS-1$
boolean removed = MessAdmin.removeSessionAttribute(context, sessionId, name);
if (removed) {
req.setAttribute(Constants.APPLICATION_MESSAGE,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "removeSessionAttribute.ok", new String[] {name}));//$NON-NLS-1$
} else {
req.setAttribute(Constants.APPLICATION_ERROR,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, cl, "removeSessionAttribute.ko", new String[] {name}));//$NON-NLS-1$
}
resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL().append("?action=sessionDetail&context=").append(context).append("&sessionId=").append(Util.URLEncode(sessionId, resp.getCharacterEncoding())).toString()));
return;
} // else
// default fall-back action
displaySessionsListPage(displayFormatProvider, req, resp, context);
}
private StringBuffer getMessages(HttpServletRequest req, HttpServletResponse resp) {
StringBuffer buffer = new StringBuffer();
if (req.getAttribute(Constants.APPLICATION_MESSAGE) != null) {
buffer.append('&').append(Constants.APPLICATION_MESSAGE).append('=').
append(Util.URLEncode(String.valueOf(req.getAttribute(Constants.APPLICATION_MESSAGE)), resp.getCharacterEncoding()));
}
if (req.getAttribute(Constants.APPLICATION_ERROR) != null) {
buffer.append('&').append(Constants.APPLICATION_ERROR).append('=')
.append(Util.URLEncode(String.valueOf(req.getAttribute(Constants.APPLICATION_ERROR)), resp.getCharacterEncoding()));
}
return buffer;
}
protected void setNoCache(HttpServletResponse resp) {
// NOTE - This header will be overridden
// automatically if a RequestDispatcher.forward()
call is
// ultimately invoked.
//resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 //$NON-NLS-1$ //$NON-NLS-2$
resp.setDateHeader("Expires", 0); // 0 means now //$NON-NLS-1$
// should we decide to enable caching, here are the current vary:
resp.addHeader("Vary", "Accept-Language,Accept-Encoding");
}
/**
* Displays the Web Applications list
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void displayWebAppsList(DisplayFormatProvider displayFormatProvider,
HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (METHOD_POST.equals(req.getMethod())) {
resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL().append("?action=webAppsList").append(getMessages(req, resp)).toString()));//$NON-NLS-1$
return;
}
Set/**/ applicationInfos = Server.getInstance().getApplicationInfos();
setNoCache(resp);
displayFormatProvider.displayWebAppsList(req, resp, applicationInfos);
}
/**
* Displays the HttpSessions list for a given WebApp (context)
* @param req
* @param resp
* @param context internal context name for required WebApp
* @throws ServletException
* @throws IOException
*/
protected void displaySessionsListPage(DisplayFormatProvider displayFormatProvider,
HttpServletRequest req, HttpServletResponse resp, String context) throws ServletException, IOException {
if (METHOD_POST.equals(req.getMethod())) {
StringBuffer buffer = req.getRequestURL().append("?action=sessionsList&context=").append(context);//$NON-NLS-1$
if (req.getAttribute("sort") != null) {//$NON-NLS-1$
buffer.append('&').append("sort=").append(req.getAttribute("sort"));//$NON-NLS-1$//$NON-NLS-2$
}
if (req.getAttribute("order") != null) {//$NON-NLS-1$
buffer.append('&').append("order=").append(req.getAttribute("order"));//$NON-NLS-1$//$NON-NLS-2$
}
resp.sendRedirect(resp.encodeRedirectURL(buffer.append(getMessages(req, resp)).toString()));
return;
}
Collection/**/ activeSessions = Server.getInstance().getApplication(context).getActiveSessionInfos();
String sortBy = req.getParameter("sort");//$NON-NLS-1$
String orderBy = null;
if (null != sortBy && !"".equals(sortBy.trim())) {
activeSessions = new ArrayList(activeSessions);
Comparator comparator = getComparator(sortBy);
if (comparator != null) {
orderBy = req.getParameter("order");//$NON-NLS-1$
if ("DESC".equalsIgnoreCase(orderBy)) {//$NON-NLS-1$
comparator = new ReverseComparator(comparator);
//orderBy = "ASC";
} else {
//orderBy = "DESC";
}
try {
Collections.sort((List)activeSessions, comparator);
} catch (IllegalStateException ise) {
// at least 1 session is invalidated
req.setAttribute(Constants.APPLICATION_ERROR,
I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, null, "sessionsList.sort.error"));//$NON-NLS-1$
}
} else {
log("WARNING: unknown sort order: " + sortBy);
}
}
setNoCache(resp);
displayFormatProvider.displaySessionsListPage(req, resp, sortBy, orderBy,
Server.getInstance().getApplication(context).getApplicationInfo(),
activeSessions, Server.getInstance().getApplication(context).getPassiveSessionsIds());
}
/**
* Displays the details page for a given HttpSession
* @param req
* @param resp
* @param context internal context name for required WebApp
* @throws ServletException
* @throws IOException
*/
protected void displaySessionDetailPage(DisplayFormatProvider displayFormatProvider,
HttpServletRequest req, HttpServletResponse resp, String context, String sessionId) throws ServletException, IOException {
if (METHOD_POST.equals(req.getMethod())) {
resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL().append("?action=sessionDetail&context=").append(context).append("&sessionId=")
.append(Util.URLEncode(sessionId, resp.getCharacterEncoding())).append(getMessages(req, resp)).toString()));//$NON-NLS-1$//$NON-NLS-2$
return;
}
Application application = Server.getInstance().getApplication(context);
Session session = application.getSession(sessionId);
if (null == session) {
String error = I18NSupport.getLocalizedMessage(I18N_BUNDLE_NAME, null, "sessionDetail.null.error", new String[] {sessionId});//$NON-NLS-1$
log(error);
req.setAttribute(Constants.APPLICATION_ERROR, error);
displaySessionsListPage(displayFormatProvider, req, resp, context);
return;
}
setNoCache(resp);
IApplicationInfo applicationInfo = application.getApplicationInfo();
ISessionInfo currentSession = session.getSessionInfo();
displayFormatProvider.displaySessionDetailPage(req, resp, applicationInfo, currentSession);
}
/**
* Displays the details page for a Web Application
* @param req
* @param resp
* @param context internal context name for required WebApp
* @throws ServletException
* @throws IOException
*/
protected void displayWebAppStatsPage(DisplayFormatProvider displayFormatProvider,
HttpServletRequest req, HttpServletResponse resp, String context) throws ServletException, IOException {
if (METHOD_POST.equals(req.getMethod())) {
resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL()
.append("?action=webAppStats&context=").append(context).append(getMessages(req, resp)).toString()));//$NON-NLS-1$
return;
}
setNoCache(resp);
IApplicationInfo webAppStats = Server.getInstance().getApplication(context).getApplicationInfo();
displayFormatProvider.displayWebAppStatsPage(req, resp, webAppStats);
}
/**
* Displays the page for the Server Informations
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void displayServerInfosPage(DisplayFormatProvider displayFormatProvider,
HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (METHOD_POST.equals(req.getMethod())) {
resp.sendRedirect(resp.encodeRedirectURL(req.getRequestURL().
append("?action=serverInfos").append(getMessages(req, resp)).toString()));//$NON-NLS-1$
return;
}
setNoCache(resp);
IServerInfo serverInfo = Server.getInstance().getServerInfo();
displayFormatProvider.displayServerInfosPage(req, resp, serverInfo);
}
/**
* Comparator used on the HttpSessions list, when sorting is required
* @param sortBy
* @return Comparator
*/
protected Comparator getComparator(String sortBy) {
Comparator comparator = null;
if ("CreationTime".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
return new Date(session.getCreationTime());
}
};
} else if ("id".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
return session.getId();
}
};
} else if ("LastAccessedTime".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
return new Date(session.getLastAccessedTime());
}
};
} else if ("MaxInactiveInterval".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
return new Date(session.getMaxInactiveInterval());
}
};
} else if ("new".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
return ComparableBoolean.valueOf(session.isNew());
}
};
} else if ("locale".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
ClassLoader cl = Server.getInstance().getApplication(session.getServletContext()).getApplicationInfo().getClassLoader();
Locale locale = LocaleProvider.Util.guessLocaleFromSession(session, cl);
return (null == locale) ? "" : locale.toString();
}
};
} else if ("user".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
ClassLoader cl = Server.getInstance().getApplication(session.getServletContext()).getApplicationInfo().getClassLoader();
Object user = UserNameProvider.Util.guessUserFromSession(session, cl);
return (null == user) ? "" : user.toString();
}
};
} else if ("UsedTime".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
return new Date(SessionUtils.getUsedTimeForSession(session));
}
};
} else if ("IdleTime".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
return new Date(SessionUtils.getIdleTimeForSession(session));
}
};
} else if ("TTL".equalsIgnoreCase(sortBy)) {//$NON-NLS-1$
comparator = new BaseSessionComparator() {
public Comparable getComparableObject(HttpSession session) {
return new Date(SessionUtils.getTTLForSession(session));
}
};
}
//TODO: complete this to TTL, etc.
return comparator;
}
/**
* {@inheritDoc}
*/
public String getServletInfo() {
return "MessAdminServlet, copyright (c) 2005-2007 C?drik LIME";
}
/**
* {@inheritDoc}
*/
public void init() throws ServletException {
super.init();
String initAuthorizationPassword = getServletConfig().getInitParameter("AuthorizationPassword");//$NON-NLS-1$
if (null != initAuthorizationPassword) {
authorizationPassword = initAuthorizationPassword;
}
DisplayFormatProvider.Util.initAll(getServletConfig());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy