Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * http://glassfish.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 package com.sun.jersey.spi.container;
 
 import java.net.URI;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
An in-bound HTTP request to be processed by the web application.

Containers instantiate, or inherit, and provide an instance to the WebApplication.

By default the implementation of javax.ws.rs.core.SecurityContext will throw java.lang.UnsupportedOperationException if the methods are invoked. Containers SHOULD use the method to define security context behaviour rather than extending from this class and overriding the methods.

Author(s):
Paul.Sandoz@Sun.Com
pavel.bucek@oracle.com
public class ContainerRequest implements HttpRequestContext {
    private static final Logger LOGGER = Logger.getLogger(ContainerRequest.class.getName());
    private static final Annotation[] EMPTY_ANNOTATIONS = new Annotation[0];
    public static final String VARY_HEADER = "Vary";
    private final WebApplication wa;
    private final boolean isTraceEnabled;
    private Map<StringObjectproperties;
    private String method;
    private InputStream entity;
    private URI baseUri;
    private URI requestUri;
    private URI absolutePathUri;
    private String encodedPath;
    private String decodedPath;
    private InBoundHeaders headers;
    private int headersModCount;
    private MediaType contentType;
    private List<MediaTypeaccept;
    private List<LocaleacceptLanguages;
    private Map<StringCookiecookies;
    private SecurityContext securityContext;

    
Create a new container request.

The base URI and the request URI must contain the same scheme, user info, host and port components.

The base URI must not contain the query and fragment components. The encoded path component of the request URI must start with the encoded path component of the base URI. The encoded path component of the base URI must end in a '/' character.

Parameters:
wa the web application
method the HTTP method
baseUri the base URI of the request
requestUri the request URI
headers the request headers
entity the InputStream of the request entity
    public ContainerRequest(
            WebApplication wa,
            String method,
            URI baseUri,
            URI requestUri,
            InBoundHeaders headers,
            InputStream entity) {
        this. = wa;
        this. = wa.isTracingEnabled();
        this. = method;
        this. = baseUri;
        this. = requestUri;
        this. = headers;
        this. = headers.getModCount();
        this. = entity;
    }
    /* package */ ContainerRequest(ContainerRequest r) {
        this. = r.wa;
        this. = r.isTraceEnabled;
    }
    // ContainerRequest

    
Get the mutable properties.

Care should be taken not to clear the properties or remove properties that are unknown otherwise unspecified behaviour may result.

Returns:
the properties.
    public Map<StringObjectgetProperties() {
        if ( != null) {
            return ;
        }
        return  = new HashMap<StringObject>();
    }

    
Set the HTTP method.

Parameters:
method the method.
    public void setMethod(String method) {
        this. = method;
    }

    
Set the base and request URI.

Parameters:
baseUri the base URI.
requestUri the (complete) request URI.
    public void setUris(URI baseUriURI requestUri) {
        this. = baseUri;
        this. = requestUri;
        // reset state
         = null;
         =  = null;
         =  = null;
    }

    
Get the input stream of the entity.

Returns:
the input stream of the entity.
    public InputStream getEntityInputStream() {
        return ;
    }

    
Set the input stream of the entity.

Parameters:
entity the input stream of the entity.
    public void setEntityInputStream(InputStream entity) {
        this. = entity;
    }

    
Set the request headers.

Parameters:
headers the request headers.
    public void setHeaders(InBoundHeaders headers) {
        this. = headers;
        this. = headers.getModCount();
        // reset state
         = null;
         = null;
         = null;
         = null;
    }

    
Set the security context.

Parameters:
securityContext the security context.
    public void setSecurityContext(SecurityContext securityContext) {
        this. = securityContext;
    }

    
Get the security context.

Returns:
the security context.
        return ;
    }

    
Get the message body workers.

Returns:
the message body workers.
        return .getMessageBodyWorkers();
    }
    // Traceable
    @Override
    public boolean isTracingEnabled() {
        return ;
    }
    @Override
    public void trace(String message) {
        if (!isTracingEnabled())
            return;
                !getRequestHeaders().containsKey("X-Jersey-Trace-Accept"))
            return;
        TraceInformation ti = (TraceInformationgetProperties().
                get(TraceInformation.class.getName());
        ti.trace(message);
    }
    // HttpRequestContext
    @Override
    public URI getBaseUri() {
        return ;
    }
    @Override
    public UriBuilder getBaseUriBuilder() {
        return UriBuilder.fromUri(getBaseUri());
    }
    @Override
    public URI getRequestUri() {
        return ;
    }
    @Override
    public UriBuilder getRequestUriBuilder() {
        return UriBuilder.fromUri(getRequestUri());
    }
    @Override
    public URI getAbsolutePath() {
        if ( != nullreturn ;
        return  = UriBuilder.fromUri().
                replaceQuery("").fragment("").
                build();
    }
    @Override
        return UriBuilder.fromUri(getAbsolutePath());
    }
    @Override
    public String getPath() {
        return getPath(true);
    }
    @Override
    public String getPath(boolean decode) {
        if (decode) {
            if ( != nullreturn ;
            return  = UriComponent.decode(
                    getEncodedPath(),
                    ..);
        } else {
            return getEncodedPath();
        }
    }
    private String getEncodedPath() {
        if ( != nullreturn ;
        final int length = getBaseUri().getRawPath().length();
        if(length < getRequestUri().getRawPath().length()) {
            return  = getRequestUri().getRawPath().substring(length);
        } else {
            return "";
        }
    }
    @Override
    public List<PathSegmentgetPathSegments() {
        return getPathSegments(true);
    }
    @Override
    public List<PathSegmentgetPathSegments(boolean decode) {
        if (decode) {
            if ( != null)
                return ;
            return  = UriComponent.decodePath(getPath(false), true);
        } else {
            if ( != null)
                return ;
            return  = UriComponent.decodePath(getPath(false), false);
        }
    }
    @Override
        return getQueryParameters(true);
    }
    @Override
    public MultivaluedMap<StringStringgetQueryParameters(boolean decode) {
        if (decode) {
            if ( != null)
                return ;
            return  = UriComponent.decodeQuery(
                    getRequestUri(), true);
        } else {
            if ( != null)
                return ;
            return  = UriComponent.decodeQuery(
                    getRequestUri(), false);
        }
    }
    @Override
    public String getHeaderValue(String name) {
        final List<Stringv = getRequestHeaders().get(name);
        if (v == nullreturn null;
        if (v.isEmpty()) return "";
        if (v.size() == 1) return v.get(0);
        StringBuilder sb = new StringBuilder(v.get(0));
        for (int i = 1; i < v.size(); i++) {
            final String s = v.get(i);
            if (s.length() > 0)
                sb.append(',').append(s);
        }
        return sb.toString();
    }
    @Override
    public <T> T getEntity(Class<T> typeType genericTypeAnnotation[] as) {
        MediaType mediaType = getMediaType();
        if (mediaType == null) {
            mediaType = .;
        }
                typegenericType,
                asmediaType);
        if (bw == null) {
            String message = "A message body reader for Java class " + type.getName() +
                    ", and Java type " + genericType +
                    ", and MIME media type " + mediaType + " was not found.\n";
            Map<MediaTypeList<MessageBodyReader>> m = getMessageBodyWorkers().
                    getReaders(mediaType);
            message += "The registered message body readers compatible with the MIME media type are:\n" +
                    getMessageBodyWorkers().readersToString(m);
            .severe(message);
            throw new WebApplicationException(
                    new MessageException(message),
                    Responses.unsupportedMediaType().build());
        }
        if (isTracingEnabled()) {
            trace(String.format("matched message body reader: %s, \"%s\" -> %s",
                    genericType,
                    mediaType,
                    ReflectionHelper.objectToString(bw)));
        }
        try {
            return bw.readFrom(typegenericTypeasmediaType);
        } catch (WebApplicationException ex) {
            throw ex;
        } catch (Exception e) {
            throw new MappableContainerException(e);
        }
    }

    
Set the request entity.

Parameters:
type the class of object that is to be written.
genericType the type of object to be written, obtained either by reflection of a resource method return type or by inspection of the returned instance. javax.ws.rs.core.GenericEntity provides a way to specify this information at runtime.
annotations an array of the annotations on the resource method that returns the object.
mediaType the media type of the HTTP entity.
httpHeaders a mutable map of the HTTP response headers.
entity the entity instance to write.
Throws:
com.sun.jersey.api.container.MappableContainerException encapsulates exceptions thrown while serializing the entity.
    public <T> void setEntity(final Class<T> typefinal Type genericType,
                              final Annotation annotations[], final MediaType mediaType,
                              final MultivaluedMap<StringObjecthttpHeadersfinal T entity) {
        final MessageBodyWriter<T> writer = getMessageBodyWorkers().getMessageBodyWriter(typegenericTypeannotationsmediaType);
        if (writer == null) {
            String message = "A message body writer for Java class " + type.getName() +
                    ", and Java type " + genericType +
                    ", and MIME media type " + mediaType + " was not found.\n";
            Map<MediaTypeList<MessageBodyReader>> m = getMessageBodyWorkers().
                    getReaders(mediaType);
            message += "The registered message body readers compatible with the MIME media type are:\n" +
                    getMessageBodyWorkers().readersToString(m);
            .severe(message);
            throw new WebApplicationException(
                    new MessageException(message),
                    Responses.unsupportedMediaType().build());
        }
        if (isTracingEnabled()) {
            trace(String.format("matched message body writer: %s, \"%s\" -> %s",
                    genericType,
                    mediaType,
                    ReflectionHelper.objectToString(writer)));
        }
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            writer.writeTo(entitytypegenericTypeannotationsmediaTypehttpHeadersbyteArrayOutputStream);
        } catch (IOException e) {
            throw new MappableContainerException(e);
        }
        this. = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    }
    @Override
    public <T> T getEntity(Class<T> type) {
        return getEntity(typetype);
    }
    @Override
    public MediaType getAcceptableMediaType(List<MediaTypemediaTypes) {
        if (mediaTypes.isEmpty())
            return getAcceptableMediaTypes().get(0);
        for (MediaType a : getAcceptableMediaTypes()) {
            if (a.getType().equals(.))
                return mediaTypes.get(0);
            for (MediaType m : mediaTypes)
                if (m.isCompatible(a) && !m.isWildcardType() && !m.isWildcardSubtype())
                    return m;
        }
        return null;
    }
    @Override
    public List<MediaTypegetAcceptableMediaTypes(List<QualitySourceMediaTypepriorityMediaTypes) {
        return new ArrayList<MediaType>(HttpHelper.getAccept(thispriorityMediaTypes));
    }
    @Override
        if ( == null ||  != .getModCount()) {
             = new MultivaluedMapImpl();
            for (Map.Entry<StringCookiee : getCookies().entrySet()) {
                .putSingle(e.getKey(), e.getValue().getValue());
            }
        }
        return ;
    }
    @Override
    public Form getFormParameters() {
        if (MediaTypes.typeEquals(.getMediaType())) {
            InputStream in = getEntityInputStream();
            if (in.getClass() != ByteArrayInputStream.class) {
                // Buffer input
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                try {
                    ReaderWriter.writeTo(inbyteArrayOutputStream);
                } catch (IOException e) {
                    throw new IllegalArgumentException(e);
                }
                in = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                setEntityInputStream(in);
            }
            ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStreamin;
            Form f = getEntity(Form.class);
            byteArrayInputStream.reset();
            return f;
        } else {
            return new Form();
        }
    }
    // HttpHeaders
    @Override
        return ;
    }
    @Override
    public List<StringgetRequestHeader(String name) {
        return .get(name);
    }
    @Override
        if ( == null ||  != .getModCount())
             = new ArrayList<MediaType>(HttpHelper.getAccept(this));
        return ;
    }
    @Override
    public List<LocalegetAcceptableLanguages() {
        if ( == null ||  != .getModCount()) {
            List<AcceptableLanguageTagalts = HttpHelper.getAcceptLangauge(this);
             = new ArrayList<Locale>(alts.size());
            for (AcceptableLanguageTag alt : alts) {
                .add(alt.getAsLocale());
            }
        }
        return ;
    }
    @Override
    public MediaType getMediaType() {
        if ( == null ||  != .getModCount())
             = HttpHelper.getContentType(this);
        return ;
    }
    @Override
    public Locale getLanguage() {
        return HttpHelper.getContentLanguageAsLocale(this);
    }
    @Override
    public Map<StringCookiegetCookies() {
        if ( == null ||  != .getModCount()) {
             = new HashMap<StringCookie>();
            List<Stringcl = getRequestHeaders().get(.);
            if (cl != null) {
                for (String cookie : cl) {
                    if (cookie != null)
                        .putAll(
                                HttpHeaderReader.readCookies(cookie));
                }
            }
        }
        return ;
    }
    // Request
    @Override
    public String getMethod() {
        return ;
    }
    @Override
    public Variant selectVariant(List<Variantvariants) {
        if (variants == null || variants.isEmpty())
            throw new IllegalArgumentException("The list of variants is null or empty");
        // TODO mark the Vary header to be added to the response
        return VariantSelector.selectVariant(thisvariants);
    }
    @Override
        Set<MatchingEntityTagmatchingTags = HttpHelper.getIfMatch(this);
        if (matchingTags == null) {
            return null;
        }
        // Since the resource does not exist the method must not be
        // perform and 412 Precondition Failed is returned
        return Responses.preconditionFailed();
    }
    @Override
        if(eTag == null) {
            throw new IllegalArgumentException("Parameter 'eTag' cannot be null.");
        }
        ResponseBuilder r = evaluateIfMatch(eTag);
        if (r != null)
            return r;
        return evaluateIfNoneMatch(eTag);
    }
    @Override
    public ResponseBuilder evaluatePreconditions(Date lastModified) {
        if(lastModified == null) {
            throw new IllegalArgumentException("Parameter 'lastModified' cannot be null.");
        }
        final long lastModifiedTime = lastModified.getTime();
        ResponseBuilder r = evaluateIfUnmodifiedSince(lastModifiedTime);
        if (r != null)
            return r;
        return evaluateIfModifiedSince(lastModifiedTime);
    }
    @Override
    public ResponseBuilder evaluatePreconditions(Date lastModifiedEntityTag eTag) {
        if(lastModified == null || eTag == null) {
            throw new IllegalArgumentException("Parameters 'lastModified' and 'eTag' cannot be null.");
        }
        ResponseBuilder r = evaluateIfMatch(eTag);
        if (r != null)
            return r;
        final long lastModifiedTime = lastModified.getTime();
        r = evaluateIfUnmodifiedSince(lastModifiedTime);
        if (r != null)
            return r;
        final boolean isGetOrHead = getMethod().equals("GET") || getMethod().equals("HEAD");
        final Set<MatchingEntityTagmatchingTags = HttpHelper.getIfNoneMatch(this);
        if (matchingTags != null) {
            r = evaluateIfNoneMatch(eTagmatchingTagsisGetOrHead);
            // If the If-None-Match header is present and there is no
            // match then the If-Modified-Since header must be ignored
            if (r == null)
                return r;
            // Otherwise if the If-None-Match header is present and there
            // is a match then the If-Modified-Since header must be checked
            // for consistency
        }
        final String ifModifiedSinceHeader = getRequestHeaders().getFirst("If-Modified-Since");
        if (ifModifiedSinceHeader != null && isGetOrHead) {
            r = evaluateIfModifiedSince(lastModifiedTimeifModifiedSinceHeader);
            if (r != null)
                r.tag(eTag);
        }
        return r;
    }
    private ResponseBuilder evaluateIfMatch(EntityTag eTag) {
        Set<MatchingEntityTagmatchingTags = HttpHelper.getIfMatch(this);
        if (matchingTags == null) {
            return null;
        }
        // The strong comparison function must be used to compare the entity
        // tags. Thus if the entity tag of the entity is weak then matching
        // of entity tags in the If-Match header should fail.
        if (eTag.isWeak()) {
            return Responses.preconditionFailed();
        }
        if (matchingTags != . &&
                !matchingTags.contains(eTag)) {
            // 412 Precondition Failed
            return Responses.preconditionFailed();
        }
        return null;
    }
        Set<MatchingEntityTagmatchingTags = HttpHelper.getIfNoneMatch(this);
        if (matchingTags == null)
            return null;
        final String httpMethod = getMethod();
        return evaluateIfNoneMatch(
                eTag,
                matchingTags,
                httpMethod.equals("GET") || httpMethod.equals("HEAD"));
    }
            EntityTag eTag,
            Set<MatchingEntityTagmatchingTags,
            boolean isGetOrHead) {
        if (isGetOrHead) {
            if (matchingTags == .) {
                // 304 Not modified
                return Response.notModified(eTag);
            }
            // The weak comparison function may be used to compare entity tags
            if (matchingTags.contains(eTag) || matchingTags.contains(new EntityTag(eTag.getValue(), !eTag.isWeak()))) {
                // 304 Not modified
                return Response.notModified(eTag);
            }
        } else {
            // The strong comparison function must be used to compare the entity
            // tags. Thus if the entity tag of the entity is weak then matching
            // of entity tags in the If-None-Match header should fail if the
            // HTTP method is not GET or not HEAD.
            if (eTag.isWeak()) {
                return null;
            }
            if (matchingTags == . || matchingTags.contains(eTag)) {
                // 412 Precondition Failed
                return Responses.preconditionFailed();
            }
        }
        return null;
    }
    private ResponseBuilder evaluateIfUnmodifiedSince(long lastModified) {
        String ifUnmodifiedSinceHeader = getRequestHeaders().getFirst("If-Unmodified-Since");
        if (ifUnmodifiedSinceHeader != null) {
            try {
                long ifUnmodifiedSince = HttpHeaderReader.readDate(ifUnmodifiedSinceHeader).getTime();
                if (roundDown(lastModified) > ifUnmodifiedSince) {
                    // 412 Precondition Failed
                    return Responses.preconditionFailed();
                }
            } catch (ParseException ex) {
                // Ignore the header if parsing error
            }
        }
        return null;
    }
    private ResponseBuilder evaluateIfModifiedSince(long lastModified) {
        String ifModifiedSinceHeader = getRequestHeaders().getFirst("If-Modified-Since");
        if (ifModifiedSinceHeader == null)
            return null;
        final String httpMethod = getMethod();
        if (httpMethod.equals("GET") || httpMethod.equals("HEAD")) {
            return evaluateIfModifiedSince(
                    lastModified,
                    ifModifiedSinceHeader);
        } else {
            return null;
        }
    }
            long lastModified,
            String ifModifiedSinceHeader) {
        try {
            long ifModifiedSince = HttpHeaderReader.readDate(ifModifiedSinceHeader).getTime();
            if (roundDown(lastModified) <= ifModifiedSince) {
                // 304 Not modified
                return Responses.notModified();
            }
        } catch (ParseException ex) {
            // Ignore the header if parsing error
        }
        return null;
    }

    
Round down the time to the nearest second.

Parameters:
time the time to round down.
Returns:
the rounded down time.
    private static long roundDown(long time) {
        return time - time % 1000;
    }
    // SecurityContext
    @Override
    public Principal getUserPrincipal() {
        if ( == null)
            throw new UnsupportedOperationException();
        return .getUserPrincipal();
    }
    @Override
    public boolean isUserInRole(String role) {
        if ( == null)
            throw new UnsupportedOperationException();
        return .isUserInRole(role);
    }
    @Override
    public boolean isSecure() {
        if ( == null)
            throw new UnsupportedOperationException();
        return .isSecure();
    }
    @Override
    public String getAuthenticationScheme() {
        if ( == null)
            throw new UnsupportedOperationException();
        return .getAuthenticationScheme();
    }
New to GrepCode? Check out our FAQ X