Java Code Examples for org.apache.catalina.connector.Request#getContext()

The following examples show how to use org.apache.catalina.connector.Request#getContext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JvmRouteBinderValve.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Detect possible the JVMRoute change at cluster backup node..
 *
 * @param request
 *            tomcat request being processed
 * @param response
 *            tomcat response being processed
 * @exception IOException
 *                if an input/output error has occurred
 * @exception ServletException
 *                if a servlet error has occurred
 */
@Override
public void invoke(Request request, Response response) throws IOException,
        ServletException {

     if (getEnabled() &&
             request.getContext() != null &&
             request.getContext().getDistributable() &&
             !request.isAsyncDispatching()) {
         // valve cluster can access manager - other cluster handle turnover
         // at host level - hopefully!
         Manager manager = request.getContext().getManager();

         if (manager != null && (
                 (manager instanceof ClusterManager
                   && getCluster() != null
                   && getCluster().getManager(((ClusterManager)manager).getName()) != null)
                 ||
                 (manager instanceof PersistentManager))) {
            handlePossibleTurnover(request);
        }
    }
    // Pass this request on to the next valve in our pipeline
    getNext().invoke(request, response);
}
 
Example 2
Source File: JvmRouteBinderValve.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Detect possible the JVMRoute change at cluster backup node..
 * 
 * @param request
 *            tomcat request being processed
 * @param response
 *            tomcat response being processed
 * @exception IOException
 *                if an input/output error has occurred
 * @exception ServletException
 *                if a servlet error has occurred
 */
@Override
public void invoke(Request request, Response response) throws IOException,
        ServletException {

     if (getEnabled() &&
             request.getContext() != null &&
             request.getContext().getDistributable() &&
             !request.isAsyncDispatching()) {
         // valve cluster can access manager - other cluster handle turnover 
         // at host level - hopefully!
         Manager manager = request.getContext().getManager();

         if (manager != null && (
                 (manager instanceof ClusterManager
                   && getCluster() != null
                   && getCluster().getManager(((ClusterManager)manager).getName()) != null)
                 ||
                 (manager instanceof PersistentManager)))
             handlePossibleTurnover(request);
    }
    // Pass this request on to the next valve in our pipeline
    getNext().invoke(request, response);
}
 
Example 3
Source File: JvmRouteBinderValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Detect possible the JVMRoute change at cluster backup node..
 * 
 * @param request
 *            tomcat request being processed
 * @param response
 *            tomcat response being processed
 * @exception IOException
 *                if an input/output error has occurred
 * @exception ServletException
 *                if a servlet error has occurred
 */
@Override
public void invoke(Request request, Response response) throws IOException,
        ServletException {

     if (getEnabled() &&
             request.getContext() != null &&
             request.getContext().getDistributable() &&
             !request.isAsyncDispatching()) {
         // valve cluster can access manager - other cluster handle turnover 
         // at host level - hopefully!
         Manager manager = request.getContext().getManager();

         if (manager != null && (
                 (manager instanceof ClusterManager
                   && getCluster() != null
                   && getCluster().getManager(((ClusterManager)manager).getName()) != null)
                 ||
                 (manager instanceof PersistentManager)))
             handlePossibleTurnover(request);
    }
    // Pass this request on to the next valve in our pipeline
    getNext().invoke(request, response);
}
 
Example 4
Source File: WebappAuthenticationValve.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private boolean isContextSkipped(Request request) {
    Context context = request.getContext();
    String ctx = context == null ? null :context.getPath();
    if (ctx == null || "".equals(ctx)) {
        ctx = request.getContextPath();
        if (ctx == null || "".equals(ctx)) {
            String requestUri = request.getRequestURI();
            if ("/".equals(requestUri)) {
                return true;
            }
            StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/");
            if (!tokenizer.hasMoreTokens()) {
                return false;
            }
            ctx = tokenizer.nextToken();
        }
    }
    return ("carbon".equalsIgnoreCase(ctx) || "services".equalsIgnoreCase(ctx));
}
 
Example 5
Source File: RedisSessionRequestValve.java    From redis-session-manager with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    Context context = request.getContext();
    if (context == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext"));
        return;
    }
    Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());

    boolean processed = false;
    try {
        if (ignorePattern == null || !ignorePattern.matcher(request.getRequestURI()).matches()) {
            processed = true;
            if (log.isTraceEnabled()) {
                log.trace("Will save to redis after request for [" + getQueryString(request) + "]");
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Ignoring [" + getQueryString(request) + "]");
            }
        }
        getNext().invoke(request, response);
    } finally {
        manager.afterRequest(processed);
    }
}
 
Example 6
Source File: RequestFilterValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Reject the request that was denied by this valve.
 * <p>If <code>invalidAuthenticationWhenDeny</code> is true
 * and the context has <code>preemptiveAuthentication</code>
 * set, set an invalid authorization header to trigger basic auth.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be processed
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void denyRequest(Request request, Response response)
        throws IOException, ServletException {
    if (invalidAuthenticationWhenDeny) {
        Context context = request.getContext();
        if (context != null && context.getPreemptiveAuthentication()) {
            if (request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) {
                request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid");
            }
            getNext().invoke(request, response);
            return;
        }
    }
    response.sendError(denyStatus);
}
 
Example 7
Source File: JvmRouteBinderValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Send the changed Sessionid to all clusternodes.
 * 
 * @see JvmRouteSessionIDBinderListener#messageReceived(
 *            org.apache.catalina.ha.ClusterMessage)
 * @param sessionId
 *            current failed sessionid
 * @param newSessionID
 *            new session id, bind to the new cluster node
 */
protected void sendSessionIDClusterBackup(Request request, String sessionId,
        String newSessionID) {
    CatalinaCluster c = getCluster();
    if (c != null && !(getManager(request) instanceof BackupManager)) {
        SessionIDMessage msg = new SessionIDMessage();
        msg.setOrignalSessionID(sessionId);
        msg.setBackupSessionID(newSessionID);
        Context context = request.getContext();
        msg.setContextName(context.getName());
        msg.setHost(context.getParent().getName());
        c.send(msg);
    }
}
 
Example 8
Source File: RequestFilterValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Reject the request that was denied by this valve.
 * <p>If <code>invalidAuthenticationWhenDeny</code> is true
 * and the context has <code>preemptiveAuthentication</code>
 * set, set an invalid authorization header to trigger basic auth.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be processed
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void denyRequest(Request request, Response response)
        throws IOException, ServletException {
    if (invalidAuthenticationWhenDeny) {
        Context context = request.getContext();
        if (context != null && context.getPreemptiveAuthentication()) {
            if (request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) {
                request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid");
            }
            getNext().invoke(request, response);
            return;
        }
    }
    response.sendError(denyStatus);
}
 
Example 9
Source File: JvmRouteBinderValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Send the changed Sessionid to all clusternodes.
 * 
 * @see JvmRouteSessionIDBinderListener#messageReceived(
 *            org.apache.catalina.ha.ClusterMessage)
 * @param sessionId
 *            current failed sessionid
 * @param newSessionID
 *            new session id, bind to the new cluster node
 */
protected void sendSessionIDClusterBackup(Request request, String sessionId,
        String newSessionID) {
    CatalinaCluster c = getCluster();
    if (c != null && !(getManager(request) instanceof BackupManager)) {
        SessionIDMessage msg = new SessionIDMessage();
        msg.setOrignalSessionID(sessionId);
        msg.setBackupSessionID(newSessionID);
        Context context = request.getContext();
        msg.setContextName(context.getName());
        msg.setHost(context.getParent().getName());
        c.send(msg);
    }
}
 
Example 10
Source File: RequestFilterValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Reject the request that was denied by this valve.
 * <p>If <code>invalidAuthenticationWhenDeny</code> is true
 * and the context has <code>preemptiveAuthentication</code>
 * set, set an invalid authorization header to trigger basic auth.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be processed
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void denyRequest(Request request, Response response)
        throws IOException, ServletException {
    if (invalidAuthenticationWhenDeny) {
        Context context = request.getContext();
        if (context != null && context.getPreemptiveAuthentication()) {
            if (request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) {
                request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid");
            }
            getNext().invoke(request, response);
            return;
        }
    }
    response.sendError(denyStatus);
}
 
Example 11
Source File: DatastoreValve.java    From tomcat-runtime with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * <p>If the manager contain a store, use it to persist the session at the end of the request.</p>
 */
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {

  log.debug("Processing request with session:" + request.getRequestedSessionId());

  getNext().invoke(request, response);

  Context context = request.getContext();
  Manager manager = context.getManager();

  Session session = request.getSessionInternal(false);
  if (session != null && !isUriExcluded(request.getRequestURI())) {
    log.debug("Persisting session with id: " + session.getId());
    session.access();
    session.endAccess();

    if (manager instanceof StoreManager) {
      StoreManager storeManager = (StoreManager) manager;
      storeManager.getStore().save(session);
      storeManager.removeSuper(session);
    } else {
      log.error("In order to persist the session the manager must implement StoreManager");
    }
  } else {
    log.debug("Session not persisted (Non existent or the URI is ignored)");
  }

}
 
Example 12
Source File: ReplicationValve.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Log the interesting request parameters, invoke the next Valve in the
 * sequence, and log the interesting response parameters.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response)
    throws IOException, ServletException
{
    long totalstart = 0;

    //this happens before the request
    if(doStatistics()) {
        totalstart = System.currentTimeMillis();
    }
    if (primaryIndicator) {
        createPrimaryIndicator(request) ;
    }
    Context context = request.getContext();
    boolean isCrossContext = context != null
            && context instanceof StandardContext
            && ((StandardContext) context).getCrossContext();
    try {
        if(isCrossContext) {
            if(log.isDebugEnabled()) {
                log.debug(sm.getString("ReplicationValve.crossContext.add"));
            }
            //FIXME add Pool of Arraylists
            crossContextSessions.set(new ArrayList<DeltaSession>());
        }
        getNext().invoke(request, response);
        if(context != null && cluster != null
                && context.getManager() instanceof ClusterManager) {
            ClusterManager clusterManager = (ClusterManager) context.getManager();

            // valve cluster can access manager - other cluster handle replication
            // at host level - hopefully!
            if(cluster.getManager(clusterManager.getName()) == null) {
                return ;
            }
            if(cluster.hasMembers()) {
                sendReplicationMessage(request, totalstart, isCrossContext, clusterManager);
            } else {
                resetReplicationRequest(request,isCrossContext);
            }
        }
    } finally {
        // Array must be remove: Current master request send endAccess at recycle.
        // Don't register this request session again!
        if(isCrossContext) {
            if(log.isDebugEnabled()) {
                log.debug(sm.getString("ReplicationValve.crossContext.remove"));
            }
            // crossContextSessions.remove() only exist at Java 5
            // register ArrayList at a pool
            crossContextSessions.set(null);
        }
    }
}
 
Example 13
Source File: ApplicationPushBuilder.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public ApplicationPushBuilder(Request catalinaRequest, HttpServletRequest request) {

        baseRequest = request;
        this.catalinaRequest = catalinaRequest;
        coyoteRequest = catalinaRequest.getCoyoteRequest();

        // Populate the initial list of HTTP headers
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> values = new ArrayList<>();
            headers.put(headerName, values);
            Enumeration<String> headerValues = request.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                values.add(headerValues.nextElement());
            }
        }

        // Remove the headers
        headers.remove("if-match");
        headers.remove("if-none-match");
        headers.remove("if-modified-since");
        headers.remove("if-unmodified-since");
        headers.remove("if-range");
        headers.remove("range");
        headers.remove("expect");
        headers.remove("authorization");
        headers.remove("referer");
        // Also remove the cookie header since it will be regenerated
        headers.remove("cookie");

        // set the referer header
        StringBuffer referer = request.getRequestURL();
        if (request.getQueryString() != null) {
            referer.append('?');
            referer.append(request.getQueryString());
        }
        addHeader("referer", referer.toString());

        // Session
        Context context = catalinaRequest.getContext();
        sessionCookieName = SessionConfig.getSessionCookieName(context);
        sessionPathParameterName = SessionConfig.getSessionUriParamName(context);

        HttpSession session = request.getSession(false);
        if (session != null) {
            sessionId = session.getId();
        }
        if (sessionId == null) {
            sessionId = request.getRequestedSessionId();
        }
        if (!request.isRequestedSessionIdFromCookie() && !request.isRequestedSessionIdFromURL() &&
                sessionId != null) {
            Set<SessionTrackingMode> sessionTrackingModes =
                    request.getServletContext().getEffectiveSessionTrackingModes();
            addSessionCookie = sessionTrackingModes.contains(SessionTrackingMode.COOKIE);
            addSessionPathParameter = sessionTrackingModes.contains(SessionTrackingMode.URL);
        } else {
            addSessionCookie = request.isRequestedSessionIdFromCookie();
            addSessionPathParameter = request.isRequestedSessionIdFromURL();
        }

        // Cookies
        if (request.getCookies() != null) {
            for (Cookie requestCookie : request.getCookies()) {
                cookies.add(requestCookie);
            }
        }
        for (Cookie responseCookie : catalinaRequest.getResponse().getCookies()) {
            if (responseCookie.getMaxAge() < 0) {
                // Path information not available so can only remove based on
                // name.
                Iterator<Cookie> cookieIterator = cookies.iterator();
                while (cookieIterator.hasNext()) {
                    Cookie cookie = cookieIterator.next();
                    if (cookie.getName().equals(responseCookie.getName())) {
                        cookieIterator.remove();
                    }
                }
            } else {
                cookies.add(new Cookie(responseCookie.getName(), responseCookie.getValue()));
            }
        }
        List<String> cookieValues = new ArrayList<>(1);
        cookieValues.add(generateCookieHeader(cookies,
                catalinaRequest.getContext().getCookieProcessor()));
        headers.put("cookie", cookieValues);

        // Authentication
        if (catalinaRequest.getPrincipal() != null) {
            if ((session == null) || catalinaRequest.getSessionInternal(false).getPrincipal() == null
                    || !(context.getAuthenticator() instanceof AuthenticatorBase)
                    || !((AuthenticatorBase) context.getAuthenticator()).getCache()) {
                // Set a username only if there is no session cache for the principal
                userName = catalinaRequest.getPrincipal().getName();
            }
            setHeader("authorization", "x-push");
        }
    }
 
Example 14
Source File: ReplicationValve.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Log the interesting request parameters, invoke the next Valve in the
 * sequence, and log the interesting response parameters.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response)
    throws IOException, ServletException
{
    long totalstart = 0;

    //this happens before the request
    if(doStatistics()) {
        totalstart = System.currentTimeMillis();
    }
    if (primaryIndicator) {
        createPrimaryIndicator(request) ;
    }
    Context context = request.getContext();
    boolean isCrossContext = context != null
            && context instanceof StandardContext
            && ((StandardContext) context).getCrossContext();
    try {
        if(isCrossContext) {
            if(log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.crossContext.add"));
            //FIXME add Pool of Arraylists
            crossContextSessions.set(new ArrayList<DeltaSession>());
        }
        getNext().invoke(request, response);
        if(context != null && cluster != null
                && context.getManager() instanceof ClusterManager) {
            ClusterManager clusterManager = (ClusterManager) context.getManager();

            // valve cluster can access manager - other cluster handle replication 
            // at host level - hopefully!
            if(cluster.getManager(clusterManager.getName()) == null)
                return ;
            if(cluster.hasMembers()) {
                sendReplicationMessage(request, totalstart, isCrossContext, clusterManager, cluster);
            } else {
                resetReplicationRequest(request,isCrossContext);
            }        
        }
    } finally {
        // Array must be remove: Current master request send endAccess at recycle. 
        // Don't register this request session again!
        if(isCrossContext) {
            if(log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.crossContext.remove"));
            // crossContextSessions.remove() only exist at Java 5
            // register ArrayList at a pool
            crossContextSessions.set(null);
        }
    }
}
 
Example 15
Source File: ReplicationValve.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Log the interesting request parameters, invoke the next Valve in the
 * sequence, and log the interesting response parameters.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response)
    throws IOException, ServletException
{
    long totalstart = 0;

    //this happens before the request
    if(doStatistics()) {
        totalstart = System.currentTimeMillis();
    }
    if (primaryIndicator) {
        createPrimaryIndicator(request) ;
    }
    Context context = request.getContext();
    boolean isCrossContext = context != null
            && context instanceof StandardContext
            && ((StandardContext) context).getCrossContext();
    try {
        if(isCrossContext) {
            if(log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.crossContext.add"));
            //FIXME add Pool of Arraylists
            crossContextSessions.set(new ArrayList<DeltaSession>());
        }
        getNext().invoke(request, response);
        if(context != null && cluster != null
                && context.getManager() instanceof ClusterManager) {
            ClusterManager clusterManager = (ClusterManager) context.getManager();

            // valve cluster can access manager - other cluster handle replication 
            // at host level - hopefully!
            if(cluster.getManager(clusterManager.getName()) == null)
                return ;
            if(cluster.hasMembers()) {
                sendReplicationMessage(request, totalstart, isCrossContext, clusterManager, cluster);
            } else {
                resetReplicationRequest(request,isCrossContext);
            }        
        }
    } finally {
        // Array must be remove: Current master request send endAccess at recycle. 
        // Don't register this request session again!
        if(isCrossContext) {
            if(log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.crossContext.remove"));
            // crossContextSessions.remove() only exist at Java 5
            // register ArrayList at a pool
            crossContextSessions.set(null);
        }
    }
}