PageRenderTime 1ms CodeModel.GetById 34ms app.highlight 4ms RepoModel.GetById 0ms app.codeStats 0ms

/extras/guice/src/main/java/org/atmosphere/guice/AtmosphereGuiceServlet.java

https://github.com/ayush/atmosphere
Java | 183 lines | 56 code | 17 blank | 110 comment | 6 complexity | 9f50353e738eac8a4f63ce1ca639c109 MD5 | raw file
  1/*
  2 * Copyright 2011 Jeanfrancois Arcand
  3 *
  4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5 * use this file except in compliance with the License. You may obtain a copy of
  6 * the License at
  7 *
  8 * http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 13 * License for the specific language governing permissions and limitations under
 14 * the License.
 15 */
 16/*
 17 *
 18 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 19 *
 20 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 21 *
 22 * The contents of this file are subject to the terms of either the GNU
 23 * General Public License Version 2 only ("GPL") or the Common Development
 24 * and Distribution License("CDDL") (collectively, the "License").  You
 25 * may not use this file except in compliance with the License. You can obtain
 26 * a copy of the License at https://jersey.dev.java.net/CDDL+GPL.html
 27 * or jersey/legal/LICENSE.txt.  See the License for the specific
 28 * language governing permissions and limitations under the License.
 29 *
 30 * When distributing the software, include this License Header Notice in each
 31 * file and include the License file at jersey/legal/LICENSE.txt.
 32 * Sun designates this particular file as subject to the "Classpath" exception
 33 * as provided by Sun in the GPL Version 2 section of the License file that
 34 * accompanied this code.  If applicable, add the following below the License
 35 * Header, with the fields enclosed by brackets [] replaced by your own
 36 * identifying information: "Portions Copyrighted [year]
 37 * [name of copyright owner]"
 38 *
 39 * Contributor(s):
 40 *
 41 * If you wish your version of this file to be governed by only the CDDL or
 42 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 43 * elects to include this software in this distribution under the [CDDL or GPL
 44 * Version 2] license."  If you don't indicate a single choice of license, a
 45 * recipient has the option to distribute your version of this file under
 46 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 47 * its licensees as provided above.  However, if you add GPL Version 2 code
 48 * and therefore, elected the GPL Version 2 license, then the option applies
 49 * only if the new code is made subject to such option by the copyright
 50 * holder.
 51 */
 52
 53package org.atmosphere.guice;
 54
 55import com.google.inject.Injector;
 56import com.google.inject.Key;
 57import com.google.inject.TypeLiteral;
 58import com.google.inject.name.Names;
 59import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
 60import org.atmosphere.cpr.AtmosphereServlet;
 61import org.atmosphere.handler.ReflectorServletProcessor;
 62import org.slf4j.Logger;
 63import org.slf4j.LoggerFactory;
 64
 65import javax.servlet.ServletConfig;
 66import javax.servlet.ServletException;
 67import java.util.Map;
 68
 69/**
 70 * Google Guice Integration. To use it, just do in web.xml:
 71 *
 72 * <blockquote><code>
 73     &lt;web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 74        xmlns:j2ee = "http://java.sun.com/xml/ns/j2ee"
 75        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 76        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt;
 77        &lt;listener&gt;
 78            &lt;listener-class&gt;org.atmosphere.samples.guice.GuiceChatConfig&lt;/listener-class&gt;
 79        &lt;/listener&gt;
 80        &lt;description&gt;Atmosphere Chat&lt;/description&gt;
 81        &lt;display-name&gt;Atmosphere Chat&lt;/display-name&gt;
 82        &lt;servlet&gt;
 83            &lt;description&gt;AtmosphereServlet&lt;/description&gt;
 84            &lt;servlet-name&gt;AtmosphereServlet&lt;/servlet-name&gt;
 85            &lt;servlet-class&gt;org.atmosphere.guice.AtmosphereGuiceServlet&lt;/servlet-class&gt;
 86            &lt;load-on-startup&gt;0&lt;/load-on-startup&gt;
 87        &lt;/servlet&gt;
 88        &lt;servlet-mapping&gt;
 89            &lt;servlet-name&gt;AtmosphereServlet&lt;/servlet-name&gt;
 90            &lt;url-pattern&gt;/chat/*&lt;/url-pattern&gt;
 91        &lt;/servlet-mapping&gt;
 92    &lt;/web-app&gt;
 93
 94    and then
 95
 96    public class GuiceConfig extends GuiceServletContextListener {
 97
 98        @Override
 99        protected Injector getInjector() {
100            return Guice.createInjector(new ServletModule() {
101                @Override
102                protected void configureServlets() {
103                    bind(PubSubTest.class);
104                    bind(new TypeLiteral&lt;Map&lt;String, String&gt;&gt;() {
105                        }).annotatedWith(Names.named(AtmosphereGuiceServlet.JERSEY_PROPERTIES)).toInstance(
106                            Collections.&lt;String, String>emptyMap());
107                }
108            });
109        }
110    }
111 </code></blockquote>
112 *
113 * @author Jeanfrancois Arcand
114 * @author Richard Wallace
115 */
116public class AtmosphereGuiceServlet extends AtmosphereServlet {
117
118    private static final Logger logger = LoggerFactory.getLogger(AtmosphereGuiceServlet.class);
119    public static final String JERSEY_PROPERTIES = AtmosphereGuiceServlet.class.getName() + ".properties";
120    private static final String GUICE_FILTER = "com.google.inject.servlet.GuiceFilter";
121
122    private boolean guiceInstalled = false;
123
124    /**
125     * Install Guice event if other extension has been already installed.
126     * @param sc {@link javax.servlet.ServletConfig}
127     * @throws ServletException
128     */
129    @Override
130    protected void loadConfiguration(ServletConfig sc) throws ServletException {
131        super.loadConfiguration(sc);
132
133        if (!guiceInstalled) {
134            detectSupportedFramework(sc);
135        }
136    }
137
138    /**
139     * Auto-detect Jersey when no atmosphere.xml file are specified.
140     *
141     * @param sc {@link javax.servlet.ServletConfig}
142     * @return true if Jersey classes are detected
143     */
144    @Override
145    protected boolean detectSupportedFramework(ServletConfig sc) {
146        Injector injector = (Injector) config.getServletContext().getAttribute(Injector.class.getName());
147        GuiceContainer guiceServlet = injector.getInstance(GuiceContainer.class);
148
149        setUseStreamForFlushingComments(false);
150        ReflectorServletProcessor rsp = new ReflectorServletProcessor();
151        setDefaultBroadcasterClassName(JERSEY_BROADCASTER);
152        setUseStreamForFlushingComments(true);
153
154        rsp.setServlet(guiceServlet);
155        rsp.setFilterClassName(GUICE_FILTER);
156        getAtmosphereConfig().setSupportSession(false);
157
158        String mapping = sc.getInitParameter(PROPERTY_SERVLET_MAPPING);
159        if (mapping == null) {
160            mapping = "/*";
161        }
162
163        try {
164            Map<String, String> props = injector.getInstance(
165                    Key.get(new TypeLiteral<Map<String, String>>() {},Names.named(JERSEY_PROPERTIES)));
166
167
168            if (props != null) {
169                for (String p : props.keySet()) {
170                    addInitParameter(p, props.get(p));
171                }
172            }
173        } catch (Exception ex) {
174            // Do not fail
175            logger.debug("failed to add Jersey init parameters to Atmosphere servlet", ex);
176        }
177
178        addAtmosphereHandler(mapping, rsp);
179        guiceInstalled = true;
180        return true;
181    }
182}
183