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; }
protected Session[] getSessionsForPath(String path) { if ((path == null) || (!path.startsWith("/") && path.equals(""))) { throw new IllegalArgumentException(sm.getString("managerServlet.invalidPath", RequestUtil.filter(path))); } String displayPath = path; if( path.equals("/") ) path = ""; Context context = (Context) host.findChild(path); if (null == context) { throw new IllegalArgumentException(sm.getString("managerServlet.noContext", RequestUtil.filter(displayPath))); } Session[] sessions = context.getManager().findSessions(); return sessions; }
protected Session getSessionForPathAndId(String path, String id) throws IOException { if ((path == null) || (!path.startsWith("/") && path.equals(""))) { throw new IllegalArgumentException(sm.getString("managerServlet.invalidPath", RequestUtil.filter(path))); } String displayPath = path; if( path.equals("/") ) path = ""; Context context = (Context) host.findChild(path); if (null == context) { throw new IllegalArgumentException(sm.getString("managerServlet.noContext", RequestUtil.filter(displayPath))); } Session session = context.getManager().findSession(id); return session; }
/** * Return the requested resource as an <code>InputStream</code>. The * path must be specified according to the rules described under * <code>getResource</code>. If no such resource can be identified, * return <code>null</code>. * * @param path The path to the desired resource. */ public InputStream getResourceAsStream(String path) { if (path == null || (Globals.STRICT_SERVLET_COMPLIANCE && !path.startsWith("/"))) return (null); path = RequestUtil.normalize(path); if (path == null) return (null); DirContext resources = context.getResources(); if (resources != null) { try { Object resource = resources.lookup(path); if (resource instanceof Resource) return (((Resource) resource).streamContent()); } catch (Exception e) { } } return (null); }
/** * Return a Set containing the resource paths of resources member of the * specified collection. Each path will be a String starting with * a "/" character. The returned set is immutable. * * @param path Collection path */ public Set getResourcePaths(String path) { // Validate the path argument if (path == null) { return null; } if (!path.startsWith("/")) { throw new IllegalArgumentException (sm.getString("applicationContext.resourcePaths.iae", path)); } path = RequestUtil.normalize(path); if (path == null) return (null); DirContext resources = context.getResources(); if (resources != null) { return (getResourcePathsInternal(resources, path)); } return (null); }
/** * Set the content type for this Response. * * @param type The new content type */ public void setContentType(String type) { if (isCommitted()) return; if (included) return; // Ignore any call from an included servlet this.contentType = type; if (type.indexOf(';') >= 0) { encoding = RequestUtil.parseCharacterEncoding(type); if (encoding == null) encoding = "ISO-8859-1"; } else { if (encoding != null) this.contentType = type + ";charset=" + encoding; } }
/** * Return a context-relative path, beginning with a "/", that represents * the canonical version of the specified path after ".." and "." elements * are resolved out. If the specified path attempts to go outside the * boundaries of the current context (i.e. too many ".." path elements * are present), return <code>null</code> instead. * * This normalize should be the same as DefaultServlet.normalize, which is almost the same * ( see source code below ) as RequestUtil.normalize. Do we need all this duplication? * * @param path Path to be normalized */ public static String normalize(String path) { if (path == null) return null; String normalized = path; //Why doesn't RequestUtil do this?? // Normalize the slashes and add leading slash if necessary if ( normalized.indexOf('\\') >= 0 ) normalized = normalized.replace( '\\', '/' ); normalized = RequestUtil.normalize( path ); return normalized; }
/** * Add a new servlet mapping, replacing any existing mapping for * the specified pattern. * * @param pattern URL pattern to be mapped * @param name Name of the corresponding servlet to execute * * @exception IllegalArgumentException if the specified servlet name * is not known to this Context */ public void addServletMapping(String pattern, String name) { // Validate the proposed mapping if (findChild(name) == null) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.name", name)); pattern = adjustURLPattern(RequestUtil.URLDecode(pattern)); if (!validateURLPattern(pattern)) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.pattern", pattern)); // Add this mapping to our registered set synchronized (servletMappings) { servletMappings.put(pattern, name); } fireContainerEvent("addServletMapping", pattern); }
/** * Merge the parameters from the saved query parameter string (if any), and * the parameters already present on this request (if any), such that the * parameter values from the query string show up first if there are * duplicate parameter names. */ private void mergeParameters() { if ((queryParamString == null) || (queryParamString.length() < 1)) return; HashMap<String, String[]> queryParameters = new HashMap<String, String[]>(); String encoding = getCharacterEncoding(); if (encoding == null) encoding = "ISO-8859-1"; RequestUtil.parseParameters(queryParameters, queryParamString, encoding); Iterator<String> keys = parameters.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Object value = queryParameters.get(key); if (value == null) { queryParameters.put(key, parameters.get(key)); continue; } queryParameters.put (key, mergeValues(value, parameters.get(key))); } parameters = queryParameters; }
/** * Read all parameters directly from the input stream. Necessary because parameters are not mapped to the * HttpRequest.getParameter api on PUT requests * @param req * @param params */ private void parseStreamParameters(HttpServletRequest req, Map<String, List<String>> params) { try { String content = this.convertStreamToString(req.getInputStream()); if( content != null && content.length() >= 1 ){ Map<String, String[]> ps = new HashMap<String, String[]>(); RequestUtil.parseParameters(ps, content, "UTF-8"); for (String key : ps.keySet()) { List<String> param = new ArrayList<String>(); for(String value : ps.get(key)) { param.add(value); } params.put(key, param); } } } catch (IOException e) { throw new InputException(e); } }
/** * Return a Set containing the resource paths of resources member of the * specified collection. Each path will be a String starting with * a "/" character. The returned set is immutable. * * @param path Collection path */ @Override public Set<String> getResourcePaths(String path) { // Validate the path argument if (path == null) { return null; } if (!path.startsWith("/")) { throw new IllegalArgumentException (sm.getString("applicationContext.resourcePaths.iae", path)); } String normalizedPath = RequestUtil.normalize(path); if (normalizedPath == null) return (null); DirContext resources = context.getResources(); if (resources != null) { return (getResourcePathsInternal(resources, normalizedPath)); } return (null); }
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; }
/** * 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())); } }
/** * 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())); } }
/** * Internal method that allows a redirect to be sent with a status other * than {@link HttpServletResponse#SC_FOUND} (302). No attempt is made to * validate the status code. */ public void sendRedirect(String location, int status) throws IOException { if (isCommitted()) { throw new IllegalStateException(sm.getString("coyoteResponse.sendRedirect.ise")); } // Ignore any call from an included servlet if (included) { return; } // Clear any data content that has been buffered resetBuffer(true); // Generate a temporary redirect to the specified location try { String locationUri; // Relative redirects require HTTP/1.1 if (getRequest().getCoyoteRequest().getSupportsRelativeRedirects() && getContext().getUseRelativeRedirects()) { locationUri = location; } else { locationUri = toAbsolute(location); } setStatus(status); setHeader("Location", locationUri); if (getContext().getSendRedirectBody()) { PrintWriter writer = getWriter(); writer.print(sm.getString("coyoteResponse.sendRedirect.note", RequestUtil.filter(locationUri))); flushBuffer(); } } catch (IllegalArgumentException e) { log.warn(sm.getString("response.sendRedirectFail", location), e); setStatus(SC_NOT_FOUND); } // Cause the response to be finished (from the application perspective) setSuspended(true); }
public void addURLPattern(String urlPattern) { if ("*".equals(urlPattern)) { this.matchAllUrlPatterns = true; } else { String[] results = new String[urlPatterns.length + 1]; System.arraycopy(urlPatterns, 0, results, 0, urlPatterns.length); results[urlPatterns.length] = RequestUtil.URLDecode(urlPattern); urlPatterns = results; } }
/** * Set the location. * * @param location The new location */ public void setLocation(String location) { // if ((location == null) || !location.startsWith("/")) // throw new IllegalArgumentException // ("Error Page Location must start with a '/'"); this.location = RequestUtil.URLDecode(location); }
/** * Add a URL pattern to be part of this web resource collection. */ public void addPattern(String pattern) { if (pattern == null) return; String decodedPattern = RequestUtil.URLDecode(pattern); String results[] = new String[patterns.length + 1]; for (int i = 0; i < patterns.length; i++) { results[i] = patterns[i]; } results[patterns.length] = decodedPattern; patterns = results; }
/** * Reload the web application at the specified context path. * * @param writer Writer to render to * @param path Context path of the application to be restarted */ protected void reload(PrintWriter writer, String path) { if (debug >= 1) log("restart: Reloading web application at '" + path + "'"); if ((path == null) || (!path.startsWith("/") && path.equals(""))) { writer.println(sm.getString("managerServlet.invalidPath", RequestUtil.filter(path))); return; } String displayPath = path; if( path.equals("/") ) path = ""; try { Context context = (Context) host.findChild(path); if (context == null) { writer.println(sm.getString ("managerServlet.noContext", RequestUtil.filter(displayPath))); return; } // It isn't possible for the manager to reload itself if (context.getPath().equals(this.context.getPath())) { writer.println(sm.getString("managerServlet.noSelf")); return; } context.reload(); writer.println (sm.getString("managerServlet.reloaded", displayPath)); } catch (Throwable t) { log("ManagerServlet.reload[" + displayPath + "]", t); writer.println(sm.getString("managerServlet.exception", t.toString())); } }
/** * Start the web application at the specified context path. * * @param writer Writer to render to * @param path Context path of the application to be started */ protected void start(PrintWriter writer, String path) { if (debug >= 1) log("start: Starting web application at '" + path + "'"); if ((path == null) || (!path.startsWith("/") && path.equals(""))) { writer.println(sm.getString("managerServlet.invalidPath", RequestUtil.filter(path))); return; } String displayPath = path; if( path.equals("/") ) path = ""; try { Context context = (Context) host.findChild(path); if (context == null) { writer.println(sm.getString("managerServlet.noContext", RequestUtil.filter(displayPath))); return; } ((Lifecycle) context).start(); if (context.getAvailable()) writer.println (sm.getString("managerServlet.started", displayPath)); else writer.println (sm.getString("managerServlet.startFailed", displayPath)); } catch (Throwable t) { getServletContext().log (sm.getString("managerServlet.startFailed", displayPath), t); writer.println (sm.getString("managerServlet.startFailed", displayPath)); writer.println(sm.getString("managerServlet.exception", t.toString())); } }
/** * Stop the web application at the specified context path. * * @param writer Writer to render to * @param path Context path of the application to be stopped */ protected void stop(PrintWriter writer, String path) { if (debug >= 1) log("stop: Stopping web application at '" + path + "'"); if ((path == null) || (!path.startsWith("/") && path.equals(""))) { writer.println(sm.getString("managerServlet.invalidPath", RequestUtil.filter(path))); return; } String displayPath = path; if( path.equals("/") ) path = ""; try { Context context = (Context) host.findChild(path); if (context == null) { writer.println(sm.getString("managerServlet.noContext", RequestUtil.filter(displayPath))); return; } // It isn't possible for the manager to stop itself if (context.getPath().equals(this.context.getPath())) { writer.println(sm.getString("managerServlet.noSelf")); return; } ((Lifecycle) context).stop(); writer.println(sm.getString("managerServlet.stopped", displayPath)); } catch (Throwable t) { log("ManagerServlet.stop[" + displayPath + "]", t); writer.println(sm.getString("managerServlet.exception", t.toString())); } }
/** * Add a URL pattern to be part of this web resource collection. */ public void addPattern(String pattern) { if (pattern == null) return; pattern = RequestUtil.URLDecode(pattern); String results[] = new String[patterns.length + 1]; for (int i = 0; i < patterns.length; i++) { results[i] = patterns[i]; } results[patterns.length] = pattern; patterns = results; }
/** * Return the SecurityConstraints configured to guard the request URI for * this request, or <code>null</code> if there is no such constraint. * * @param request Request we are processing * @param context Context the Request is mapped to */ public SecurityConstraint [] findSecurityConstraints(Request request, Context context) { ArrayList<SecurityConstraint> results = null; // Are there any defined security constraints? SecurityConstraint constraints[] = context.findConstraints(); if ((constraints == null) || (constraints.length == 0)) { if (context.getLogger().isDebugEnabled()) context.getLogger().debug(" No applicable constraints defined"); return (null); } // Check each defined security constraint String uri = request.getDecodedRequestURI(); String contextPath = request.getContextPath(); if (contextPath.length() > 0) uri = uri.substring(contextPath.length()); uri = RequestUtil.URLDecode(uri); // Before checking constraints String method = request.getMethod(); for (int i = 0; i < constraints.length; i++) { if (context.getLogger().isDebugEnabled()) context.getLogger().debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); if (constraints[i].included(uri, method)) { if(results == null) { results = new ArrayList<SecurityConstraint>(); } results.add(constraints[i]); } } // No applicable security constraint was found if (context.getLogger().isDebugEnabled()) context.getLogger().debug(" No applicable constraint located"); if(results == null) return null; SecurityConstraint [] array = new SecurityConstraint[results.size()]; System.arraycopy(results.toArray(), 0, array, 0, array.length); return array; }
/** * Merge the parameters from the saved query parameter string (if any), and * the parameters already present on this request (if any), such that the * parameter values from the query string show up first if there are * duplicate parameter names. */ private void mergeParameters() { if ((queryParamString == null) || (queryParamString.length() < 1)) return; HashMap queryParameters = new HashMap(); String encoding = getCharacterEncoding(); if (encoding == null) encoding = "ISO-8859-1"; try { RequestUtil.parseParameters (queryParameters, queryParamString, encoding); } catch (Exception e) { ; } Iterator keys = parameters.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); Object value = queryParameters.get(key); if (value == null) { queryParameters.put(key, parameters.get(key)); continue; } queryParameters.put (key, mergeValues(value, parameters.get(key))); } parameters = queryParameters; }
/** * Return a RequestDispatcher that wraps the resource at the specified * path, which may be interpreted as relative to the current request path. * * @param path Path of the resource to be wrapped */ public RequestDispatcher getRequestDispatcher(String path) { if (context == null) return (null); // If the path is already context-relative, just pass it through if (path == null) return (null); else if (path.startsWith("/")) return (context.getServletContext().getRequestDispatcher(path)); // Convert a request-relative path to a context-relative one String servletPath = (String) getAttribute(Globals.SERVLET_PATH_ATTR); if (servletPath == null) servletPath = getServletPath(); int pos = servletPath.lastIndexOf('/'); String relative = null; if (pos >= 0) { relative = RequestUtil.normalize (servletPath.substring(0, pos + 1) + path); } else { relative = RequestUtil.normalize(servletPath + path); } return (context.getServletContext().getRequestDispatcher(relative)); }
/** * Set the content type (and optionally the character encoding) * associated with this Request. For example, * <code>text/html; charset=ISO-8859-4</code>. * * @param type The new content type */ public void setContentType(String type) { this.contentType = type; if (type.indexOf(';') >= 0) characterEncoding = RequestUtil.parseCharacterEncoding(type); }