Search in sources :

Example 16 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat by apache.

the class TestMapperPerformance method testPerformanceImpl.

private long testPerformanceImpl(String requestedHostName) throws Exception {
    MappingData mappingData = new MappingData();
    MessageBytes host = MessageBytes.newInstance();
    host.setString(requestedHostName);
    MessageBytes uri = MessageBytes.newInstance();
    uri.setString("/foo/bar/blah/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        mappingData.recycle();
        mapper.map(host, uri, null, mappingData);
    }
    long time = System.currentTimeMillis() - start;
    return time;
}
Also used : MessageBytes(org.apache.tomcat.util.buf.MessageBytes)

Example 17 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat by apache.

the class ApplicationHttpRequest method mergeParameters.

// ------------------------------------------------------ Private Methods
/**
     * 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;
    // Parse the query string from the dispatch target
    Parameters paramParser = new Parameters();
    MessageBytes queryMB = MessageBytes.newInstance();
    queryMB.setString(queryParamString);
    String encoding = getCharacterEncoding();
    // in MessageBytes.toBytes().
    if (encoding != null) {
        try {
            queryMB.setCharset(B2CConverter.getCharset(encoding));
        } catch (UnsupportedEncodingException ignored) {
        // Fall-back to ISO-8859-1
        }
    }
    paramParser.setQuery(queryMB);
    paramParser.setQueryStringEncoding(encoding);
    paramParser.handleQueryParameters();
    // Insert the additional parameters from the dispatch target
    Enumeration<String> dispParamNames = paramParser.getParameterNames();
    while (dispParamNames.hasMoreElements()) {
        String dispParamName = dispParamNames.nextElement();
        String[] dispParamValues = paramParser.getParameterValues(dispParamName);
        String[] originalValues = parameters.get(dispParamName);
        if (originalValues == null) {
            parameters.put(dispParamName, dispParamValues);
            continue;
        }
        parameters.put(dispParamName, mergeValues(dispParamValues, originalValues));
    }
}
Also used : Parameters(org.apache.tomcat.util.http.Parameters) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 18 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat by apache.

the class StandardContextValve method invoke.

/**
     * Select the appropriate child Wrapper to process this request,
     * based on the specified request URI.  If no matching Wrapper can
     * be found, return an appropriate HTTP error.
     *
     * @param request Request to be processed
     * @param response Response to be produced
     *
     * @exception IOException if an input/output error occurred
     * @exception ServletException if a servlet error occurred
     */
@Override
public final void invoke(Request request, Response response) throws IOException, ServletException {
    // Disallow any direct access to resources under WEB-INF or META-INF
    MessageBytes requestPathMB = request.getRequestPathMB();
    if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/META-INF")) || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0)) || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // Select the Wrapper to be used for this Request
    Wrapper wrapper = request.getWrapper();
    if (wrapper == null || wrapper.isUnavailable()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    // Acknowledge the request
    try {
        response.sendAcknowledgement();
    } catch (IOException ioe) {
        container.getLogger().error(sm.getString("standardContextValve.acknowledgeException"), ioe);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    if (request.isAsyncSupported()) {
        request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported());
    }
    wrapper.getPipeline().getFirst().invoke(request, response);
}
Also used : Wrapper(org.apache.catalina.Wrapper) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) IOException(java.io.IOException)

Example 19 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat by apache.

the class StandardWrapperValve method invoke.

// --------------------------------------------------------- Public Methods
/**
     * Invoke the servlet we are managing, respecting the rules regarding
     * servlet lifecycle and SingleThreadModel support.
     *
     * @param request Request to be processed
     * @param response Response to be produced
     *
     * @exception IOException if an input/output error occurred
     * @exception ServletException if a servlet error occurred
     */
@Override
public final void invoke(Request request, Response response) throws IOException, ServletException {
    // Initialize local variables we may need
    boolean unavailable = false;
    Throwable throwable = null;
    // This should be a Request attribute...
    long t1 = System.currentTimeMillis();
    requestCount.incrementAndGet();
    StandardWrapper wrapper = (StandardWrapper) getContainer();
    Servlet servlet = null;
    Context context = (Context) wrapper.getParent();
    // Check for the application being marked unavailable
    if (!context.getState().isAvailable()) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardContext.isUnavailable"));
        unavailable = true;
    }
    // Check for the servlet being marked unavailable
    if (!unavailable && wrapper.isUnavailable()) {
        container.getLogger().info(sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
        unavailable = true;
    }
    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            servlet = wrapper.allocate();
        }
    } catch (UnavailableException e) {
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e);
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
    } catch (ServletException e) {
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e));
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.allocateException", wrapper.getName()), e);
        throwable = e;
        exception(request, response, e);
        servlet = null;
    }
    MessageBytes requestPathMB = request.getRequestPathMB();
    DispatcherType dispatcherType = DispatcherType.REQUEST;
    if (request.getDispatcherType() == DispatcherType.ASYNC)
        dispatcherType = DispatcherType.ASYNC;
    request.setAttribute(Globals.DISPATCHER_TYPE_ATTR, dispatcherType);
    request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, requestPathMB);
    // Create the filter chain for this request
    ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
    // NOTE: This also calls the servlet's service() method
    try {
        if ((servlet != null) && (filterChain != null)) {
            // Swallow output if needed
            if (context.getSwallowOutput()) {
                try {
                    SystemLogHandler.startCapture();
                    if (request.isAsyncDispatching()) {
                        request.getAsyncContextInternal().doInternalDispatch();
                    } else {
                        filterChain.doFilter(request.getRequest(), response.getResponse());
                    }
                } finally {
                    String log = SystemLogHandler.stopCapture();
                    if (log != null && log.length() > 0) {
                        context.getLogger().info(log);
                    }
                }
            } else {
                if (request.isAsyncDispatching()) {
                    request.getAsyncContextInternal().doInternalDispatch();
                } else {
                    filterChain.doFilter(request.getRequest(), response.getResponse());
                }
            }
        }
    } catch (ClientAbortException e) {
        throwable = e;
        exception(request, response, e);
    } catch (IOException e) {
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        throwable = e;
        exception(request, response, e);
    } catch (UnavailableException e) {
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        //            throwable = e;
        //            exception(request, response, e);
        wrapper.unavailable(e);
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            response.setDateHeader("Retry-After", available);
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("standardWrapper.isUnavailable", wrapper.getName()));
        } else if (available == Long.MAX_VALUE) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, sm.getString("standardWrapper.notFound", wrapper.getName()));
        }
    // Do not save exception in 'throwable', because we
    // do not want to do exception(request, response, e) processing
    } catch (ServletException e) {
        Throwable rootCause = StandardWrapper.getRootCause(e);
        if (!(rootCause instanceof ClientAbortException)) {
            container.getLogger().error(sm.getString("standardWrapper.serviceExceptionRoot", wrapper.getName(), context.getName(), e.getMessage()), rootCause);
        }
        throwable = e;
        exception(request, response, e);
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.serviceException", wrapper.getName(), context.getName()), e);
        throwable = e;
        exception(request, response, e);
    }
    // Release the filter chain (if any) for this request
    if (filterChain != null) {
        filterChain.release();
    }
    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.deallocateException", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    // unload it and release this instance
    try {
        if ((servlet != null) && (wrapper.getAvailable() == Long.MAX_VALUE)) {
            wrapper.unload();
        }
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        container.getLogger().error(sm.getString("standardWrapper.unloadException", wrapper.getName()), e);
        if (throwable == null) {
            throwable = e;
            exception(request, response, e);
        }
    }
    long t2 = System.currentTimeMillis();
    long time = t2 - t1;
    processingTime += time;
    if (time > maxTime)
        maxTime = time;
    if (time < minTime)
        minTime = time;
}
Also used : Context(org.apache.catalina.Context) UnavailableException(javax.servlet.UnavailableException) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) Servlet(javax.servlet.Servlet) ClientAbortException(org.apache.catalina.connector.ClientAbortException) DispatcherType(javax.servlet.DispatcherType)

Example 20 with MessageBytes

use of org.apache.tomcat.util.buf.MessageBytes in project tomcat by apache.

the class AjpProcessor method prepareResponse.

/**
     * When committing the response, we have to validate the set of headers, as
     * well as setup the response filters.
     */
@Override
protected final void prepareResponse() throws IOException {
    response.setCommitted(true);
    tmpMB.recycle();
    responseMsgPos = -1;
    responseMessage.reset();
    responseMessage.appendByte(Constants.JK_AJP13_SEND_HEADERS);
    // Responses with certain status codes are not permitted to include a
    // response body.
    int statusCode = response.getStatus();
    if (statusCode < 200 || statusCode == 204 || statusCode == 205 || statusCode == 304) {
        // No entity body
        swallowResponse = true;
    }
    // Responses to HEAD requests are not permitted to include a response
    // body.
    MessageBytes methodMB = request.method();
    if (methodMB.equals("HEAD")) {
        // No entity body
        swallowResponse = true;
    }
    // HTTP header contents
    responseMessage.appendInt(statusCode);
    // Reason phrase is optional but mod_jk + httpd 2.x fails with a null
    // reason phrase - bug 45026
    tmpMB.setString(Integer.toString(response.getStatus()));
    responseMessage.appendBytes(tmpMB);
    // Special headers
    MimeHeaders headers = response.getMimeHeaders();
    String contentType = response.getContentType();
    if (contentType != null) {
        headers.setValue("Content-Type").setString(contentType);
    }
    String contentLanguage = response.getContentLanguage();
    if (contentLanguage != null) {
        headers.setValue("Content-Language").setString(contentLanguage);
    }
    long contentLength = response.getContentLengthLong();
    if (contentLength >= 0) {
        headers.setValue("Content-Length").setLong(contentLength);
    }
    // Other headers
    int numHeaders = headers.size();
    responseMessage.appendInt(numHeaders);
    for (int i = 0; i < numHeaders; i++) {
        MessageBytes hN = headers.getName(i);
        int hC = Constants.getResponseAjpIndex(hN.toString());
        if (hC > 0) {
            responseMessage.appendInt(hC);
        } else {
            responseMessage.appendBytes(hN);
        }
        MessageBytes hV = headers.getValue(i);
        responseMessage.appendBytes(hV);
    }
    // Write to buffer
    responseMessage.end();
    socketWrapper.write(true, responseMessage.getBuffer(), 0, responseMessage.getLen());
    socketWrapper.flush(true);
}
Also used : MimeHeaders(org.apache.tomcat.util.http.MimeHeaders) MessageBytes(org.apache.tomcat.util.buf.MessageBytes)

Aggregations

MessageBytes (org.apache.tomcat.util.buf.MessageBytes)32 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)7 Context (org.apache.catalina.Context)6 MimeHeaders (org.apache.tomcat.util.http.MimeHeaders)6 Test (org.junit.Test)6 IOException (java.io.IOException)4 Host (org.apache.catalina.Host)4 LoggingBaseTest (org.apache.catalina.startup.LoggingBaseTest)4 Pattern (java.util.regex.Pattern)3 ServletException (javax.servlet.ServletException)3 Cookie (javax.servlet.http.Cookie)3 Wrapper (org.apache.catalina.Wrapper)3 StandardContext (org.apache.catalina.core.StandardContext)3 StandardHost (org.apache.catalina.core.StandardHost)3 CharChunk (org.apache.tomcat.util.buf.CharChunk)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Principal (java.security.Principal)2 MappingData (org.apache.catalina.mapper.MappingData)2 InputStream (java.io.InputStream)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1