michael@0: /*
michael@0: * ====================================================================
michael@0: * Licensed to the Apache Software Foundation (ASF) under one
michael@0: * or more contributor license agreements. See the NOTICE file
michael@0: * distributed with this work for additional information
michael@0: * regarding copyright ownership. The ASF licenses this file
michael@0: * to you under the Apache License, Version 2.0 (the
michael@0: * "License"); you may not use this file except in compliance
michael@0: * with the License. You may obtain a copy of the License at
michael@0: *
michael@0: * http://www.apache.org/licenses/LICENSE-2.0
michael@0: *
michael@0: * Unless required by applicable law or agreed to in writing,
michael@0: * software distributed under the License is distributed on an
michael@0: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
michael@0: * KIND, either express or implied. See the License for the
michael@0: * specific language governing permissions and limitations
michael@0: * under the License.
michael@0: * ====================================================================
michael@0: *
michael@0: * This software consists of voluntary contributions made by many
michael@0: * individuals on behalf of the Apache Software Foundation. For more
michael@0: * information on the Apache Software Foundation, please see
michael@0: *
michael@0: * HttpService relies on {@link HttpProcessor} to generate mandatory protocol
michael@0: * headers for all outgoing messages and apply common, cross-cutting message
michael@0: * transformations to all incoming and outgoing messages, whereas individual
michael@0: * {@link HttpRequestHandler}s are expected to take care of application specific
michael@0: * content generation and processing.
michael@0: *
michael@0: * HttpService relies on {@link HttpRequestHandler} to resolve matching request
michael@0: * handler for a particular request URI of an incoming HTTP request.
michael@0: *
michael@0: * HttpService can use optional {@link HttpExpectationVerifier} to ensure that
michael@0: * incoming requests meet server's expectations.
michael@0: *
michael@0: * @since 4.0
michael@0: */
michael@0: public class HttpService {
michael@0:
michael@0: /**
michael@0: * TODO: make all variables final in the next major version
michael@0: */
michael@0: private volatile HttpParams params = null;
michael@0: private volatile HttpProcessor processor = null;
michael@0: private volatile HttpRequestHandlerResolver handlerResolver = null;
michael@0: private volatile ConnectionReuseStrategy connStrategy = null;
michael@0: private volatile HttpResponseFactory responseFactory = null;
michael@0: private volatile HttpExpectationVerifier expectationVerifier = null;
michael@0:
michael@0: /**
michael@0: * Create a new HTTP service.
michael@0: *
michael@0: * @param processor the processor to use on requests and responses
michael@0: * @param connStrategy the connection reuse strategy
michael@0: * @param responseFactory the response factory
michael@0: * @param handlerResolver the handler resolver. May be null.
michael@0: * @param expectationVerifier the expectation verifier. May be null.
michael@0: * @param params the HTTP parameters
michael@0: *
michael@0: * @since 4.1
michael@0: */
michael@0: public HttpService(
michael@0: final HttpProcessor processor,
michael@0: final ConnectionReuseStrategy connStrategy,
michael@0: final HttpResponseFactory responseFactory,
michael@0: final HttpRequestHandlerResolver handlerResolver,
michael@0: final HttpExpectationVerifier expectationVerifier,
michael@0: final HttpParams params) {
michael@0: super();
michael@0: if (processor == null) {
michael@0: throw new IllegalArgumentException("HTTP processor may not be null");
michael@0: }
michael@0: if (connStrategy == null) {
michael@0: throw new IllegalArgumentException("Connection reuse strategy may not be null");
michael@0: }
michael@0: if (responseFactory == null) {
michael@0: throw new IllegalArgumentException("Response factory may not be null");
michael@0: }
michael@0: if (params == null) {
michael@0: throw new IllegalArgumentException("HTTP parameters may not be null");
michael@0: }
michael@0: this.processor = processor;
michael@0: this.connStrategy = connStrategy;
michael@0: this.responseFactory = responseFactory;
michael@0: this.handlerResolver = handlerResolver;
michael@0: this.expectationVerifier = expectationVerifier;
michael@0: this.params = params;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Create a new HTTP service.
michael@0: *
michael@0: * @param processor the processor to use on requests and responses
michael@0: * @param connStrategy the connection reuse strategy
michael@0: * @param responseFactory the response factory
michael@0: * @param handlerResolver the handler resolver. May be null.
michael@0: * @param params the HTTP parameters
michael@0: *
michael@0: * @since 4.1
michael@0: */
michael@0: public HttpService(
michael@0: final HttpProcessor processor,
michael@0: final ConnectionReuseStrategy connStrategy,
michael@0: final HttpResponseFactory responseFactory,
michael@0: final HttpRequestHandlerResolver handlerResolver,
michael@0: final HttpParams params) {
michael@0: this(processor, connStrategy, responseFactory, handlerResolver, null, params);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Create a new HTTP service.
michael@0: *
michael@0: * @param proc the processor to use on requests and responses
michael@0: * @param connStrategy the connection reuse strategy
michael@0: * @param responseFactory the response factory
michael@0: *
michael@0: * @deprecated use {@link HttpService#HttpService(HttpProcessor,
michael@0: * ConnectionReuseStrategy, HttpResponseFactory, HttpRequestHandlerResolver, HttpParams)}
michael@0: */
michael@0: public HttpService(
michael@0: final HttpProcessor proc,
michael@0: final ConnectionReuseStrategy connStrategy,
michael@0: final HttpResponseFactory responseFactory) {
michael@0: super();
michael@0: setHttpProcessor(proc);
michael@0: setConnReuseStrategy(connStrategy);
michael@0: setResponseFactory(responseFactory);
michael@0: }
michael@0:
michael@0: /**
michael@0: * @deprecated set {@link HttpProcessor} using constructor
michael@0: */
michael@0: public void setHttpProcessor(final HttpProcessor processor) {
michael@0: if (processor == null) {
michael@0: throw new IllegalArgumentException("HTTP processor may not be null");
michael@0: }
michael@0: this.processor = processor;
michael@0: }
michael@0:
michael@0: /**
michael@0: * @deprecated set {@link ConnectionReuseStrategy} using constructor
michael@0: */
michael@0: public void setConnReuseStrategy(final ConnectionReuseStrategy connStrategy) {
michael@0: if (connStrategy == null) {
michael@0: throw new IllegalArgumentException("Connection reuse strategy may not be null");
michael@0: }
michael@0: this.connStrategy = connStrategy;
michael@0: }
michael@0:
michael@0: /**
michael@0: * @deprecated set {@link HttpResponseFactory} using constructor
michael@0: */
michael@0: public void setResponseFactory(final HttpResponseFactory responseFactory) {
michael@0: if (responseFactory == null) {
michael@0: throw new IllegalArgumentException("Response factory may not be null");
michael@0: }
michael@0: this.responseFactory = responseFactory;
michael@0: }
michael@0:
michael@0: /**
michael@0: * @deprecated set {@link HttpResponseFactory} using constructor
michael@0: */
michael@0: public void setParams(final HttpParams params) {
michael@0: this.params = params;
michael@0: }
michael@0:
michael@0: /**
michael@0: * @deprecated set {@link HttpRequestHandlerResolver} using constructor
michael@0: */
michael@0: public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) {
michael@0: this.handlerResolver = handlerResolver;
michael@0: }
michael@0:
michael@0: /**
michael@0: * @deprecated set {@link HttpExpectationVerifier} using constructor
michael@0: */
michael@0: public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
michael@0: this.expectationVerifier = expectationVerifier;
michael@0: }
michael@0:
michael@0: public HttpParams getParams() {
michael@0: return this.params;
michael@0: }
michael@0:
michael@0: /**
michael@0: * Handles receives one HTTP request over the given connection within the
michael@0: * given execution context and sends a response back to the client.
michael@0: *
michael@0: * @param conn the active connection to the client
michael@0: * @param context the actual execution context.
michael@0: * @throws IOException in case of an I/O error.
michael@0: * @throws HttpException in case of HTTP protocol violation or a processing
michael@0: * problem.
michael@0: */
michael@0: public void handleRequest(
michael@0: final HttpServerConnection conn,
michael@0: final HttpContext context) throws IOException, HttpException {
michael@0:
michael@0: context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
michael@0:
michael@0: HttpResponse response = null;
michael@0:
michael@0: try {
michael@0:
michael@0: HttpRequest request = conn.receiveRequestHeader();
michael@0: request.setParams(
michael@0: new DefaultedHttpParams(request.getParams(), this.params));
michael@0:
michael@0: ProtocolVersion ver =
michael@0: request.getRequestLine().getProtocolVersion();
michael@0: if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
michael@0: // Downgrade protocol version if greater than HTTP/1.1
michael@0: ver = HttpVersion.HTTP_1_1;
michael@0: }
michael@0:
michael@0: if (request instanceof HttpEntityEnclosingRequest) {
michael@0:
michael@0: if (((HttpEntityEnclosingRequest) request).expectContinue()) {
michael@0: response = this.responseFactory.newHttpResponse(ver,
michael@0: HttpStatus.SC_CONTINUE, context);
michael@0: response.setParams(
michael@0: new DefaultedHttpParams(response.getParams(), this.params));
michael@0:
michael@0: if (this.expectationVerifier != null) {
michael@0: try {
michael@0: this.expectationVerifier.verify(request, response, context);
michael@0: } catch (HttpException ex) {
michael@0: response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0,
michael@0: HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
michael@0: response.setParams(
michael@0: new DefaultedHttpParams(response.getParams(), this.params));
michael@0: handleException(ex, response);
michael@0: }
michael@0: }
michael@0: if (response.getStatusLine().getStatusCode() < 200) {
michael@0: // Send 1xx response indicating the server expections
michael@0: // have been met
michael@0: conn.sendResponseHeader(response);
michael@0: conn.flush();
michael@0: response = null;
michael@0: conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
michael@0: }
michael@0: } else {
michael@0: conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
michael@0: }
michael@0: }
michael@0:
michael@0: if (response == null) {
michael@0: response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_OK, context);
michael@0: response.setParams(
michael@0: new DefaultedHttpParams(response.getParams(), this.params));
michael@0:
michael@0: context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
michael@0: context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);
michael@0:
michael@0: this.processor.process(request, context);
michael@0: doService(request, response, context);
michael@0: }
michael@0:
michael@0: // Make sure the request content is fully consumed
michael@0: if (request instanceof HttpEntityEnclosingRequest) {
michael@0: HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
michael@0: EntityUtils.consume(entity);
michael@0: }
michael@0:
michael@0: } catch (HttpException ex) {
michael@0: response = this.responseFactory.newHttpResponse
michael@0: (HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR,
michael@0: context);
michael@0: response.setParams(
michael@0: new DefaultedHttpParams(response.getParams(), this.params));
michael@0: handleException(ex, response);
michael@0: }
michael@0:
michael@0: this.processor.process(response, context);
michael@0: conn.sendResponseHeader(response);
michael@0: conn.sendResponseEntity(response);
michael@0: conn.flush();
michael@0:
michael@0: if (!this.connStrategy.keepAlive(response, context)) {
michael@0: conn.close();
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Handles the given exception and generates an HTTP response to be sent
michael@0: * back to the client to inform about the exceptional condition encountered
michael@0: * in the course of the request processing.
michael@0: *
michael@0: * @param ex the exception.
michael@0: * @param response the HTTP response.
michael@0: */
michael@0: protected void handleException(final HttpException ex, final HttpResponse response) {
michael@0: if (ex instanceof MethodNotSupportedException) {
michael@0: response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
michael@0: } else if (ex instanceof UnsupportedHttpVersionException) {
michael@0: response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
michael@0: } else if (ex instanceof ProtocolException) {
michael@0: response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
michael@0: } else {
michael@0: response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
michael@0: }
michael@0: byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
michael@0: ByteArrayEntity entity = new ByteArrayEntity(msg);
michael@0: entity.setContentType("text/plain; charset=US-ASCII");
michael@0: response.setEntity(entity);
michael@0: }
michael@0:
michael@0: /**
michael@0: * The default implementation of this method attempts to resolve an
michael@0: * {@link HttpRequestHandler} for the request URI of the given request
michael@0: * and, if found, executes its
michael@0: * {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)}
michael@0: * method.
michael@0: *
michael@0: * Super-classes can override this method in order to provide a custom michael@0: * implementation of the request processing logic. michael@0: * michael@0: * @param request the HTTP request. michael@0: * @param response the HTTP response. michael@0: * @param context the execution context. michael@0: * @throws IOException in case of an I/O error. michael@0: * @throws HttpException in case of HTTP protocol violation or a processing michael@0: * problem. michael@0: */ michael@0: protected void doService( michael@0: final HttpRequest request, michael@0: final HttpResponse response, michael@0: final HttpContext context) throws HttpException, IOException { michael@0: HttpRequestHandler handler = null; michael@0: if (this.handlerResolver != null) { michael@0: String requestURI = request.getRequestLine().getUri(); michael@0: handler = this.handlerResolver.lookup(requestURI); michael@0: } michael@0: if (handler != null) { michael@0: handler.handle(request, response, context); michael@0: } else { michael@0: response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); michael@0: } michael@0: } michael@0: michael@0: }