001/*
002 * (C) Copyright 2017 Nuxeo (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 *     Thomas Roger
018 */
019
020package org.nuxeo.web.ui;
021
022import java.io.IOException;
023
024import javax.servlet.Filter;
025import javax.servlet.FilterChain;
026import javax.servlet.FilterConfig;
027import javax.servlet.ServletException;
028import javax.servlet.ServletRequest;
029import javax.servlet.ServletResponse;
030import javax.servlet.http.HttpServletRequest;
031import javax.servlet.http.HttpServletResponse;
032
033import org.nuxeo.ecm.platform.url.api.DocumentView;
034import org.nuxeo.ecm.platform.url.api.DocumentViewCodecManager;
035import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
036import org.nuxeo.runtime.api.Framework;
037
038/**
039 * @since 9.10
040 */
041public class NuxeoJSFWebUIRedirectFilter implements Filter {
042
043    public static final String WEB_UI_CODEC_NAME = "webUIRedirect";
044
045    @Override
046    public void init(FilterConfig filterConfig) {
047        // do nothing
048    }
049
050    @Override
051    public void destroy() {
052        // do nothing
053    }
054
055    @Override
056    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
057            throws IOException, ServletException {
058        HttpServletRequest httpRequest = (HttpServletRequest) request;
059        HttpServletResponse httpResponse = (HttpServletResponse) response;
060
061        DocumentViewCodecManager docViewManager = Framework.getService(DocumentViewCodecManager.class);
062        String requestURL = httpRequest.getRequestURL().toString();
063        String baseURL = VirtualHostHelper.getBaseURL(request);
064        DocumentView docView = docViewManager.getDocumentViewFromUrl(requestURL, true, baseURL);
065        if (docView != null) {
066            String url = docViewManager.getUrlFromDocumentView(WEB_UI_CODEC_NAME, docView, true, baseURL);
067            if (url != null) {
068                httpResponse.sendRedirect(url);
069                return;
070            }
071        }
072        chain.doFilter(request, response);
073    }
074}