001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.ecm.webengine.app.jersey;
018
019import java.io.IOException;
020
021import javax.servlet.ServletException;
022import javax.servlet.http.HttpServletRequest;
023import javax.servlet.http.HttpServletResponse;
024
025import org.nuxeo.ecm.webengine.WebEngine;
026import org.nuxeo.ecm.webengine.jaxrs.Reloadable;
027import org.nuxeo.runtime.api.Framework;
028
029import com.sun.jersey.spi.container.servlet.ServletContainer;
030
031/**
032 * JAX-RS servlet based on jersey servlet to provide hot reloading.
033 * <p>
034 * Use it as the webengine servlet in web.xml if you want hot reload, otherwise use {@link ServletContainer}.
035 *
036 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
037 */
038public class ReloadingJerseyServlet extends ServletContainer implements Reloadable {
039
040    private static final long serialVersionUID = 1L;
041
042    protected WebEngine engine;
043
044    @Override
045    public void init() throws ServletException {
046        super.init();
047        engine = Framework.getLocalService(WebEngine.class);
048    }
049
050    @Override
051    public void destroy() {
052        engine = null;
053        super.destroy();
054    }
055
056    @Override
057    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
058        if (engine == null) {
059            engine = Framework.getLocalService(WebEngine.class);
060        }
061        String method = request.getMethod().toUpperCase();
062        if (!"GET".equals(method)) {
063            // force reading properties because jersey is consuming one
064            // character
065            // from the input stream - see WebComponent.isEntityPresent.
066            request.getParameterMap();
067        }
068        super.service(request, response);
069    }
070
071    public synchronized void reloadIfNeeded() {
072        if (engine.tryReload()) {
073            reload();
074        }
075    }
076}