001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004
005 This file is part of Granite Data Services.
006
007 Granite Data Services is free software; you can redistribute it and/or modify
008 it under the terms of the GNU Library General Public License as published by
009 the Free Software Foundation; either version 2 of the License, or (at your
010 option) any later version.
011
012 Granite Data Services is distributed in the hope that it will be useful, but
013 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015 for more details.
016
017 You should have received a copy of the GNU Library General Public License
018 along with this library; if not, see <http://www.gnu.org/licenses/>.
019 */
020
021 package org.granite.tide.cdi;
022
023 import javax.enterprise.context.RequestScoped;
024 import javax.enterprise.inject.Default;
025 import javax.enterprise.inject.Instance;
026 import javax.enterprise.inject.Produces;
027 import javax.enterprise.util.AnnotationLiteral;
028 import javax.inject.Inject;
029 import javax.servlet.ServletContext;
030
031 import org.granite.context.GraniteContext;
032 import org.granite.gravity.Gravity;
033 import org.granite.gravity.GravityManager;
034 import org.granite.messaging.webapp.HttpGraniteContext;
035
036
037 /**
038 * TideGravity produces the Gravity instance for injection in CDI beans
039 *
040 * @author William DRAI
041 */
042 public class TideGravity {
043
044 @Inject
045 Instance<ServletContext> servletContextInstance;
046
047 @SuppressWarnings("serial")
048 private static final AnnotationLiteral<Default> DEFAULT_LITERAL = new AnnotationLiteral<Default>() {};
049
050 @Produces @RequestScoped
051 public Gravity getGravity() {
052
053 ServletContext servletContext = null;
054
055 if (!servletContextInstance.isUnsatisfied()) {
056 // Use ServletContext exposed with @Default qualifier (with Seam Servlet for example)
057 servletContext = servletContextInstance.select(DEFAULT_LITERAL).get();
058 }
059 else {
060 // If not found, look in GraniteContext
061 GraniteContext graniteContext = GraniteContext.getCurrentInstance();
062 if (graniteContext == null || !(graniteContext instanceof HttpGraniteContext))
063 throw new RuntimeException("Gravity not found: not in a GraniteDS HTTP context");
064
065 servletContext = ((HttpGraniteContext)graniteContext).getServletContext();
066 }
067
068 return GravityManager.getGravity(servletContext);
069 }
070 }