/** * Removes an attribute from an HttpSession * @param cn Name of the application hosting the session from which the * attribute is to be removed * @param sessionId * @param attributeName * @param smClient StringManager for the client's locale * @return true if there was an attribute removed, false otherwise * @throws IOException */ protected boolean removeSessionAttribute(ContextName cn, String sessionId, String attributeName, StringManager smClient) throws IOException { HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't remove attribute '" + attributeName + "' for null session " + sessionId); } return false; } boolean wasPresent = (null != session.getAttribute(attributeName)); try { session.removeAttribute(attributeName); } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } } return wasPresent; }
protected static boolean validateContextName(ContextName cn, PrintWriter writer, StringManager sm) { // ContextName should be non-null with a path that is empty or starts // with / if (cn != null && (cn.getPath().startsWith("/") || cn.getPath().equals(""))) { return true; } String path = null; if (cn != null) { path = RequestUtil.filter(cn.getPath()); } writer.println(sm.getString("managerServlet.invalidPath", path)); return false; }
/** * * @param cn * Name of the application for which the sessions will be listed * @param req * @param resp * @param smClient * StringManager for the client's locale * @throws ServletException * @throws IOException */ protected void displaySessionsListPage(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForName(cn, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = Collections.reverseOrder(comparator); orderBy = "ASC"; } else { orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); // strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP // 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); }
/** * Removes an attribute from an HttpSession * * @param cn * Name of the application hosting the session from which the * attribute is to be removed * @param sessionId * @param attributeName * @param smClient * StringManager for the client's locale * @return true if there was an attribute removed, false otherwise * @throws IOException */ protected boolean removeSessionAttribute(ContextName cn, String sessionId, String attributeName, StringManager smClient) throws IOException { HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't remove attribute '" + attributeName + "' for null session " + sessionId); } return false; } boolean wasPresent = (null != session.getAttribute(attributeName)); try { session.removeAttribute(attributeName); } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } } return wasPresent; }
@Override public void fileModified(File newWar) { try { File deployWar = new File(getDeployDirFile(), newWar.getName()); ContextName cn = new ContextName(deployWar.getName(), true); if (deployWar.exists() && deployWar.lastModified() > newWar.lastModified()) { if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.alreadyDeployed", cn.getName())); return; } if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.modInstall", cn.getName(), deployWar.getAbsolutePath())); // install local if (!isServiced(cn.getName())) { addServiced(cn.getName()); try { copy(newWar, deployWar); check(cn.getName()); } finally { removeServiced(cn.getName()); } } else { log.error(sm.getString("farmWarDeployer.servicingDeploy", cn.getName(), deployWar.getName())); } install(cn.getName(), deployWar); } catch (Exception x) { log.error(sm.getString("farmWarDeployer.modInstallFail"), x); } }
@Override public void fileRemoved(File removeWar) { try { ContextName cn = new ContextName(removeWar.getName(), true); if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.removeLocal", cn.getName())); remove(cn.getName(), true); } catch (Exception x) { log.error(sm.getString("farmWarDeployer.removeLocalFail"), x); } }
/** * Deploy an application for the specified path from the specified * web application archive. * * @param config URL of the context configuration file to be deployed * @param cn Name of the application to be deployed * @param war URL of the web application archive to be deployed * @return message String */ protected String deployInternal(String config, ContextName cn, String war, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.deploy(printWriter, config, cn, war, false, smClient); return stringWriter.toString(); }
/** * * Extract the expiration request parameter * * @param cn Name of the application from which to expire sessions * @param req * @param smClient StringManager for the client's locale */ protected String expireSessions(ContextName cn, HttpServletRequest req, StringManager smClient) { int idle = -1; String idleParam = req.getParameter("idle"); if (idleParam != null) { try { idle = Integer.parseInt(idleParam); } catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); } } return sessions(cn, idle, smClient); }
protected List<Session> getSessionsForName(ContextName cn, StringManager smClient) { if ((cn == null) || !(cn.getPath().startsWith("/") || cn.getPath().equals(""))) { String path = null; if (cn != null) { path = cn.getPath(); } throw new IllegalArgumentException(smClient.getString( "managerServlet.invalidPath", RequestUtil.filter(path))); } Context ctxt = (Context) host.findChild(cn.getName()); if (null == ctxt) { throw new IllegalArgumentException(smClient.getString( "managerServlet.noContext", RequestUtil.filter(cn.getDisplayName()))); } Manager manager = ctxt.getManager(); List<Session> sessions = new ArrayList<Session>(); sessions.addAll(Arrays.asList(manager.findSessions())); if (manager instanceof DistributedManager && showProxySessions) { // Add dummy proxy sessions Set<String> sessionIds = ((DistributedManager) manager).getSessionIdsFull(); // Remove active (primary and backup) session IDs from full list for (Session session : sessions) { sessionIds.remove(session.getId()); } // Left with just proxy sessions - add them for (String sessionId : sessionIds) { sessions.add(new DummyProxySession(sessionId)); } } return sessions; }
protected Session getSessionForNameAndId(ContextName cn, String id, StringManager smClient) { List<Session> sessions = getSessionsForName(cn, smClient); if (sessions.isEmpty()) return null; for(Session session : sessions) { if (session.getId().equals(id)) { return session; } } return null; }
/** * * @param cn Name of the application for which the sessions will be listed * @param req * @param resp * @param smClient StringManager for the client's locale * @throws ServletException * @throws IOException */ protected void displaySessionsListPage(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForName(cn, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = Collections.reverseOrder(comparator); orderBy = "ASC"; } else { orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); }
/** * * @param req * @param resp * @param smClient StringManager for the client's locale * @throws ServletException * @throws IOException */ protected void displaySessionDetailPage(HttpServletRequest req, HttpServletResponse resp, ContextName cn, String sessionId, StringManager smClient) throws ServletException, IOException { Session session = getSessionForNameAndId(cn, sessionId, smClient); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now req.setAttribute("currentSession", session); getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp); }
/** * Invalidate HttpSessions * @param cn Name of the application for which sessions are to be * invalidated * @param sessionIds * @param smClient StringManager for the client's locale * @return number of invalidated sessions * @throws IOException */ protected int invalidateSessions(ContextName cn, String[] sessionIds, StringManager smClient) throws IOException { if (null == sessionIds) { return 0; } int nbAffectedSessions = 0; for (int i = 0; i < sessionIds.length; ++i) { String sessionId = sessionIds[i]; HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't invalidate null session " + sessionId); } continue; } try { session.invalidate(); ++nbAffectedSessions; if (debug >= 1) { log("Invalidating session id " + sessionId); } } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } } } return nbAffectedSessions; }
/** * Reload the web application at the specified context path. * * @param writer Writer to render to * @param cn Name of the application to be restarted */ protected void reload(PrintWriter writer, ContextName cn, StringManager smClient) { if (debug >= 1) log("restart: Reloading web application '" + cn + "'"); if (!validateContextName(cn, writer, smClient)) { return; } try { Context context = (Context) host.findChild(cn.getName()); if (context == null) { writer.println(smClient.getString("managerServlet.noContext", RequestUtil.filter(cn.getDisplayName()))); return; } // It isn't possible for the manager to reload itself if (context.getName().equals(this.context.getName())) { writer.println(smClient.getString("managerServlet.noSelf")); return; } context.reload(); writer.println(smClient.getString("managerServlet.reloaded", cn.getDisplayName())); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.reload[" + cn.getDisplayName() + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); } }
/** * * Extract the expiration request parameter * * @param cn * @param req */ protected void expireSessions(PrintWriter writer, ContextName cn, HttpServletRequest req, StringManager smClient) { int idle = -1; String idleParam = req.getParameter("idle"); if (idleParam != null) { try { idle = Integer.parseInt(idleParam); } catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); } } sessions(writer, cn, idle, smClient); }
/** * Start the web application at the specified context path. * * @param writer Writer to render to * @param cn Name of the application to be started */ protected void start(PrintWriter writer, ContextName cn, StringManager smClient) { if (debug >= 1) log("start: Starting web application '" + cn + "'"); if (!validateContextName(cn, writer, smClient)) { return; } String displayPath = cn.getDisplayName(); try { Context context = (Context) host.findChild(cn.getName()); if (context == null) { writer.println(smClient.getString("managerServlet.noContext", RequestUtil.filter(displayPath))); return; } context.start(); if (context.getState().isAvailable()) writer.println(smClient.getString("managerServlet.started", displayPath)); else writer.println(smClient.getString("managerServlet.startFailed", displayPath)); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getServletContext().log(sm.getString("managerServlet.startFailed", displayPath), t); writer.println(smClient.getString("managerServlet.startFailed", displayPath)); writer.println(smClient.getString("managerServlet.exception", t.toString())); } }
/** * Stop the web application at the specified context path. * * @param writer Writer to render to * @param cn Name of the application to be stopped */ protected void stop(PrintWriter writer, ContextName cn, StringManager smClient) { if (debug >= 1) log("stop: Stopping web application '" + cn + "'"); if (!validateContextName(cn, writer, smClient)) { return; } String displayPath = cn.getDisplayName(); try { Context context = (Context) host.findChild(cn.getName()); if (context == null) { writer.println(smClient.getString("managerServlet.noContext", RequestUtil.filter(displayPath))); return; } // It isn't possible for the manager to stop itself if (context.getName().equals(this.context.getName())) { writer.println(smClient.getString("managerServlet.noSelf")); return; } context.stop(); writer.println(smClient.getString( "managerServlet.stopped", displayPath)); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(smClient.getString("managerServlet.exception", t.toString())); } }
/** * Deploy applications for any directories or WAR files that are found * in our "application root" directory. */ protected void deployApps(String name) { File appBase = appBase(); File configBase = configBase(); ContextName cn = new ContextName(name, false); String baseName = cn.getBaseName(); if (deploymentExists(cn.getName())) { return; } // Deploy XML descriptor from configBase File xml = new File(configBase, baseName + ".xml"); if (xml.exists()) { deployDescriptor(cn, xml); return; } // Deploy WAR File war = new File(appBase, baseName + ".war"); if (war.exists()) { deployWAR(cn, war); return; } // Deploy expanded folder File dir = new File(appBase, baseName); if (dir.exists()) deployDirectory(cn, dir); }
/** * Deploy XML context descriptors. */ protected void deployDescriptors(File configBase, String[] files) { if (files == null) return; ExecutorService es = host.getStartStopExecutor(); List<Future<?>> results = new ArrayList<Future<?>>(); for (int i = 0; i < files.length; i++) { File contextXml = new File(configBase, files[i]); if (files[i].toLowerCase(Locale.ENGLISH).endsWith(".xml")) { ContextName cn = new ContextName(files[i], true); if (isServiced(cn.getName()) || deploymentExists(cn.getName())) continue; results.add( es.submit(new DeployDescriptor(this, cn, contextXml))); } } for (Future<?> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.threaded.error"), e); } } }
/** * Deploy directories. */ protected void deployDirectories(File appBase, String[] files) { if (files == null) return; ExecutorService es = host.getStartStopExecutor(); List<Future<?>> results = new ArrayList<Future<?>>(); for (int i = 0; i < files.length; i++) { if (files[i].equalsIgnoreCase("META-INF")) continue; if (files[i].equalsIgnoreCase("WEB-INF")) continue; File dir = new File(appBase, files[i]); if (dir.isDirectory()) { ContextName cn = new ContextName(files[i], false); if (isServiced(cn.getName()) || deploymentExists(cn.getName())) continue; results.add(es.submit(new DeployDirectory(this, cn, dir))); } } for (Future<?> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDir.threaded.error"), e); } } }
/** * Calculate the key properties string to be added to an object's * {@link ObjectName} to indicate that it is associated with that container. * * @param container The container the object is associated with * @return A string suitable for appending to the ObjectName * @deprecated To be removed since to creates a circular dependency. Will * be replaced in Tomcat 8 by a new method on {@link * Container}. */ @Deprecated public static String getContainerKeyProperties(Container container) { Container c = container; StringBuilder keyProperties = new StringBuilder(); int containerCount = 0; // Work up container hierarchy, add a component to the name for // each container while (!(c instanceof Engine)) { if (c instanceof Wrapper) { keyProperties.append(",servlet="); keyProperties.append(c.getName()); } else if (c instanceof Context) { keyProperties.append(",context="); ContextName cn = new ContextName(c.getName(), false); keyProperties.append(cn.getDisplayName()); } else if (c instanceof Host) { keyProperties.append(",host="); keyProperties.append(c.getName()); } else if (c == null) { // May happen in unit testing and/or some embedding scenarios keyProperties.append(",container"); keyProperties.append(containerCount++); keyProperties.append("=null"); break; } else { // Should never happen... keyProperties.append(",container"); keyProperties.append(containerCount++); keyProperties.append('='); keyProperties.append(c.getName()); } c = c.getParent(); } return keyProperties.toString(); }
/** * 部署文件目录 * Deploy directories. */ protected void deployDirectories(File appBase, String[] files) { if (files == null) return; ExecutorService es = host.getStartStopExecutor(); List<Future<?>> results = new ArrayList<Future<?>>(); for (int i = 0; i < files.length; i++) { if (files[i].equalsIgnoreCase("META-INF")) continue; if (files[i].equalsIgnoreCase("WEB-INF")) continue; File dir = new File(appBase, files[i]); if (dir.isDirectory()) { ContextName cn = new ContextName(files[i], false); if (isServiced(cn.getName()) || deploymentExists(cn.getName())) continue; results.add(es.submit(new DeployDirectory(this, cn, dir))); } } for (Future<?> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDir.threaded.error"), e); } } }