org.apache.catalina.connector.Response Java Examples

The following examples show how to use org.apache.catalina.connector.Response. 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: InstanceCustomizerTest.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
@Test
public void instanceCustomizer() throws IOException {
    try (final Meecrowave meecrowave = new Meecrowave(new Meecrowave.Builder()
            .randomHttpPort()
            .instanceCustomizer(t -> t.getHost().getPipeline().addValve(new ValveBase() {
                @Override
                public void invoke(final Request request, final Response response) throws IOException, ServletException {
                    response.getWriter().write("custom");
                }
            }))
            .includePackages(InstanceCustomizerTest.class.getName())).bake()) {
        try (final InputStream stream = new URL("http://localhost:" + meecrowave.getConfiguration().getHttpPort() + "/whatever").openStream()) {
            assertEquals("custom", Streams.asString(stream, "UTF-8"));
        }
    }
}
 
Example #2
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 #3
Source File: MongoAccessLogValve.java    From tomcat-mongo-access-log with Apache License 2.0 6 votes vote down vote up
@Override
public void addElement(StringBuilder buf, DBObject result, Date date, Request request,
        Response response, long time) {
    if (millis) {
        result.put("elapsedMillis", time);
    } else {
        // second
        buf.append(time / 1000);
        buf.append('.');
        int remains = (int) (time % 1000);
        buf.append(remains / 100);
        remains = remains % 100;
        buf.append(remains / 10);
        buf.append(remains % 10);
        result.put("elapsedSeconds", Double.valueOf(buf.toString()));
        buf.delete(0, buf.length());
    }
}
 
Example #4
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 #5
Source File: ExtendedAccessLogValve.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    if (null != response) {
        Iterator<String> iter = response.getHeaders(header).iterator();
        if (iter.hasNext()) {
            StringBuilder buffer = new StringBuilder();
            boolean first = true;
            while (iter.hasNext()) {
                if (first) {
                    first = false;
                } else {
                    buffer.append(",");
                }
                buffer.append(iter.next());
            }
            buf.append(wrap(buffer.toString()));
        }
        return ;
    }
    buf.append("-");
}
 
Example #6
Source File: WebappAuthenticationValveTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This method tests the behaviour of the invoke method of WebAuthenticationValve when "
        + "secured endpoints are invoked.")
public void testInvokeSecuredEndpoints() throws NoSuchFieldException, IllegalAccessException {
    String encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER).getBytes()));
    Request request = createRequest("basic " + encodedString);
    webappAuthenticationValve.invoke(request, null, compositeValve);
    encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER + "test").getBytes()));
    request = createRequest("basic " + encodedString);
    Response response = new Response();
    org.apache.coyote.Response coyoteResponse = new org.apache.coyote.Response();
    Connector connector = new Connector();
    response.setConnector(connector);
    response.setCoyoteResponse(coyoteResponse);
    webappAuthenticationValve.invoke(request, response, compositeValve);
    Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED,
            "Response of un-authorized request is not updated");
}
 
Example #7
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 #8
Source File: ContainerBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Check this container for an access log and if none is found, look to the
 * parent. If there is no parent and still none is found, use the NoOp
 * access log.
 */
@Override
public void logAccess(Request request, Response response, long time,
        boolean useDefault) {

    boolean logged = false;

    if (getAccessLog() != null) {
        getAccessLog().log(request, response, time);
        logged = true;
    }

    if (getParent() != null) {
        // No need to use default logger once request/response has been logged
        // once
        getParent().logAccess(request, response, time, (useDefault && !logged));
    }
}
 
Example #9
Source File: SessionFlushValve.java    From session-managers with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(final Request request, final Response response) {
    this.lockTemplate.withReadLock(new LockTemplate.LockedOperation<Void>() {

        @Override
        public Void invoke() throws IOException, ServletException {
            try {
                SessionFlushValve.this.next.invoke(request, response);
            } finally {
                Session session = request.getSessionInternal(false);
                if (session != null && session.isValid()) {
                    SessionFlushValve.this.store.save(session);
                }
            }

            return null;
        }

    });

}
 
Example #10
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 #11
Source File: ExtendedAccessLogValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public void addElement(StringBuilder buf, Date date, Request request,
        Response response, long time) {
    if (null != response) {
        Iterator<String> iter = response.getHeaders(header).iterator();
        if (iter.hasNext()) {
            StringBuilder buffer = new StringBuilder();
            boolean first = true;
            while (iter.hasNext()) {
                if (first) {
                    first = false;
                } else {
                    buffer.append(",");
                }
                buffer.append(iter.next());
            }
            buf.append(wrap(buffer.toString()));
        }
        return ;
    }
    buf.append("-");
}
 
Example #12
Source File: RemoteAddrValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    String property;
    if (getAddConnectorPort()) {
        property = request.getRequest().getRemoteAddr() + ";" + request.getConnector().getPort();
    } else {
        property = request.getRequest().getRemoteAddr();
    }
    process(property, request, response);
}
 
Example #13
Source File: AccessLogValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void addElement(StringBuilder buf, Date date, Request request,
        Response response, long time) {
    RequestInfo info = request.getCoyoteRequest().getRequestProcessor();
    if(info != null) {
        buf.append(info.getWorkerThreadName());
    } else {
        buf.append("-");
    }
}
 
Example #14
Source File: AuthenticatorBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void secureResponseJspic(Request request, Response response, JaspicState state) {
    try {
        state.serverAuthContext.secureResponse(state.messageInfo, null);
        request.setRequest((HttpServletRequest) state.messageInfo.getRequestMessage());
        response.setResponse((HttpServletResponse) state.messageInfo.getResponseMessage());
    } catch (AuthException e) {
        log.warn(sm.getString("authenticator.jaspicSecureResponseFail"), e);
    }
}
 
Example #15
Source File: TestMimeHeaders.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void log(Request request, Response response, long time) {
    super.log(request, response, time);
    try {
        MimeHeaders mh = request.getCoyoteRequest().getMimeHeaders();
        Field headersArrayField = MimeHeaders.class
                .getDeclaredField("headers");
        headersArrayField.setAccessible(true);
        arraySize = ((Object[]) headersArrayField.get(mh)).length;
    } catch (Exception ex) {
        assertNull(ex.getMessage(), ex);
    }
}
 
Example #16
Source File: ApplicationDispatcher.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Create and return a response wrapper that has been inserted in the
 * appropriate spot in the response chain.
 */
private ServletResponse wrapResponse(State state) {

    // Locate the response we should insert in front of
    ServletResponse previous = null;
    ServletResponse current = state.outerResponse;
    while (current != null) {
        if(state.hresponse == null && (current instanceof HttpServletResponse)) {
            state.hresponse = (HttpServletResponse)current;
            if(!state.including) // Forward only needs hresponse
                return null;
        }
        if (!(current instanceof ServletResponseWrapper))
            break;
        if (current instanceof ApplicationHttpResponse)
            break;
        if (current instanceof ApplicationResponse)
            break;
        previous = current;
        current = ((ServletResponseWrapper) current).getResponse();
    }

    // Instantiate a new wrapper at this point and insert it in the chain
    ServletResponse wrapper = null;
    if ((current instanceof ApplicationHttpResponse) ||
        (current instanceof Response) ||
        (current instanceof HttpServletResponse))
        wrapper =
            new ApplicationHttpResponse((HttpServletResponse) current,
                    state.including);
    else
        wrapper = new ApplicationResponse(current, state.including);
    if (previous == null)
        state.outerResponse = wrapper;
    else
        ((ServletResponseWrapper) previous).setResponse(wrapper);
    state.wrapResponse = wrapper;
    return wrapper;

}
 
Example #17
Source File: StuckThreadDetectionValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void invoke(Request request, Response response)
        throws IOException, ServletException {

    if (threshold <= 0) {
        // short-circuit if not monitoring stuck threads
        getNext().invoke(request, response);
        return;
    }

    // Save the thread/runnable
    // Keeping a reference to the thread object here does not prevent
    // GC'ing, as the reference is removed from the Map in the finally clause

    Long key = Long.valueOf(Thread.currentThread().getId());
    StringBuffer requestUrl = request.getRequestURL();
    if(request.getQueryString()!=null) {
        requestUrl.append("?");
        requestUrl.append(request.getQueryString());
    }
    MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(),
        requestUrl.toString(), interruptThreadThreshold > 0);
    activeThreads.put(key, monitoredThread);

    try {
        getNext().invoke(request, response);
    } finally {
        activeThreads.remove(key);
        if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) {
            if(monitoredThread.wasInterrupted()) {
                interruptedThreadsCount.incrementAndGet();
            }
            completedStuckThreadsQueue.add(
                    new CompletedStuckThread(monitoredThread.getThread(),
                        monitoredThread.getActiveTimeInMillis()));
        }
    }
}
 
Example #18
Source File: TestCrawlerSessionManagerValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testCrawlerIpsPositive() throws Exception {
    CrawlerSessionManagerValve valve = new CrawlerSessionManagerValve();
    valve.setCrawlerIps("216\\.58\\.206\\.174");
    valve.setCrawlerUserAgents(valve.getCrawlerUserAgents());
    valve.setNext(EasyMock.createMock(Valve.class));
    HttpSession session = createSessionExpectations(valve, true);
    Request request = createRequestExpectations("216.58.206.174", session, true);

    EasyMock.replay(request, session);

    valve.invoke(request, EasyMock.createMock(Response.class));

    EasyMock.verify(request, session);
}
 
Example #19
Source File: ExtendedAccessLogValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void addElement(StringBuilder buf, Date date, Request request,
        Response response, long time) {
    Cookie[] c = request.getCookies();
    for (int i = 0; c != null && i < c.length; i++) {
        if (name.equals(c[i].getName())) {
            buf.append(wrap(c[i].getValue()));
        }
    }
}
 
Example #20
Source File: TestCometProcessor.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(Request request, Response response)
        throws IOException, ServletException {

    CometEventImpl event = new CometEventImpl(request, response);

    getNext().invoke(request, response);

    if (request.isComet()) {
        Thread t = new AsyncCometCloseThread(event);
        t.start();
    }
}
 
Example #21
Source File: StuckThreadDetectionValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void invoke(Request request, Response response)
        throws IOException, ServletException {

    if (threshold <= 0) {
        // short-circuit if not monitoring stuck threads
        getNext().invoke(request, response);
        return;
    }

    // Save the thread/runnable
    // Keeping a reference to the thread object here does not prevent
    // GC'ing, as the reference is removed from the Map in the finally clause

    Long key = Long.valueOf(Thread.currentThread().getId());
    StringBuffer requestUrl = request.getRequestURL();
    if(request.getQueryString()!=null) {
        requestUrl.append("?");
        requestUrl.append(request.getQueryString());
    }
    MonitoredThread monitoredThread = new MonitoredThread(Thread.currentThread(),
        requestUrl.toString(), interruptThreadThreshold > 0);
    activeThreads.put(key, monitoredThread);

    try {
        getNext().invoke(request, response);
    } finally {
        activeThreads.remove(key);
        if (monitoredThread.markAsDone() == MonitoredThreadState.STUCK) {
            if(monitoredThread.wasInterrupted()) {
                interruptedThreadsCount.incrementAndGet();
            }
            completedStuckThreadsQueue.add(
                    new CompletedStuckThread(monitoredThread.getThread(),
                        monitoredThread.getActiveTimeInMillis()));
        }
    }
}
 
Example #22
Source File: AccessLogValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void addElement(StringBuilder buf, Date date, Request request,
        Response response, long time) {
    Enumeration<String> iter = request.getHeaders(header);
    if (iter.hasMoreElements()) {
        buf.append(iter.nextElement());
        while (iter.hasMoreElements()) {
            buf.append(',').append(iter.nextElement());
        }
        return;
    }
    buf.append('-');
}
 
Example #23
Source File: ApplicationDispatcher.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Unwrap the response if we have wrapped it.
 */
private void unwrapResponse(State state) {

    if (state.wrapResponse == null)
        return;

    if (state.outerRequest.isAsyncStarted()) {
        if (!state.outerRequest.getAsyncContext().hasOriginalRequestAndResponse()) {
            return;
        }
    }

    ServletResponse previous = null;
    ServletResponse current = state.outerResponse;
    while (current != null) {

        // If we run into the container response we are done
        if ((current instanceof Response)
            || (current instanceof ResponseFacade))
            break;

        // Remove the current response if it is our wrapper
        if (current == state.wrapResponse) {
            ServletResponse next =
              ((ServletResponseWrapper) current).getResponse();
            if (previous == null)
                state.outerResponse = next;
            else
                ((ServletResponseWrapper) previous).setResponse(next);
            break;
        }

        // Advance to the next response in the chain
        previous = current;
        current = ((ServletResponseWrapper) current).getResponse();

    }

}
 
Example #24
Source File: KeycloakAuthenticatorValve.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean forwardToErrorPageInternal(Request request, HttpServletResponse response, Object loginConfig) throws IOException {
    if (loginConfig == null) return false;
    LoginConfig config = (LoginConfig)loginConfig;
    if (config.getErrorPage() == null) return false;
    forwardToErrorPage(request, (Response)response, config);
    return true;
}
 
Example #25
Source File: ExtendedAccessLogValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void addElement(CharArrayWriter buf, Date date, Request request,
        Response response, long time) {
    ElementTimestampStruct eds = currentDate.get();
    long millis = eds.currentTimestamp.getTime();
    if (date.getTime() > (millis + INTERVAL -1) ||
            date.getTime() < millis) {
        eds.currentTimestamp.setTime(
                date.getTime() - (date.getTime() % INTERVAL));
        eds.currentTimestampString =
            eds.currentTimestampFormat.format(eds.currentTimestamp);
    }
    buf.append(eds.currentTimestampString);
}
 
Example #26
Source File: SslAcceleratorValve.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public @Override void invoke(Request req, Response resp) throws IOException, ServletException {
    if (sslAcceleratorPort != null && req.getLocalPort() == sslAcceleratorPort.intValue()) {
        req.setSecure(true);
    }

    if (getNext() != null) {
        getNext().invoke(req, resp);
    }
}
 
Example #27
Source File: RemoteCIDRValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void invoke(final Request request, final Response response) throws IOException, ServletException {

    if (isAllowed(request.getRequest().getRemoteAddr())) {
        getNext().invoke(request, response);
    } else {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}
 
Example #28
Source File: LetsEncryptValve.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(final Request request, final Response response) throws IOException, ServletException {
    if (request.getRequestURI().equals(current.endpoint)) {
        response.setHeader("Content-Type", "text/plain");
        response.getWriter().write(current.challenge);
        return;
    }
    getNext().invoke(request, response);
}
 
Example #29
Source File: ExtendedAccessLogValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void addElement(StringBuilder buf, Date date, Request request,
        Response response, long time) {
    ElementTimestampStruct eds = currentDate.get();
    long millis = eds.currentTimestamp.getTime();
    if (date.getTime() > (millis + INTERVAL -1) ||
            date.getTime() < millis) {
        eds.currentTimestamp.setTime(
                date.getTime() - (date.getTime() % INTERVAL));
        eds.currentTimestampString =
            eds.currentTimestampFormat.format(eds.currentTimestamp);
    }
    buf.append(eds.currentTimestampString);
}
 
Example #30
Source File: AccessLogValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void addElement(StringBuilder buf, Date date, Request request,
        Response response, long time) {
    long commitTime = response.getCoyoteResponse().getCommitTime();
    if (commitTime == -1) {
        buf.append('-');
    } else {
        long delta =
                commitTime - request.getCoyoteRequest().getStartTime();
        buf.append(Long.toString(delta));
    }
}