001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nicolas Chapurlat <nchapurlat@nuxeo.com>
018 */
019
020package org.nuxeo.ecm.webengine.jaxrs.coreiodelegate;
021
022import java.util.Enumeration;
023import java.util.Locale;
024import java.util.Map;
025
026import javax.servlet.ServletRequest;
027import javax.servlet.http.HttpServletRequest;
028
029import org.nuxeo.ecm.core.api.CoreSession;
030import org.nuxeo.ecm.core.io.registry.context.RenderingContext;
031import org.nuxeo.ecm.core.io.registry.context.RenderingContext.CtxBuilder;
032import org.nuxeo.ecm.core.io.registry.context.RenderingContextImpl.RenderingContextBuilder;
033import org.nuxeo.ecm.webengine.jaxrs.session.SessionFactory;
034
035/**
036 * Utility class that get or create a {@link RenderingContext} from the current {@link HttpServletRequest}.
037 *
038 * @since 7.2
039 */
040public final class RenderingContextWebUtils {
041
042    private static final String CTX_KEY = "_STORED_GENERATED_RENDERING_CONTEXT";
043
044    public static final String REQUEST_KEY = "_STORED_GENERATED_HTTP_SERVLET_REQUEST";
045
046    private RenderingContextWebUtils() {
047    }
048
049    /**
050     * Get the current context in the current {@link HttpServletRequest} or create it from the current
051     * {@link HttpServletRequest}.
052     *
053     * @since 7.2
054     */
055    public static RenderingContext getContext(ServletRequest request) {
056        // try to get an existing RenderingContext from the request
057        Object stored = request.getAttribute(getContextKey());
058        if (stored != null) {
059            return (RenderingContext) stored;
060        }
061        RenderingContextBuilder builder = CtxBuilder.builder();
062        fillContext(builder, request);
063        RenderingContext ctx = builder.get();
064        registerContext(request, ctx);
065        return ctx;
066    }
067
068    /**
069     * Register the given context as the context to use to manage the marshalling.
070     *
071     * @param request The current request.
072     * @param ctx The context to register.
073     * @since 7.10
074     */
075    public static void registerContext(ServletRequest request, RenderingContext ctx) {
076        request.setAttribute(getContextKey(), ctx);
077    }
078
079    /**
080     * Return the key used to store the context in the request.
081     *
082     * @since 7.10
083     */
084    public static String getContextKey() {
085        return CTX_KEY;
086    }
087
088    /**
089     * Create an {@link RenderingContextBuilder}, fill it with the current {@link HttpServletRequest} and return it.
090     *
091     * @since 7.2
092     */
093    public static RenderingContextBuilder getBuilder(ServletRequest request) {
094        RenderingContextBuilder builder = CtxBuilder.builder();
095        fillContext(builder, request);
096        return builder;
097    }
098
099    /**
100     * Fill an existing with the current {@link HttpServletRequest}.
101     *
102     * @since 7.2
103     */
104    public static RenderingContextBuilder fillContext(RenderingContextBuilder builder, ServletRequest request) {
105        // create a context builder and put base url, session and request
106        builder.param(REQUEST_KEY, request);
107        // for web context, put the base url, the session and the headers
108        if (request instanceof HttpServletRequest) {
109            HttpServletRequest webRequest = (HttpServletRequest) request;
110            // base url
111            @SuppressWarnings("deprecation")
112            String baseURL = VirtualHostHelper.getBaseURL(webRequest);
113            // current session
114            CoreSession session = SessionFactory.getSession(webRequest);
115            builder.base(baseURL).session(session);
116            // gets the locale from the request or takes the server's default
117            Locale locale = request.getLocale();
118            if (locale != null) {
119                builder.locale(locale);
120            }
121            // headers
122            Enumeration<String> headerNames = webRequest.getHeaderNames();
123            while (headerNames.hasMoreElements()) {
124                String headerName = headerNames.nextElement();
125                Enumeration<String> headerValues = webRequest.getHeaders(headerName);
126                while (headerValues.hasMoreElements()) {
127                    builder.param(headerName, headerValues.nextElement());
128                }
129            }
130        }
131        // parameters
132        for (Map.Entry<String, String[]> parameter : request.getParameterMap().entrySet()) {
133            builder.paramValues(parameter.getKey(), (Object[]) parameter.getValue());
134        }
135        // attributes
136        Enumeration<String> attributeNames = request.getAttributeNames();
137        while (attributeNames.hasMoreElements()) {
138            String attributeName = attributeNames.nextElement();
139            Object attributeValue = request.getAttribute(attributeName);
140            builder.param(attributeName, attributeValue);
141        }
142        return builder;
143    }
144
145}