diff --git a/pom.xml b/pom.xml index 1f67e839a..080cbc115 100644 --- a/pom.xml +++ b/pom.xml @@ -60,6 +60,13 @@ scm:git:git@github.com:caelum/vraptor.git + + + org.jboss.weld.servlet + weld-servlet + 1.1.7.Final + + cglib @@ -108,90 +115,6 @@ 1.3.1 - - - org.springframework - spring-aop - 3.0.5.RELEASE - - - org.springframework - spring-asm - 3.0.5.RELEASE - - - org.springframework - spring-beans - 3.0.5.RELEASE - - - org.springframework - spring-context - 3.0.5.RELEASE - - - org.springframework - spring-core - 3.0.5.RELEASE - - - org.springframework - spring-expression - 3.0.5.RELEASE - - - org.springframework - spring-web - 3.0.5.RELEASE - - - org.aspectj - aspectjrt - 1.6.9 - - - - - - com.google.inject - guice - 3.0 - true - - - com.google.inject.extensions - guice-multibindings - 3.0 - true - - - aopalliance - aopalliance - 1.0 - - - javax.inject - javax.inject - 1 - true - - - net.sf.scannotation - scannotation - 1.0.2 - - - - - - org.picocontainer - picocontainer - 2.13.6 - true - - - - org.codehaus.jettison @@ -207,54 +130,6 @@ - - - jfree - jfreechart - 1.0.12 - - - - - - org.hibernate - hibernate - 3.2.0.ga - true - - - javax.transaction - jta - - - - - org.hibernate - hibernate-annotations - 3.3.1.GA - true - - - org.hibernate - hibernate-validator - 4.0.2.GA - new - true - - - org.hibernate - hibernate-validator - 3.1.0.GA - true - - - javax.validation - validation-api - 1.0.0.GA - true - - - br.com.caelum iogi @@ -287,7 +162,6 @@ true - org.hamcrest hamcrest-core diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/VRaptor.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/VRaptor.java index 419557755..c0b430bb5 100644 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/VRaptor.java +++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/VRaptor.java @@ -51,16 +51,14 @@ * @author Fabio Kung */ public class VRaptor implements Filter { - private ContainerProvider provider; + private ServletContext servletContext; - private StaticContentHandler staticHandler; + @Inject private StaticContentHandler staticHandler; private static final Logger logger = LoggerFactory.getLogger(VRaptor.class); public void destroy() { - provider.stop(); - provider = null; servletContext = null; } @@ -103,10 +101,5 @@ public void init(FilterConfig cfg) throws ServletException { logger.info("VRaptor 3.5.0-SNAPSHOT successfuly initialized"); } - void init(ContainerProvider provider) { - this.provider = provider; - this.provider.start(servletContext); - this.staticHandler = provider.getContainer().instanceFor(StaticContentHandler.class); - } } diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/config/BasicConfiguration.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/config/BasicConfiguration.java deleted file mode 100644 index 2bd82857e..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/config/BasicConfiguration.java +++ /dev/null @@ -1,146 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.config; - -import java.lang.reflect.InvocationTargetException; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ioc.ContainerProvider; -import br.com.caelum.vraptor.ioc.guice.GuiceProvider; -import br.com.caelum.vraptor.ioc.pico.PicoProvider; -import br.com.caelum.vraptor.ioc.spring.MissingConfigurationException; -import br.com.caelum.vraptor.ioc.spring.SpringProvider; - -/** - * VRaptors servlet context init parameter configuration reader. - * - * @author Guilherme Silveira - */ -public class BasicConfiguration { - - private static final Logger logger = LoggerFactory.getLogger(BasicConfiguration.class); - - /** - * context parameter that represents the class of IoC provider - */ - public static final String CONTAINER_PROVIDER = "br.com.caelum.vraptor.provider"; - - /** - * context parameter that represents application character encoding - */ - public static final String ENCODING = "br.com.caelum.vraptor.encoding"; - - /** - * context parameter that represents the base package(s) of your application - */ - public static final String BASE_PACKAGES_PARAMETER_NAME = "br.com.caelum.vraptor.packages"; - - /** - * Disables/enables classpath scanning - */ - public static final String SCANNING_PARAM = "br.com.caelum.vraptor.scanning"; - - private final ServletContext servletContext; - - public BasicConfiguration(ServletContext servletContext) { - this.servletContext = servletContext; - } - - public ContainerProvider getProvider() throws ServletException { - Class providerType = getProviderType(); - logger.info("Using {} as Container Provider", providerType); - try { - return providerType.getDeclaredConstructor().newInstance(); - } catch (InvocationTargetException e) { - throw new ServletException(e.getCause()); - } catch (Exception e) { - throw new ServletException(e); - } - } - - private Class getProviderType() { - String provider = servletContext.getInitParameter(CONTAINER_PROVIDER); - if (provider != null) { - try { - return (Class) Class.forName(provider); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("You must configure a class that exists on the " - + CONTAINER_PROVIDER + " context param.", e); - } - } - if (classExists("org.springframework.context.ApplicationContext")) { - return SpringProvider.class; - } - if (classExists("com.google.inject.Guice")) { - return GuiceProvider.class; - } - - if (classExists("org.picocontainer.PicoContainer")) { - return PicoProvider.class; - } - throw new IllegalArgumentException("You don't have any DI container jars on your classpath. " + - "You can find them on vraptor-3.x.x.zip, so you must put one of the " + - "lib/containers/ jars on your classpath, where is your preferred container."); - } - - private boolean classExists(String className) { - try { - Class.forName(className); - return true; - } catch (ClassNotFoundException e) { - return false; - } - } - - public boolean hasBasePackages() { - return servletContext.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME) != null; - } - - public String[] getBasePackages() { - String packages = servletContext.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME); - if (packages == null) { - throw new MissingConfigurationException(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME - + " context-param not found in web.xml. Set this parameter with your base package"); - } - return packages.trim().split(",\\s*"); - } - - public String getEncoding() { - return servletContext.getInitParameter(ENCODING); - } - - public String getWebinfClassesDirectory() { - return servletContext.getRealPath("/WEB-INF/classes/"); - } - - public ServletContext getServletContext() { - return servletContext; - } - - public boolean isClasspathScanningEnabled() { - String scanningParam = servletContext.getInitParameter(SCANNING_PARAM); - logger.info("{} = {}", SCANNING_PARAM, servletContext.getInitParameter(SCANNING_PARAM)); - return scanningParam == null || !scanningParam.trim().equals("disabled"); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/http/EncodingHandlerFactory.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/http/EncodingHandlerFactory.java index 18aca7893..73bb582df 100644 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/http/EncodingHandlerFactory.java +++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/http/EncodingHandlerFactory.java @@ -19,18 +19,20 @@ import javax.servlet.ServletContext; -import br.com.caelum.vraptor.config.BasicConfiguration; import br.com.caelum.vraptor.ioc.ApplicationScoped; import br.com.caelum.vraptor.ioc.ComponentFactory; @ApplicationScoped public class EncodingHandlerFactory implements ComponentFactory{ - + /** + * context parameter that represents application character encoding + */ + public static final String ENCODING = "br.com.caelum.vraptor.encoding"; private final EncodingHandler handler; public EncodingHandlerFactory(ServletContext context) { - String encoding = new BasicConfiguration(context).getEncoding(); + String encoding = context.getInitParameter(ENCODING); this.handler = encoding == null? new NullEncodingHandler() : new WebXmlEncodingHandler(encoding); } diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/ContainerProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/ContainerProvider.java deleted file mode 100644 index cb23c0e5e..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/ContainerProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc; - -import javax.servlet.ServletContext; - -import br.com.caelum.vraptor.core.Execution; -import br.com.caelum.vraptor.core.RequestInfo; - -/** - * A container provider, i.e. spring, pico, guice, tapestry and so on. - * - * @author guilherme silveira - */ -public interface ContainerProvider { - - T provideForRequest(RequestInfo vraptorRequest, Execution execution); - - void stop(); - - void start(ServletContext context); - - Container getContainer(); - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/AbstractScope.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/AbstractScope.java deleted file mode 100644 index 30e216e25..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/AbstractScope.java +++ /dev/null @@ -1,93 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import br.com.caelum.vraptor.interceptor.TypeNameExtractor; - -import com.google.inject.Inject; -import com.google.inject.Key; -import com.google.inject.Provider; -import com.google.inject.Scope; - -/** - * - * @author Lucas Cavalcanti - * @since 3.3.0 - * - */ -public abstract class AbstractScope implements Scope { - - enum NullObject { INSTANCE } - - static interface ScopeHolder { - Object getAttribute(String name); - void setAttribute(String name, Object value); - } - - private TypeNameExtractor extractor; - - @Inject - public void setExtractor(TypeNameExtractor extractor) { - this.extractor = extractor; - } - - abstract ScopeHolder getHolder(); - abstract String getScopeName(); - - public Provider scope(final Key key, final Provider creator) { - return new ScopedProvider(key, creator); - } - - private class ScopedProvider implements Provider { - private final Key key; - private final Provider creator; - private String name; - - private ScopedProvider(Key key, Provider creator) { - this.key = key; - this.creator = creator; - } - - public T get() { - ScopeHolder holder = getHolder(); - synchronized (holder) { - Object obj = holder.getAttribute(getName()); - if (NullObject.INSTANCE == obj) { - return null; - } - T t = (T) obj; - if (t == null) { - t = creator.get(); - holder.setAttribute(getName(), (t != null) ? t : NullObject.INSTANCE); - } - return t; - } - } - - @Override - public String toString() { - return String.format("%s[%s]", creator, getScopeName()); - } - - private String getName() { - if (name == null) { - name = extractor.nameFor(key.getTypeLiteral().getType()); - } - return name; - } - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/AllImplementationsProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/AllImplementationsProvider.java deleted file mode 100644 index a2e664923..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/AllImplementationsProvider.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * - */ -package br.com.caelum.vraptor.ioc.guice; - -import java.util.ArrayList; -import java.util.List; - -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.google.inject.Provider; - -final class AllImplementationsProvider implements Provider> { - private List> types = new ArrayList>(); - private Injector injector; - @Inject - public void setInjector(Injector injector) { - this.injector = injector; - } - public void addType(Class type) { - types.add(type); - } - public List get() { - List instances = new ArrayList(); - for (Class t : types) { - instances.add(injector.getInstance(t)); - } - return instances; - } -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ApplicationCustomScope.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ApplicationCustomScope.java deleted file mode 100644 index 71785fdfc..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ApplicationCustomScope.java +++ /dev/null @@ -1,64 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import java.util.ArrayList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.inject.Key; -import com.google.inject.Provider; -import com.google.inject.Scopes; - -/** - * Application Scope for guice. - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * @since 3.2 - * - */ -public class ApplicationCustomScope implements LifecycleScope { - - private static final Logger logger = LoggerFactory.getLogger(ApplicationCustomScope.class); - - private List listeners; - - public void registerDestroyListener(LifecycleListener listener) { - listeners.add(listener); - } - - public void start() { - listeners = new ArrayList(); - } - - public void stop() { - for (LifecycleListener listener : listeners) { - try { - listener.onEvent(); - } catch (Exception e) { - logger.warn("Error while invoking PreDestroy", e); - } - } - } - - public Provider scope(Key key, Provider provider) { - return Scopes.SINGLETON.scope(key, provider); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ComponentFactoryProviderAdapter.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ComponentFactoryProviderAdapter.java deleted file mode 100644 index e702d1e4f..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ComponentFactoryProviderAdapter.java +++ /dev/null @@ -1,43 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import br.com.caelum.vraptor.ioc.ComponentFactory; - -import com.google.inject.Inject; -import com.google.inject.Provider; - -/** - * An adapter from VRaptor's ComponentFactory to Guice's Provider - * - * @author Lucas Cavalcanti - * @since 3.2 - * - */ -class ComponentFactoryProviderAdapter implements Provider { - - private final ComponentFactory factory; - - @Inject - public ComponentFactoryProviderAdapter(ComponentFactory factory) { - this.factory = factory; - } - - public T get() { - return factory.getInstance(); - } - -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/GuiceComponentRegistry.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/GuiceComponentRegistry.java deleted file mode 100644 index d726efbc0..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/GuiceComponentRegistry.java +++ /dev/null @@ -1,176 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ComponentRegistry; -import br.com.caelum.vraptor.ioc.Cacheable; -import br.com.caelum.vraptor.ioc.ComponentFactory; -import br.com.caelum.vraptor.ioc.ComponentFactoryIntrospector; -import br.com.caelum.vraptor.ioc.StereotypeHandler; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.inject.Binder; -import com.google.inject.Inject; -import com.google.inject.Provider; -import com.google.inject.Scope; -import com.google.inject.ScopeAnnotation; -import com.google.inject.TypeLiteral; -import com.google.inject.binder.ScopedBindingBuilder; -import com.google.inject.matcher.Matchers; -import com.google.inject.multibindings.Multibinder; -import com.google.inject.spi.TypeEncounter; -import com.google.inject.spi.TypeListener; -import com.google.inject.util.Types; - -/** - * ComponentRegistry for Guice - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * @since 3.2 - * - */ -public class GuiceComponentRegistry implements ComponentRegistry { - - private static final Logger logger = LoggerFactory.getLogger(GuiceComponentRegistry.class); - - private final Binder binder; - - private final Set> boundClasses = new HashSet>(); - private final Set> listTypes = new HashSet>(); - - private final Multibinder stereotypeHandlers; - - public GuiceComponentRegistry(Binder binder, Multibinder stereotypeHandlers) { - this.binder = binder; - this.stereotypeHandlers = stereotypeHandlers; - } - public void register(Class requiredType, Class componentType) { - boundClasses.add(requiredType); - logger.debug("Binding {} to {}", requiredType, componentType); - if (StereotypeHandler.class.isAssignableFrom(requiredType)) { - stereotypeHandlers.addBinding().to(requiredType); - } - ScopedBindingBuilder binding = bindToConstructor(requiredType, componentType); - if (defaultScope(componentType)) { - binding.in(GuiceProvider.REQUEST); - } - registerFactory(componentType); - } - - private boolean defaultScope(Class componentType) { - for(Annotation annotation : componentType.getAnnotations()) { - if (annotation.annotationType().isAnnotationPresent(ScopeAnnotation.class)) { - return false; - } - } - return true; - } - public void deepRegister(Class componentType) { - register(componentType, componentType); - deepRegister(componentType, componentType); - } - - private void deepRegister(Class required, Class component) { - if (required == null || required.equals(Object.class)) { - return; - } - if (boundClasses.add(required)) { - logger.debug("Binding {} to {}", required, component); - binder.bind(required).to(component); - } else { - logger.debug("Ignoring binding of {} to {}", required, component); - } - - for (Class c : required.getInterfaces()) { - deepRegister(c, component); - } - - deepRegister(required.getSuperclass(), component); - } - - public void registerInScope(Map classes, Scope scope) { - for (Entry entry : classes.entrySet()) { - bindToConstructor(entry.getKey(), entry.getValue()).in(scope); - registerFactory(entry.getValue()); - } - } - private ScopedBindingBuilder bindToConstructor(Class requiredType, Class componentType) { - if (componentType.isAnnotationPresent(Cacheable.class)) { - return binder.bind(requiredType).annotatedWith(Cacheable.class).toConstructor(componentType.getDeclaredConstructors()[0]); - } - Constructor constructor = getConstructor(componentType); - for (Type type : constructor.getGenericParameterTypes()) { - if (type instanceof ParameterizedType) { - ParameterizedType ptype =((ParameterizedType) type); - if (ptype.getRawType() instanceof Class && List.class.isAssignableFrom((Class) ptype.getRawType()) - && ptype.getRawType() instanceof Class && !listTypes.contains(ptype.getActualTypeArguments()[0])) { - listTypes.add((Class) ptype.getActualTypeArguments()[0]); - registerListType((Class) ptype.getActualTypeArguments()[0], binder); - } - } - } - return binder.bind(requiredType).toConstructor(constructor); - } - private Constructor getConstructor(Class componentType) { - Constructor[] constructors = componentType.getDeclaredConstructors(); - Iterable filteredConstructor = Iterables.filter(Lists.newArrayList(constructors), new Predicate() { - - public boolean apply(Constructor constructor) { - return constructor.isAnnotationPresent(Inject.class); - } - - }); - return Iterables.getFirst(filteredConstructor, constructors[0]); - } - - private void registerFactory(Class componentType) { - if (ComponentFactory.class.isAssignableFrom(componentType)) { - final Class target = new ComponentFactoryIntrospector().targetTypeForComponentFactory(componentType); - Type adapterType = Types.newParameterizedType(ComponentFactoryProviderAdapter.class, target); - Type factoryType = Types.newParameterizedType(ComponentFactory.class, target); -// binder.bind(TypeLiteral.get(adapterType)); - binder.bind(TypeLiteral.get(factoryType)).to(componentType); - binder.bind(target).toProvider((TypeLiteral) TypeLiteral.get(adapterType)); - } - } - private void registerListType(Class type, Binder binder) { - final AllImplementationsProvider provider = new AllImplementationsProvider(); - binder.bindListener(VRaptorAbstractModule.type(Matchers.subclassesOf(type)), new TypeListener() { - public void hear(TypeLiteral literal, TypeEncounter encounter) { - provider.addType(literal.getRawType()); - } - }); - binder.bind(TypeLiteral.get(Types.listOf(type))).toProvider((Provider)provider); - binder.requestInjection(provider); - } - -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/GuiceProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/GuiceProvider.java deleted file mode 100644 index c12f5ff4c..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/GuiceProvider.java +++ /dev/null @@ -1,152 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import java.util.Set; - -import javax.servlet.ServletContext; - -import br.com.caelum.vraptor.ComponentRegistry; -import br.com.caelum.vraptor.config.BasicConfiguration; -import br.com.caelum.vraptor.core.Execution; -import br.com.caelum.vraptor.core.RequestInfo; -import br.com.caelum.vraptor.ioc.Container; -import br.com.caelum.vraptor.ioc.ContainerProvider; -import br.com.caelum.vraptor.ioc.StereotypeHandler; -import br.com.caelum.vraptor.ioc.spring.VRaptorRequestHolder; -import br.com.caelum.vraptor.scan.WebAppBootstrap; -import br.com.caelum.vraptor.scan.WebAppBootstrapFactory; - -import com.google.inject.Binder; -import com.google.inject.ConfigurationException; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Module; -import com.google.inject.Stage; -import com.google.inject.TypeLiteral; -import com.google.inject.multibindings.Multibinder; -import com.google.inject.util.Modules; - -/** - * - * A Container Provider that uses Google Guice as DI container. - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * @since 3.2 - * - */ -public class GuiceProvider implements ContainerProvider { - - private boolean stopSession = false; - static final RequestCustomScope REQUEST = new RequestCustomScope(); - static final SessionCustomScope SESSION = new SessionCustomScope(); - static final ApplicationCustomScope APPLICATION = new ApplicationCustomScope(); - - private final class GuiceContainer implements Container { - public T instanceFor(Class type) { - return injector.getInstance(type); - } - - public boolean canProvide(Class type) { - try { - return injector.getProvider(type) != null; - } catch (ConfigurationException e) { - return false; - } - } - } - - private Injector injector; - private GuiceContainer container; - protected ServletContext context; - - public T provideForRequest(RequestInfo request, Execution execution) { - VRaptorRequestHolder.setRequestForCurrentThread(request); - REQUEST.start(); - try { - return execution.insideRequest(container); - } finally { - REQUEST.stop(); - VRaptorRequestHolder.resetRequestForCurrentThread(); - } - } - - @Override - public Container getContainer() { - return container; - } - - public void start(ServletContext context) { - this.context = context; - APPLICATION.start(); - container = new GuiceContainer(); - injector = Guice.createInjector(Stage.PRODUCTION, Modules.override(new VRaptorAbstractModule(context, container)).with(customModule())); - executeStereotypeHandlers(); - injector.injectMembers(REQUEST); - injector.injectMembers(SESSION); - } - - private void executeStereotypeHandlers() { - Set handlers = injector.getInstance(Key.get(new TypeLiteral>() {})); - for (Key key : injector.getAllBindings().keySet()) { - for (StereotypeHandler handler : handlers) { - Class type = key.getTypeLiteral().getRawType(); - if (type.isAnnotationPresent(handler.stereotype())) { - handler.handle(type); - } - } - } - } - - protected Module customModule() { - return new Module() { - public void configure(Binder binder) { - ComponentRegistry registry = new GuiceComponentRegistry(binder, Multibinder.newSetBinder(binder, StereotypeHandler.class)); - BasicConfiguration config = new BasicConfiguration(context); - - // using the new vraptor.scan - WebAppBootstrap webAppBootstrap = new WebAppBootstrapFactory().create(config); - webAppBootstrap.configure(registry); - - // call old-style custom components registration - registerCustomComponents(registry); - } - }; - } - - protected void registerCustomComponents(ComponentRegistry registry) { - /* TODO: For now, this is an empty hook method to enable subclasses to use - * the scanner and register their specific components. - * - * In the future, if we scan the classpath for StereotypeHandlers, we can - * eliminate this hook. - */ - } - - protected void stopSession(Boolean value) { - this.stopSession = value; - } - - public void stop() { - if(stopSession) { - SESSION.stopAll(); - } - APPLICATION.stop(); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/LifecycleListener.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/LifecycleListener.java deleted file mode 100644 index e716ac73b..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/LifecycleListener.java +++ /dev/null @@ -1,29 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -/** - * - * Listen to lifecycles - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * @since 3.2 - * - */ -public interface LifecycleListener { - void onEvent(); -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/LifecycleScope.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/LifecycleScope.java deleted file mode 100644 index 4928f26b9..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/LifecycleScope.java +++ /dev/null @@ -1,31 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import com.google.inject.Scope; - -/** - * - * Extension for Guice Scope in order to support lifecycle callbacks - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * @since 3.2 - * - */ -public interface LifecycleScope extends Scope { - void registerDestroyListener(LifecycleListener listener); -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/RequestCustomScope.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/RequestCustomScope.java deleted file mode 100644 index e70aaef2a..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/RequestCustomScope.java +++ /dev/null @@ -1,85 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.inject.Inject; -import com.google.inject.Provider; - -/** - * Guice's Request Scope. Based on GuiceWeb request scope. - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * @since 3.2 - * - */ -public class RequestCustomScope extends AbstractScope implements LifecycleScope { - - private static final Logger logger = LoggerFactory.getLogger(RequestCustomScope.class); - private final ThreadLocal> listeners = new ThreadLocal>(); - - private Provider provider; - - @Inject - public void setProvider(Provider provider) { - this.provider = provider; - } - - @Override - ScopeHolder getHolder() { - return new ScopeHolder() { - - public void setAttribute(String name, Object value) { - provider.get().setAttribute(name, value); - } - - public Object getAttribute(String name) { - return provider.get().getAttribute(name); - } - }; - } - - @Override - String getScopeName() { - return "REQUEST"; - } - - public void start() { - listeners.set(new ArrayList()); - } - - public void stop() { - for (LifecycleListener listener : listeners.get()) { - try { - listener.onEvent(); - } catch (Exception e) { - logger.warn("Error while invoking PreDestroy", e); - } - } - } - - public void registerDestroyListener(LifecycleListener listener) { - listeners.get().add(listener); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ScopeLifecycleListener.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ScopeLifecycleListener.java deleted file mode 100644 index 7d96c7885..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/ScopeLifecycleListener.java +++ /dev/null @@ -1,101 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import net.vidageek.mirror.dsl.Mirror; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.inject.TypeLiteral; -import com.google.inject.spi.InjectionListener; -import com.google.inject.spi.TypeEncounter; -import com.google.inject.spi.TypeListener; - -/** - * - * Listens for guice bindings - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * @since 3.2 - * - */ -final class ScopeLifecycleListener implements TypeListener { - - private static final Logger logger = LoggerFactory.getLogger(ScopeLifecycleListener.class); - private final LifecycleScope scope; - - public ScopeLifecycleListener(LifecycleScope scope) { - this.scope = scope; - } - - public void hear(TypeLiteral literal, TypeEncounter encounter) { - final List constructs = new ArrayList(); - final List destroys = new ArrayList(); - extractLifecycleMethods(literal, constructs, destroys); - - logger.debug("Registering lifecycle listeners for {}", literal); - - if (!constructs.isEmpty() || !destroys.isEmpty()) { - encounter.register(new LifecycleExecutor(constructs, destroys)); - } - } - - private void extractLifecycleMethods(TypeLiteral literal, final List constructs, - final List destroys) { - for (Method method : new Mirror().on(literal.getRawType()).reflectAll().methods()) { - if (method.isAnnotationPresent(PostConstruct.class)) { - constructs.add(method); - } - - if (method.isAnnotationPresent(PreDestroy.class)) { - destroys.add(method); - } - } - } - - private final class LifecycleExecutor implements InjectionListener { - private final List destroys; - private final List constructs; - - private LifecycleExecutor(List constructs, List destroys) { - this.destroys = destroys; - this.constructs = constructs; - } - - public void afterInjection(final Object instance) { - for (Method method : constructs) { - new Mirror().on(instance).invoke().method(method).withoutArgs(); - } - scope.registerDestroyListener(new LifecycleListener() { - public void onEvent() { - for (Method method : destroys) { - new Mirror().on(instance).invoke().method(method).withoutArgs(); - } - } - }); - } - } - -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/SessionCustomScope.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/SessionCustomScope.java deleted file mode 100644 index 5c4b13f27..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/SessionCustomScope.java +++ /dev/null @@ -1,95 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import javax.servlet.http.HttpSession; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.LinkedListMultimap; -import com.google.common.collect.Multimap; -import com.google.inject.Inject; -import com.google.inject.Provider; - -/** - * Guice's Session Scope. Based on GuiceWeb's session scope. - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * @since 3.2 - * - */ -public class SessionCustomScope extends AbstractScope implements LifecycleScope { - - private static final Logger logger = LoggerFactory.getLogger(SessionCustomScope.class); - - private Multimap listeners = LinkedListMultimap.create(); - - private Provider provider; - - @Inject - public void setProvider(Provider provider) { - this.provider = provider; - } - - @Override - ScopeHolder getHolder() { - return new ScopeHolder() { - - public void setAttribute(String name, Object value) { - provider.get().setAttribute(name, value); - } - - public Object getAttribute(String name) { - return provider.get().getAttribute(name); - } - }; - } - - @Override - String getScopeName() { - return "SESSION"; - } - - public void registerDestroyListener(LifecycleListener listener) { - listeners.put(provider.get().getId(), listener); - } - - public void start(HttpSession session) { - stop(session); - } - - public void stop(HttpSession session) { - for (LifecycleListener listener : listeners.removeAll(session.getId())) { - stop(listener); - } - } - - public void stopAll() { - for (LifecycleListener listener : listeners.values()) { - stop(listener); - } - } - - private void stop(LifecycleListener listener) { - try { - listener.onEvent(); - } catch (Exception e) { - logger.warn("Error while invoking PreDestroy", e); - } - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/SessionScopeListener.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/SessionScopeListener.java deleted file mode 100644 index 5316670b3..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/SessionScopeListener.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package br.com.caelum.vraptor.ioc.guice; - -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SessionScopeListener implements HttpSessionListener { - private static final Logger logger = LoggerFactory.getLogger(SessionScopeListener.class); - public void sessionCreated(HttpSessionEvent event) { - logger.debug("starting session {}", event.getSession().getId()); - GuiceProvider.SESSION.start(event.getSession()); - } - - public void sessionDestroyed(HttpSessionEvent event) { - logger.debug("stopping session {}", event.getSession().getId()); - GuiceProvider.SESSION.stop(event.getSession()); - } -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/VRaptorAbstractModule.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/VRaptorAbstractModule.java deleted file mode 100644 index b435b5ac0..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/guice/VRaptorAbstractModule.java +++ /dev/null @@ -1,162 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.guice; - -import static com.google.inject.matcher.Matchers.annotatedWith; -import static com.google.inject.matcher.Matchers.not; - -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ComponentRegistry; -import br.com.caelum.vraptor.core.BaseComponents; -import br.com.caelum.vraptor.core.RequestInfo; -import br.com.caelum.vraptor.http.MutableRequest; -import br.com.caelum.vraptor.http.MutableResponse; -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.Container; -import br.com.caelum.vraptor.ioc.PrototypeScoped; -import br.com.caelum.vraptor.ioc.RequestScoped; -import br.com.caelum.vraptor.ioc.SessionScoped; -import br.com.caelum.vraptor.ioc.StereotypeHandler; -import br.com.caelum.vraptor.ioc.spring.VRaptorRequestHolder; -import br.com.caelum.vraptor.serialization.xstream.XStreamJSONSerialization; -import br.com.caelum.vraptor.serialization.xstream.XStreamXMLSerialization; - -import com.google.inject.AbstractModule; -import com.google.inject.Provider; -import com.google.inject.Scopes; -import com.google.inject.TypeLiteral; -import com.google.inject.matcher.AbstractMatcher; -import com.google.inject.matcher.Matcher; -import com.google.inject.multibindings.Multibinder; - -/** - * - * An AbstractModule that wires VRaptor components. - * - * @author Lucas Cavalcanti - * @author Sergio Lopes - * - * @since 3.2 - * - */ -public class VRaptorAbstractModule extends AbstractModule { - - private static final Logger logger = LoggerFactory.getLogger(VRaptorAbstractModule.class); - - private final ServletContext context; - private final Container container; - - public VRaptorAbstractModule(ServletContext context, Container container) { - this.context = context; - this.container = container; - } - - @Override - protected void configure() { - bindScope(RequestScoped.class, GuiceProvider.REQUEST); - bindScope(SessionScoped.class, GuiceProvider.SESSION); - bindScope(ApplicationScoped.class, Scopes.SINGLETON); - bindScope(PrototypeScoped.class, Scopes.NO_SCOPE); - - Matcher> isApplication = type(annotatedWith(ApplicationScoped.class)); - Matcher> isSession = type(annotatedWith(SessionScoped.class)); - - bindListener(isApplication, new ScopeLifecycleListener(GuiceProvider.APPLICATION)); - bindListener(isSession, new ScopeLifecycleListener(GuiceProvider.SESSION)); - bindListener(not(isApplication).and(not(isSession)), new ScopeLifecycleListener(GuiceProvider.REQUEST)); - - requestInfoBindings(); - - bind(Container.class).toInstance(container); - - GuiceComponentRegistry registry = new GuiceComponentRegistry(binder(), Multibinder.newSetBinder(binder(), StereotypeHandler.class)); - - bind(ComponentRegistry.class).toInstance(registry); - - registry.registerInScope((Map) BaseComponents.getApplicationScoped(), GuiceProvider.APPLICATION); - registry.registerInScope((Map) BaseComponents.getPrototypeScoped(), Scopes.NO_SCOPE); - registry.registerInScope((Map) BaseComponents.getRequestScoped(), GuiceProvider.REQUEST); - - for (Class converter : BaseComponents.getBundledConverters()) { - registry.register(converter, converter); - } - - - for (Class handler : BaseComponents.getStereotypeHandlers()) { - registry.register(handler, handler); - } - - for (Entry, Class> entry : BaseComponents.getCachedComponents().entrySet()) { - registry.register(entry.getKey(), entry.getValue()); - } - - //XXX - registry.register(XStreamXMLSerialization.class, XStreamXMLSerialization.class); - registry.register(XStreamJSONSerialization.class, XStreamJSONSerialization.class); - - } - - private void requestInfoBindings() { - bind(MutableRequest.class).toProvider(new Provider() { - - public MutableRequest get() { - return VRaptorRequestHolder.currentRequest().getRequest(); - } - }); - - bind(RequestInfo.class).toProvider(new Provider() { - - public RequestInfo get() { - return VRaptorRequestHolder.currentRequest(); - } - }); - - bind(HttpSession.class).toProvider(new Provider() { - - public HttpSession get() { - return VRaptorRequestHolder.currentRequest().getRequest().getSession(); - } - }); - bind(MutableResponse.class).toProvider(new Provider() { - - public MutableResponse get() { - return VRaptorRequestHolder.currentRequest().getResponse(); - } - }); - bind(HttpServletResponse.class).to(MutableResponse.class); - bind(HttpServletRequest.class).to(MutableRequest.class); - bind(ServletContext.class).toInstance(context); - } - - static Matcher> type(final Matcher matcher) { - return new AbstractMatcher>() { - public boolean matches(TypeLiteral literal) { - return matcher.matches(literal.getRawType()); - } - }; - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/ComponentFactoryRegistry.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/ComponentFactoryRegistry.java deleted file mode 100644 index 094e85a9c..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/ComponentFactoryRegistry.java +++ /dev/null @@ -1,31 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.pico; - -import java.util.Map; - -import br.com.caelum.vraptor.ioc.ComponentFactory; - -public interface ComponentFactoryRegistry { - public void register(Class componentFactoryClass); - - public Map, Class> getApplicationMap(); - - public Map, Class> getSessionMap(); - - public Map, Class> getRequestMap(); -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/DefaultComponentFactoryRegistry.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/DefaultComponentFactoryRegistry.java deleted file mode 100644 index 424b2500c..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/DefaultComponentFactoryRegistry.java +++ /dev/null @@ -1,76 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.pico; - -import java.util.HashMap; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.ComponentFactory; -import br.com.caelum.vraptor.ioc.ComponentFactoryIntrospector; -import br.com.caelum.vraptor.ioc.SessionScoped; - -/** - * Registry to all ComponentRegistry classes - * - * @author Sérgio Lopes - */ -@ApplicationScoped -public class DefaultComponentFactoryRegistry implements ComponentFactoryRegistry { - - private static final Logger logger = LoggerFactory.getLogger(DefaultComponentFactoryRegistry.class); - - /* maps from targetClass to componentFactoryClass */ - private final Map, Class> applicationScoped = - new HashMap, Class>(); - private final Map, Class> sessionScoped = - new HashMap, Class>(); - private final Map, Class> requestScoped = - new HashMap, Class>(); - - private ComponentFactoryIntrospector componentFactoryIntrospector = new ComponentFactoryIntrospector(); - - public void register(Class componentFactoryClass) { - Class targetType = componentFactoryIntrospector.targetTypeForComponentFactory(componentFactoryClass); - - if (componentFactoryClass.isAnnotationPresent(ApplicationScoped.class)) { - logger.debug("Registering a ComponentFactory for {} in app scope", targetType.getName()); - applicationScoped.put(targetType, componentFactoryClass); - } else if (componentFactoryClass.isAnnotationPresent(SessionScoped.class)) { - logger.debug("Registering a ComponentFactory for {} in session scope", targetType.getName()); - sessionScoped.put(targetType, componentFactoryClass); - } else { // @RequestScoped - logger.debug("Registering a ComponentFactory for {} in request scope", targetType.getName()); - requestScoped.put(targetType, componentFactoryClass); - } - } - - public Map, Class> getApplicationMap() { - return applicationScoped; - } - - public Map, Class> getSessionMap() { - return sessionScoped; - } - - public Map, Class> getRequestMap() { - return requestScoped; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/Loader.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/Loader.java deleted file mode 100644 index 466aa46b6..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/Loader.java +++ /dev/null @@ -1,27 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.pico; - -/** - * Loads all resources, components and interceptors for vraptor. - * - * @author Guilherme Silveira - */ -public interface Loader { - void loadAll(); -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoBasedContainer.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoBasedContainer.java deleted file mode 100644 index 2f2a3dbf0..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoBasedContainer.java +++ /dev/null @@ -1,49 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.pico; - -import org.picocontainer.MutablePicoContainer; - -import br.com.caelum.vraptor.ioc.Container; - -/** - * A pico container based implementation of a component providing container. - * - * @author Guilherme Silveira - */ -public class PicoBasedContainer implements Container { - - private final MutablePicoContainer container; - - public PicoBasedContainer(MutablePicoContainer container) { - this.container = container; - this.container.addComponent(this); - } - - public T instanceFor(Class type) { - return container.getComponent(type); - } - - public boolean canProvide(Class type) { - return instanceFor(type) != null; - } - - public MutablePicoContainer getContainer() { - return container; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoComponentAdapter.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoComponentAdapter.java deleted file mode 100644 index 466ee6473..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoComponentAdapter.java +++ /dev/null @@ -1,67 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.pico; - -import java.lang.reflect.Type; - -import org.picocontainer.PicoCompositionException; -import org.picocontainer.PicoContainer; -import org.picocontainer.adapters.AbstractAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ioc.ComponentFactory; - -/** - * Pico's ComponentAdapter wrapping VRaptor's ComponentFactory - * - * @author Sérgio Lopes - */ -@SuppressWarnings({"serial"}) -public class PicoComponentAdapter extends AbstractAdapter { - - private static final Logger logger = LoggerFactory.getLogger(PicoComponentAdapter.class); - - private final Class targetType; - private final Class componentFactoryClass; - - public PicoComponentAdapter(Class targetType, Class componentFactoryClass) { - super(targetType, targetType); - - logger.debug("New adapter for {}", componentFactoryClass.getName()); - - this.targetType = targetType; - this.componentFactoryClass = componentFactoryClass; - } - - public Object getComponentInstance(PicoContainer pico, Type type) - throws PicoCompositionException { - - logger.debug("Providing {} instance via {}", targetType.getName(), componentFactoryClass.getName()); - - ComponentFactory componentFactory = pico.getComponent(componentFactoryClass); - return componentFactory.getInstance(); - } - - public String getDescriptor() { - return "Adapter for " + targetType.getName(); - } - - public void verify(PicoContainer pico) throws PicoCompositionException { - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoComponentRegistry.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoComponentRegistry.java deleted file mode 100644 index 96481f79a..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoComponentRegistry.java +++ /dev/null @@ -1,277 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.pico; - -import java.lang.reflect.Constructor; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -import javax.servlet.http.HttpSession; - -import org.picocontainer.Characteristics; -import org.picocontainer.ComponentAdapter; -import org.picocontainer.ComponentMonitor; -import org.picocontainer.DefaultPicoContainer; -import org.picocontainer.MutablePicoContainer; -import org.picocontainer.PicoContainer; -import org.picocontainer.behaviors.Caching; -import org.picocontainer.lifecycle.JavaEE5LifecycleStrategy; -import org.picocontainer.monitors.NullComponentMonitor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.core.RequestInfo; -import br.com.caelum.vraptor.interceptor.TypeNameExtractor; -import br.com.caelum.vraptor.ioc.AbstractComponentRegistry; -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.ComponentFactory; -import br.com.caelum.vraptor.ioc.ComponentFactoryIntrospector; -import br.com.caelum.vraptor.ioc.PrototypeScoped; -import br.com.caelum.vraptor.ioc.SessionScoped; - -/** - * Provides containers, controlling all scopes and registering all different - * components on their respective areas. - * - * @author Guilherme Silveira - * @author Adriano Almeida - * @author Sérgio Lopes - */ -public class PicoComponentRegistry extends AbstractComponentRegistry { - - public static final class AttributeSetterComponentMonitor extends NullComponentMonitor { - private static final long serialVersionUID = 1L; - private final AttributeSetter setter; - - public static interface AttributeSetter { - void setAttribute(String name, Object object); - } - - public AttributeSetterComponentMonitor(AttributeSetter setter) { - this.setter = setter; - } - - @Override - public void instantiated(PicoContainer container, ComponentAdapter componentAdapter, - Constructor constructor, Object instantiated, Object[] injected, long duration) { - final TypeNameExtractor extractor = container.getComponent(TypeNameExtractor.class); - Object object = componentAdapter.getComponentKey(); - if (object instanceof Class) { - Class type = (Class) object; - setter.setAttribute(extractor.nameFor(type), instantiated); - } else if (instantiated != null){ - setter.setAttribute(extractor.nameFor(instantiated.getClass()), instantiated); - } - } - } - - public static final String CONTAINER_SESSION_KEY = PicoComponentRegistry.class.getName() + ".session"; - - private static final Logger logger = LoggerFactory.getLogger(PicoComponentRegistry.class); - - private final Map, Class> applicationScoped = new HashMap, Class>(); - private final Map, Class> sessionScoped = new HashMap, Class>(); - private final Map, Class> requestScoped = new HashMap, Class>(); - private final Map, Class> prototypeScoped = new HashMap, Class>(); - private MutablePicoContainer appContainer; - private boolean initialized = false; - - private final ComponentFactoryRegistry componentFactoryRegistry; - - public PicoComponentRegistry(MutablePicoContainer container, ComponentFactoryRegistry componentFactoryRegistry) { - this.appContainer = container; - this.componentFactoryRegistry = componentFactoryRegistry; - } - - MutablePicoContainer makeChildContainer() { - this.appContainer = appContainer.makeChildContainer(); - return appContainer; - } - - public void register(Class requiredType, Class type) { - logger.debug("Registering {} with {}", requiredType.getName(), type.getName()); - - if (alreadyRegistered(requiredType)) { - logger.debug("Overriding interface {} with {}", requiredType.getName(), type.getName()); - } - registerOnScope(requiredType, type); - - registerComponentFactory(requiredType, type); - checkInitialization(requiredType, type); - } - - private void registerOnScope(Class requiredType, Class type) { - if (type.isAnnotationPresent(ApplicationScoped.class)) { - logger.debug("Registering {} as an application component", type.getName()); - this.applicationScoped.put(requiredType, type); - } else if (type.isAnnotationPresent(SessionScoped.class)) { - logger.debug("Registering {} as a session component", type.getName()); - this.sessionScoped.put(requiredType, type); - } else if (type.isAnnotationPresent(PrototypeScoped.class)) { - logger.debug("Registering {} as a prototype component", type.getName()); - this.prototypeScoped.put(requiredType, type); - } else { - // default behaviour: even without @RequestScoped - logger.debug("Registering {} as a request component", type.getName()); - this.requestScoped.put(requiredType, type); - } - } - - private void checkInitialization(Class requiredType, Class type) { - if (type.isAnnotationPresent(ApplicationScoped.class) && initialized) { - logger.warn("VRaptor was already initialized, the contexts were created but you are registering a component." - + "This is nasty. The original component might already be in use." - + "Avoid doing it: " + requiredType.getName()); - this.appContainer.addComponent(requiredType, type); - - if (isComponentFactory(requiredType, type)) { - Class targetType = new ComponentFactoryIntrospector().targetTypeForComponentFactory(type); - this.appContainer.addAdapter(new PicoComponentAdapter(targetType, (Class>) type)); - } - } - } - - private void registerComponentFactory(Class requiredType, Class type) { - if (isComponentFactory(requiredType, type)) { - componentFactoryRegistry.register((Class>) type); - } - } - - private boolean isComponentFactory(Class requiredType, Class type) { - return ComponentFactory.class.isAssignableFrom(type) && !requiredType.equals(ComponentFactory.class); - } - - /** - * Registers all application scoped elements into the container. - */ - public void init() { - logger.info("Initializing VRaptor IoC Container implementation based on PicoContainer"); - - for (Map.Entry, Class> entry : applicationScoped.entrySet()) { - logger.debug("Initializing application scope with key: {}, for component: {}", - entry.getKey(), entry.getValue()); - this.appContainer.addComponent(entry.getKey(), entry.getValue()); - } - - registerComponentFactories(appContainer, componentFactoryRegistry.getApplicationMap()); - - logger.debug("Session components to initialize: {}", sessionScoped.keySet()); - logger.debug("Requets components to initialize: {}", requestScoped.keySet()); - this.initialized = true; - } - - PicoBasedContainer provideRequestContainer(final RequestInfo request) { - MutablePicoContainer parentContainer; - - if (sessionScoped.isEmpty()) { - logger.debug("There's no @SessionScoped component, so skipping session container creation"); - parentContainer = this.appContainer; - } else { - parentContainer = getSessionContainer(request); - } - - logger.debug("Request components are {}", requestScoped); - ComponentMonitor monitor = new AttributeSetterComponentMonitor(new AttributeSetterComponentMonitor.AttributeSetter() { - public void setAttribute(String name, Object object) { - request.getRequest().setAttribute(name, object); - } - }); - MutablePicoContainer requestContainer = new DefaultPicoContainer(new Caching(), - new JavaEE5LifecycleStrategy(monitor), parentContainer, monitor); - requestContainer.addComponent(HttpSession.class, request.getRequest().getSession()); - - for (Map.Entry, Class> entry : requestScoped.entrySet()) { - requestContainer.addComponent(entry.getKey(), entry.getValue()); - } - for (Map.Entry, Class> entry : prototypeScoped.entrySet()) { - requestContainer.as(Characteristics.NO_CACHE).addComponent(entry.getKey(), entry.getValue()); - } - requestContainer.addComponent(request).addComponent(request.getRequest()).addComponent(request.getResponse()); - - registerComponentFactories(requestContainer, componentFactoryRegistry.getRequestMap()); - - return new PicoBasedContainer(requestContainer); - } - - private MutablePicoContainer getSessionContainer(RequestInfo request) { - HttpSession session = request.getRequest().getSession(); - MutablePicoContainer sessionScope = (MutablePicoContainer) session.getAttribute(CONTAINER_SESSION_KEY); - if (sessionScope == null) { - sessionScope = createSessionContainer(session); - } - return sessionScope; - } - - private boolean alreadyRegistered(Class interfaceType) { - for (Map, Class> scope : new Map[]{applicationScoped, sessionScoped, requestScoped, prototypeScoped}) { - if (scope.containsKey(interfaceType)) { - scope.remove(interfaceType); - return true; - } - } - return false; - } - - private MutablePicoContainer createSessionContainer(final HttpSession session) { - ComponentMonitor monitor = new AttributeSetterComponentMonitor(new AttributeSetterComponentMonitor.AttributeSetter() { - public void setAttribute(String name, Object object) { - session.setAttribute(name, object); - } - }); - MutablePicoContainer sessionContainer = new DefaultPicoContainer(new Caching(), - new JavaEE5LifecycleStrategy(monitor), this.appContainer, monitor); - - sessionContainer.addComponent(HttpSession.class, session); - session.setAttribute(CONTAINER_SESSION_KEY, sessionContainer); - - logger.debug("Session components are {}", sessionScoped); - - for (Map.Entry, Class> entry : sessionScoped.entrySet()) { - sessionContainer.addComponent(entry.getKey(), entry.getValue()); - } - - registerComponentFactories(sessionContainer, componentFactoryRegistry.getSessionMap()); - - sessionContainer.start(); - return sessionContainer; - } - - /** - * Register all component factories found in classpath scanning - * - * @param container - * @param componentFactoryMap - */ - private void registerComponentFactories(MutablePicoContainer container, Map, Class> componentFactoryMap) { - for (Class targetType : componentFactoryMap.keySet()) { - container.addAdapter(new PicoComponentAdapter(targetType, componentFactoryMap.get(targetType))); - } - } - - public Collection> getAllRegisteredApplicationScopedComponents() { - Collection> components = new HashSet>(); - components.addAll(applicationScoped.values()); - components.addAll(sessionScoped.values()); - components.addAll(requestScoped.values()); - components.addAll(prototypeScoped.values()); - return components; - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoProvider.java deleted file mode 100644 index 306e249cd..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/pico/PicoProvider.java +++ /dev/null @@ -1,201 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.pico; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.ServletContext; - -import org.picocontainer.DefaultPicoContainer; -import org.picocontainer.MutablePicoContainer; -import org.picocontainer.behaviors.Caching; -import org.picocontainer.lifecycle.JavaEE5LifecycleStrategy; -import org.picocontainer.monitors.NullComponentMonitor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ComponentRegistry; -import br.com.caelum.vraptor.Converter; -import br.com.caelum.vraptor.config.BasicConfiguration; -import br.com.caelum.vraptor.core.BaseComponents; -import br.com.caelum.vraptor.core.Execution; -import br.com.caelum.vraptor.core.RequestInfo; -import br.com.caelum.vraptor.ioc.Container; -import br.com.caelum.vraptor.ioc.ContainerProvider; -import br.com.caelum.vraptor.ioc.StereotypeHandler; -import br.com.caelum.vraptor.scan.WebAppBootstrap; -import br.com.caelum.vraptor.scan.WebAppBootstrapFactory; - -/** - * Managing internal components by using pico container.
- * There is an extension point through the registerComponents method, which - * allows one to give a customized container. - * - * @author Guilherme Silveira - */ -public class PicoProvider implements ContainerProvider { - - private final MutablePicoContainer picoContainer; - private MutablePicoContainer childContainer; - private final ThreadLocal containersByThread = new ThreadLocal(); - - private static final Logger logger = LoggerFactory.getLogger(PicoProvider.class); - private final Container container; - - private final class AppScopedContainer implements Container { - public T instanceFor(Class type) { - Container container = containersByThread.get(); - if (container == null) { - return picoContainer.getComponent(type); - } - return container.instanceFor(type); - } - - public boolean canProvide(Class type) { - return instanceFor(type) != null; - } - } - public PicoProvider() { - this.picoContainer = new DefaultPicoContainer(new Caching(), - new JavaEE5LifecycleStrategy(new NullComponentMonitor()), null); - - ComponentFactoryRegistry componentFactoryRegistry = new DefaultComponentFactoryRegistry(); - PicoComponentRegistry componentRegistry = new PicoComponentRegistry(this.picoContainer, componentFactoryRegistry); - - this.picoContainer.addComponent(componentRegistry); - this.picoContainer.addComponent(componentFactoryRegistry); - - container = new AppScopedContainer(); - picoContainer.addComponent(Container.class, container); - } - - public final void start(ServletContext context) { - ComponentRegistry componentRegistry = getComponentRegistry(); - registerBundledComponents(componentRegistry); - - this.picoContainer.addComponent(context); - BasicConfiguration config = new BasicConfiguration(context); - - // using the new vraptor.scan - WebAppBootstrap webAppBootstrap = new WebAppBootstrapFactory().create(config); - webAppBootstrap.configure(componentRegistry); - - // call old-style custom components registration - registerCustomComponents(componentRegistry); - - // start the container - getComponentRegistry().init(); - picoContainer.start(); - registerCacheComponents(); - - // call all handlers for registered components - Collection> components = getComponentRegistry().getAllRegisteredApplicationScopedComponents(); - List handlers = picoContainer.getComponents(StereotypeHandler.class); - - for (Class type : components) { - for (StereotypeHandler handler : handlers) { - if (type.isAnnotationPresent(handler.stereotype())) { - handler.handle(type); - } - } - } - } - - @Override - public Container getContainer() { - return container; - } - - /** - * Create a child container, and register cached components. This way, Cached components will use registered implementations - * for their types, and will be used on dependency injection - */ - private void registerCacheComponents() { - PicoComponentRegistry registry = getComponentRegistry(); - this.childContainer = registry.makeChildContainer(); - - Map, Class> cachedComponents = BaseComponents.getCachedComponents(); - for (Entry, Class> entry : cachedComponents.entrySet()) { - registry.register(entry.getKey(), entry.getValue()); - } - - this.childContainer.start(); - } - - /** - * Register default vraptor-pico implementation components. - */ - protected void registerBundledComponents(ComponentRegistry registry) { - logger.debug("Registering base pico container related implementation components"); - for (Class entry : BaseComponents.getStereotypeHandlers()) { - registry.register(entry, entry); - } - registerAll(registry, BaseComponents.getApplicationScoped()); - registerAll(registry, BaseComponents.getRequestScoped()); - registerAll(registry, BaseComponents.getPrototypeScoped()); - for (Class> converterType : BaseComponents.getBundledConverters()) { - registry.register(converterType, converterType); - } - } - - private void registerAll(ComponentRegistry registry, Map, Class> scope) { - for (Map.Entry, Class> entry : scope.entrySet()) { - registry.register(entry.getKey(), entry.getValue()); - registry.register(entry.getValue(), entry.getValue()); - } - } - - protected void registerCustomComponents(ComponentRegistry registry) { - /* TODO: For now, this is an empty hook method to enable subclasses to use - * the scanner and register their specific components. - * - * In the future, if we scan the classpath for StereotypeHandlers, we can - * eliminate this hook. - */ - } - - public void stop() { - picoContainer.stop(); - picoContainer.dispose(); - } - - public T provideForRequest(RequestInfo request, Execution execution) { - PicoBasedContainer container = null; - try { - container = getComponentRegistry().provideRequestContainer(request); - container.getContainer().start(); - - containersByThread.set(container); - return execution.insideRequest(container); - } finally { - if (container != null) { - MutablePicoContainer picoContainer = container.getContainer(); - picoContainer.stop(); - picoContainer.dispose(); - } - containersByThread.set(null); - } - } - - protected PicoComponentRegistry getComponentRegistry() { - return this.picoContainer.getComponent(PicoComponentRegistry.class); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentFactoryBean.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentFactoryBean.java deleted file mode 100644 index 7924729b8..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentFactoryBean.java +++ /dev/null @@ -1,54 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.spring; - -import org.springframework.beans.factory.FactoryBean; - -import br.com.caelum.vraptor.ioc.ComponentFactory; -import br.com.caelum.vraptor.ioc.ComponentFactoryIntrospector; -import br.com.caelum.vraptor.ioc.Container; - -/** - * @author: Fabio Kung - */ -@SuppressWarnings({ "rawtypes" }) -public class ComponentFactoryBean> implements FactoryBean { - - private Container container; - - private Class factoryType; - private Class targetType; - - public ComponentFactoryBean(Container container, Class factoryType) { - this.container = container; - this.factoryType = factoryType; - this.targetType = new ComponentFactoryIntrospector().targetTypeForComponentFactory(factoryType); - } - - public Object getObject() { - return container.instanceFor(factoryType).getInstance(); - } - - public Class getObjectType() { - return targetType; - } - - public boolean isSingleton() { - return false; - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentScanner.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentScanner.java deleted file mode 100644 index 568e7dd9d..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentScanner.java +++ /dev/null @@ -1,92 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import java.util.Arrays; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.annotation.AnnotationBeanNameGenerator; -import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; - -import br.com.caelum.vraptor.ioc.ComponentFactory; -import br.com.caelum.vraptor.ioc.Container; - -/** - * @author Fabio Kung - */ -class ComponentScanner extends ClassPathBeanDefinitionScanner { - - private static final Logger logger = LoggerFactory.getLogger(ComponentScanner.class); - - private final ConfigurableListableBeanFactory registry; - private final Container container; - - public ComponentScanner(ConfigurableListableBeanFactory registry, Container container) { - super((BeanDefinitionRegistry) registry, false); - this.registry = registry; - this.container = container; - addIncludeFilter(new ComponentTypeFilter()); - - setScopeMetadataResolver(new VRaptorScopeResolver()); - setBeanNameGenerator(new UniqueBeanNameGenerator(new AnnotationBeanNameGenerator())); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) { - super.postProcessBeanDefinition(beanDefinition, beanName); - beanDefinition.setPrimary(true); - beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); - try { - Class componentType = Class.forName(beanDefinition.getBeanClassName()); - if (ComponentFactory.class.isAssignableFrom(componentType) && checkCandidate(beanName, beanDefinition)) { - registry.registerSingleton(beanDefinition.getBeanClassName(), new ComponentFactoryBean(container, - componentType)); - } - } catch (ClassNotFoundException e) { - logger.warn("Class {} was not found during bean definition proccess", beanDefinition.getBeanClassName()); - } - catch (ExceptionInInitializerError e) { - // log and rethrow antipattern is needed, this is rally important - logger.warn("Class {}has problems during initialization", e.getCause()); - throw e; - } - } - - @Override - public int scan(String... basePackages) { - logger.debug("scanning {}", Arrays.toString(basePackages)); - return super.scan(basePackages); - } - - @Override - protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException { - if (registry.containsBeanDefinition(beanName) && registry.getBeanDefinition(beanName).getBeanClassName().equals(beanDefinition.getBeanClassName())) { - logger.warn("bean already found previously, there is probably no need to declare its package in web.xml: {}", - beanDefinition.getBeanClassName()); - return false; - } - return super.checkCandidate(beanName, beanDefinition); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentTypeFilter.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentTypeFilter.java deleted file mode 100644 index 81523ca1a..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/ComponentTypeFilter.java +++ /dev/null @@ -1,56 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.util.ArrayList; -import java.util.Collection; - -import org.springframework.core.type.AnnotationMetadata; -import org.springframework.core.type.classreading.MetadataReader; -import org.springframework.core.type.classreading.MetadataReaderFactory; -import org.springframework.core.type.filter.TypeFilter; - -import br.com.caelum.vraptor.core.BaseComponents; -import br.com.caelum.vraptor.ioc.Stereotype; - -/** - * @author Fabio Kung - */ -class ComponentTypeFilter implements TypeFilter { - - private final Collection> annotationTypes; - - public ComponentTypeFilter() { - this.annotationTypes = new ArrayList>(); - for (Class stereotype : BaseComponents.getStereotypes()) { - this.annotationTypes.add(stereotype); - } - } - - public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { - AnnotationMetadata metadata = metadataReader.getAnnotationMetadata(); - for (Class annotationType : annotationTypes) { - if (metadata.hasAnnotation(annotationType.getName())) { - return true; - } - } - return metadata.hasMetaAnnotation(Stereotype.class.getName()); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/DefaultSpringLocator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/DefaultSpringLocator.java deleted file mode 100644 index da1aa2d6e..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/DefaultSpringLocator.java +++ /dev/null @@ -1,62 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.spring; - -import javax.servlet.ServletContext; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.context.ConfigurableWebApplicationContext; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; -import org.springframework.web.context.support.XmlWebApplicationContext; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; - -/** - * Default implementation for SpringLocator. - * It tries to use spring default location to create the ApplicationContext - * @author Lucas Cavalcanti - * - */ -@ApplicationScoped -public class DefaultSpringLocator implements SpringLocator { - - private static final Logger logger = LoggerFactory.getLogger(DefaultSpringLocator.class); - - public ConfigurableWebApplicationContext getApplicationContext(ServletContext servletContext) { - ConfigurableWebApplicationContext context = (ConfigurableWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(servletContext); - if (context != null) { - logger.info("Using a web application context: {}", context); - return context; - } - if (DefaultSpringLocator.class.getResource("/applicationContext.xml") != null) { - logger.info("Using an XmlWebApplicationContext, searching for applicationContext.xml"); - XmlWebApplicationContext ctx = new XmlWebApplicationContext(); - ctx.setConfigLocation("classpath:applicationContext.xml"); - servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx); - return ctx; - } - logger.info("No application context found"); - ConfigurableWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); - ctx.setId("VRaptor"); - servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx); - return ctx; - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpServletRequestProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpServletRequestProvider.java deleted file mode 100644 index 271570236..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpServletRequestProvider.java +++ /dev/null @@ -1,48 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.beans.factory.FactoryBean; - -import br.com.caelum.vraptor.http.MutableRequest; -import br.com.caelum.vraptor.ioc.ApplicationScoped; - -/** - * Provides the current javax.servlet.http.HttpServletRequest object, provided that Spring has registered it for the - * current Thread. - * - * @author Fabio Kung - * @see org.springframework.web.context.request.RequestContextHolder - */ -@ApplicationScoped -class HttpServletRequestProvider implements FactoryBean { - - public HttpServletRequest getObject() throws Exception { - return VRaptorRequestHolder.currentRequest().getRequest(); - } - - public Class getObjectType() { - return MutableRequest.class; - } - - public boolean isSingleton() { - return false; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpServletResponseProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpServletResponseProvider.java deleted file mode 100644 index a98737f8a..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpServletResponseProvider.java +++ /dev/null @@ -1,48 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.FactoryBean; - -import br.com.caelum.vraptor.http.MutableResponse; -import br.com.caelum.vraptor.ioc.ApplicationScoped; - -/** - * Provides the current javax.servlet.http.HttpServletResponse object, provided that Spring has registered it for the - * current Thread. - * - * @author Fabio Kung - * @see org.springframework.web.context.request.ServletWebRequest - */ -@ApplicationScoped -class HttpServletResponseProvider implements FactoryBean { - - public HttpServletResponse getObject() throws Exception { - return VRaptorRequestHolder.currentRequest().getResponse(); - } - - public Class getObjectType() { - return MutableResponse.class; - } - - public boolean isSingleton() { - return false; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpSessionProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpSessionProvider.java deleted file mode 100644 index ecc0730b2..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/HttpSessionProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.FactoryBean; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; - -/** - * Provides the current javax.servlet.http.HttpSession object, provided that Spring has registered it for the - * current Thread. - * - * @author Fabio Kung - * @see org.springframework.web.context.request.RequestContextHolder - */ -@ApplicationScoped -class HttpSessionProvider implements FactoryBean { - - public HttpSession getObject() throws Exception { - return VRaptorRequestHolder.currentRequest().getRequest().getSession(); - } - - public Class getObjectType() { - return HttpSession.class; - } - - public boolean isSingleton() { - return false; - } -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/InjectionBeanPostProcessor.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/InjectionBeanPostProcessor.java deleted file mode 100644 index 76be75a95..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/InjectionBeanPostProcessor.java +++ /dev/null @@ -1,62 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import java.lang.reflect.Constructor; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor; - -/** - * Enhances the default behavior from Spring, adding support to injection - * through not annotated constructor, if there is only one. - * - * @author Fabio Kung - */ -class InjectionBeanPostProcessor extends AutowiredAnnotationBeanPostProcessor { - - - // in case we are required to change the injection annotation: - // public InjectionBeanPostProcessor() { - // this.setAutowiredAnnotationType(In.class); - // } - - @Override - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Constructor[] determineCandidateConstructors(Class beanClass, String beanName) throws BeansException { - Constructor[] candidates = super.determineCandidateConstructors(beanClass, beanName); - if (candidates == null) { - Constructor constructor = checkIfThereIsOnlyOneNonDefaultConstructor(beanClass); - if (constructor != null) { - candidates = new Constructor[]{constructor}; - } - } - return candidates; - } - - @SuppressWarnings({ "rawtypes" }) - private Constructor checkIfThereIsOnlyOneNonDefaultConstructor(Class beanClass) { - Constructor[] constructors = beanClass.getDeclaredConstructors(); - if (constructors.length == 1) { - if (constructors[0].getParameterTypes().length > 0) { - return constructors[0]; - } - } - return null; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/MissingConfigurationException.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/MissingConfigurationException.java deleted file mode 100644 index 4b803c420..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/MissingConfigurationException.java +++ /dev/null @@ -1,36 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.spring; - -/** - * @author Fabio Kung - */ -public class MissingConfigurationException extends IllegalStateException { - private static final long serialVersionUID = -3501632236065591624L; - - public MissingConfigurationException(String s) { - super(s); - } - - public MissingConfigurationException(String message, Throwable cause) { - super(message, cause); - } - - public MissingConfigurationException(Throwable cause) { - super(cause); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringBasedContainer.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringBasedContainer.java deleted file mode 100644 index b139cfa5c..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringBasedContainer.java +++ /dev/null @@ -1,129 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; - -import javax.servlet.ServletContext; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactoryUtils; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.web.context.ConfigurableWebApplicationContext; - -import br.com.caelum.vraptor.ioc.AbstractComponentRegistry; -import br.com.caelum.vraptor.ioc.Container; - -import com.google.common.collect.Sets; - -/** - * @author Fabio Kung - */ -public class SpringBasedContainer extends AbstractComponentRegistry implements Container { - - private static final class BeanRegistrationProcessor implements BeanFactoryPostProcessor { - private final SpringBasedContainer container; - - public BeanRegistrationProcessor(SpringBasedContainer container) { - this.container = container; - } - - public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException { - SpringRegistry registry = new SpringRegistry(factory, container); - - registry.configure(); - - registry.registerCustomComponents(container.toRegister); - } - - } - - private static final Logger logger = LoggerFactory.getLogger(SpringBasedContainer.class); - - final Set> toRegister = Sets.newHashSet(); - - private final ConfigurableWebApplicationContext parentContext; - - public SpringBasedContainer(ConfigurableWebApplicationContext parentContext) { - this.parentContext = parentContext; - } - - public void register(Class requiredType, Class componentType) { - if (parentContext.isActive() && "VRaptor".equals(parentContext.getId())) { - logger.info("registering class {} to {} after container initialization. Please avoid this", requiredType, componentType); - new SpringRegistry(parentContext.getBeanFactory(), this).register(componentType); - } else { - toRegister.add(componentType); - } - } - - public T instanceFor(Class type) { - try { - return parentContext.getBean(type); - } catch (NoSuchBeanDefinitionException e) { - Map beans = parentContext.getBeansOfType(type); - for (Entry def : beans.entrySet()) { - BeanDefinition definition = parentContext.getBeanFactory().getBeanDefinition(def.getKey()); - if (isPrimary(definition) || hasGreaterRoleThanInfrastructure(definition)) { - return def.getValue(); - } - } - throw e; - } - } - - public boolean canProvide(Class type) { - return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(parentContext, type).length > 0; - } - - public void start(ServletContext context) { - parentContext.setServletContext(context); - parentContext.addBeanFactoryPostProcessor(new BeanRegistrationProcessor(this)); - parentContext.refresh(); - - parentContext.start(); - } - - public void stop() { - parentContext.stop(); - if (parentContext instanceof DisposableBean){ - try { - ((DisposableBean)parentContext).destroy(); - } catch (Exception e) { - logger.error("Error when destroying application context", e); - } - } - } - - private boolean isPrimary(BeanDefinition definition) { - return definition instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) definition).isPrimary(); - } - - private boolean hasGreaterRoleThanInfrastructure(BeanDefinition definition) { - return definition.getRole() < BeanDefinition.ROLE_INFRASTRUCTURE; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringLocator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringLocator.java deleted file mode 100644 index 74cebb35e..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringLocator.java +++ /dev/null @@ -1,29 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.spring; - -import javax.servlet.ServletContext; - -import org.springframework.context.ApplicationContext; - -/** - * Component for locating a Spring ApplicationContext, to set as VRaptorApplicationContext parent - * @author Lucas Cavalcanti - */ -public interface SpringLocator { - ApplicationContext getApplicationContext(ServletContext context); -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringProvider.java deleted file mode 100644 index 0ba8c892f..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringProvider.java +++ /dev/null @@ -1,119 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.spring; - -import javax.servlet.ServletContext; -import javax.servlet.ServletRequestEvent; -import javax.servlet.http.HttpServletRequest; - -import org.springframework.web.context.ConfigurableWebApplicationContext; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.RequestContextListener; - -import br.com.caelum.vraptor.ComponentRegistry; -import br.com.caelum.vraptor.config.BasicConfiguration; -import br.com.caelum.vraptor.core.Execution; -import br.com.caelum.vraptor.core.RequestInfo; -import br.com.caelum.vraptor.ioc.ContainerProvider; -import br.com.caelum.vraptor.scan.WebAppBootstrap; -import br.com.caelum.vraptor.scan.WebAppBootstrapFactory; - -/** - * @author Fabio Kung - */ -public class SpringProvider implements ContainerProvider { - private final RequestContextListener requestListener = new RequestContextListener(); - private SpringBasedContainer container; - - /** - * Provides request scope support for Spring IoC Container when - * org.springframework.web.context.request.RequestContextListener has not - * been called. - */ - public T provideForRequest(RequestInfo request, Execution execution) { - if (springListenerAlreadyCalled()) { - return execution.insideRequest(getContainer()); - } - VRaptorRequestHolder.setRequestForCurrentThread(request); - T result; - try { - ServletContext context = request.getServletContext(); - HttpServletRequest webRequest = request.getRequest(); - requestListener.requestInitialized(new ServletRequestEvent(context, webRequest)); - try { - result = execution.insideRequest(getContainer()); - } finally { - requestListener.requestDestroyed(new ServletRequestEvent(context, webRequest)); - } - } finally { - VRaptorRequestHolder.resetRequestForCurrentThread(); - } - return result; - } - - public SpringBasedContainer getContainer() { - return container; - } - - public void stop() { - container.stop(); - } - - /** - * You can override this method to start some components, remember to call super before. - */ - public void start(ServletContext context) { - container = new SpringBasedContainer(getParentApplicationContext(context)); - - BasicConfiguration config = new BasicConfiguration(context); - WebAppBootstrap bootstrap = new WebAppBootstrapFactory().create(config); - bootstrap.configure(container); - - registerCustomComponents(container); - container.start(context); - } - - /** - * you can override this method for registering custom components, or use - * optional vraptor components, like hibernate session and session factory - * creators: - * - * registry.register(SessionCreator.class, SessionCreator.class); - * registry.register(SessionFactoryCreator.class, - * SessionFactoryCreator.class); - * - * @param registry - */ - protected void registerCustomComponents(ComponentRegistry registry) { - - } - - /** - * You can override this method for providing your own Spring - * ApplicationContext - * - * @return your spring application context - */ - protected ConfigurableWebApplicationContext getParentApplicationContext(ServletContext context) { - return new DefaultSpringLocator().getApplicationContext(context); - } - - private boolean springListenerAlreadyCalled() { - return RequestContextHolder.getRequestAttributes() != null; - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringRegistry.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringRegistry.java deleted file mode 100644 index 0a43c18ae..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/SpringRegistry.java +++ /dev/null @@ -1,191 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.ioc.spring; - -import java.util.Arrays; -import java.util.Collection; - -import org.springframework.aop.config.AopConfigUtils; -import org.springframework.aop.scope.ScopedProxyUtils; -import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.BeanDefinitionHolder; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.AbstractBeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanNameGenerator; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.context.annotation.AnnotationBeanNameGenerator; -import org.springframework.context.annotation.AnnotationConfigUtils; -import org.springframework.context.annotation.ScopeMetadata; -import org.springframework.context.annotation.ScopedProxyMode; -import org.springframework.core.Ordered; -import org.springframework.web.context.support.WebApplicationContextUtils; - -import br.com.caelum.vraptor.core.BaseComponents; -import br.com.caelum.vraptor.ioc.ComponentFactory; -import br.com.caelum.vraptor.ioc.Container; - -/** - * Class responsible for registering beans on spring. - * - * @author Lucas Cavalcanti - * @author Douglas Campos (qmx) - * @since 3.3.0 - */ -public class SpringRegistry { - - private final BeanNameGenerator beanNameGenerator = new UniqueBeanNameGenerator(new AnnotationBeanNameGenerator()); - private final ConfigurableListableBeanFactory beanFactory; - private final VRaptorScopeResolver scopeResolver = new VRaptorScopeResolver(); - private final Container container; - - public SpringRegistry(ConfigurableListableBeanFactory configurableListableBeanFactory, Container container) { - this.beanFactory = configurableListableBeanFactory; - this.container = container; - } - - private void registerOn(Class type, boolean customComponent) { - AnnotatedGenericBeanDefinition definition = new AnnotatedGenericBeanDefinition(type); - if (!customComponent) { - definition.setLazyInit(true); - } - definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_NO); - definition.setPrimary(customComponent); - definition.setRole(customComponent ? BeanDefinition.ROLE_APPLICATION : BeanDefinition.ROLE_INFRASTRUCTURE); - - String name = beanNameGenerator.generateBeanName(definition, (BeanDefinitionRegistry) beanFactory); - BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(definition, name); - - ScopeMetadata scopeMetadata = scopeResolver.resolveScopeMetadata(definition); - definitionHolder = applyScopeOn(definitionHolder, scopeMetadata); - - BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, (BeanDefinitionRegistry) beanFactory); - } - - /** - * From org.springframework.context.annotation.ClassPathBeanDefinitionScanner#applyScope() - * @param definition - * @param scopeMetadata - * - * @return - */ - private BeanDefinitionHolder applyScopeOn(BeanDefinitionHolder definition, ScopeMetadata scopeMetadata) { - String scope = scopeMetadata.getScopeName(); - ScopedProxyMode proxyMode = scopeMetadata.getScopedProxyMode(); - definition.getBeanDefinition().setScope(scope); - if (BeanDefinition.SCOPE_SINGLETON.equals(scope) || BeanDefinition.SCOPE_PROTOTYPE.equals(scope) - || proxyMode.equals(ScopedProxyMode.NO)) { - return definition; - } else { - boolean proxyTargetClass = proxyMode.equals(ScopedProxyMode.TARGET_CLASS); - return ScopedProxyUtils.createScopedProxy(definition, (BeanDefinitionRegistry) beanFactory, proxyTargetClass); - } - } - - private void registerOn(Class type) { - registerOn(type, false); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private void registerFactory(final Class type) { - if (ComponentFactory.class.isAssignableFrom(type)) { - beanFactory.registerSingleton(type.getName(), new ComponentFactoryBean(container, type)); - } - } - - void register(final Class type) { - register(type, true); - } - - private void register(final Class type, boolean customComponent) { - registerOn(type, customComponent); - registerFactory(type); - } - - private void registerPrototypeScopedComponentsOn() { - for (Class prototypeComponent : BaseComponents.getPrototypeScoped().values()) { - registerOn(prototypeComponent); - } - } - - private void registerCachedComponentsOn() { - for (Class cachedComponent : BaseComponents.getCachedComponents().values()) { - registerOn(cachedComponent, true); - } - } - - private void registerApplicationScopedComponentsOn() { - registerComponents(BaseComponents.getApplicationScoped().values()); - - registerComponents(Arrays.asList(BaseComponents.getStereotypeHandlers())); - - registerOn(StereotypedBeansRegistrar.class); - registerOn(DefaultSpringLocator.class); - } - - private void registerRequestScopedComponentsOn() { - registerComponents(BaseComponents.getRequestScoped().values()); - - registerComponents(BaseComponents.getBundledConverters()); - - registerOn(VRaptorRequestProvider.class, true); - registerOn(HttpServletRequestProvider.class, true); - registerOn(HttpServletResponseProvider.class, true); - registerOn(HttpSessionProvider.class, true); - - beanFactory.registerSingleton(SpringBasedContainer.class.getName(), container); - } - - private void registerVRaptorComponents() { - registerApplicationScopedComponentsOn(); - registerRequestScopedComponentsOn(); - registerPrototypeScopedComponentsOn(); - } - - private void registerCustomInjectionProcessor() { - RootBeanDefinition definition = new RootBeanDefinition(InjectionBeanPostProcessor.class); - definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - definition.getPropertyValues().addPropertyValue("order", Ordered.LOWEST_PRECEDENCE); - ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME, definition); - } - - void registerCustomComponents(Collection> toRegister) { - for (Class type : toRegister) { - register(type); - } - } - - private void registerComponents(Collection> toRegister) { - for (Class type : toRegister) { - register(type, false); - } - } - - void configure() { - registerVRaptorComponents(); - - AnnotationConfigUtils.registerAnnotationConfigProcessors((BeanDefinitionRegistry) beanFactory); - AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary((BeanDefinitionRegistry) beanFactory); - - registerCustomInjectionProcessor(); - - registerCachedComponentsOn(); - - WebApplicationContextUtils.registerWebApplicationScopes(beanFactory); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/StereotypedBeansRegistrar.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/StereotypedBeansRegistrar.java deleted file mode 100644 index 5e2dba825..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/StereotypedBeansRegistrar.java +++ /dev/null @@ -1,68 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.StereotypeHandler; - -/** - * @author Fabio Kung - */ -@ApplicationScoped -public class StereotypedBeansRegistrar implements ApplicationListener { - private static final Logger LOGGER = LoggerFactory.getLogger(StereotypedBeansRegistrar.class); - private final List stereotypeHandlers; - - public StereotypedBeansRegistrar(List stereotypeHandlers) { - this.stereotypeHandlers = stereotypeHandlers; - } - - public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof ContextRefreshedEvent) { - handleRefresh(((ContextRefreshedEvent) event).getApplicationContext()); - } - } - - private void handleRefresh(ApplicationContext beanFactory) { - String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames(); - for (String name : beanDefinitionNames) { - Class beanType = beanFactory.getType(name); - LOGGER.debug("scanning {} for bean definition {}", beanType, name); - if (beanType == null) { - LOGGER.info("null type for bean {}", name); - continue; - } - - for (StereotypeHandler handler : stereotypeHandlers) { - LOGGER.trace("scanning {} with {}", beanType, handler); - if (beanType.isAnnotationPresent(handler.stereotype())) { - handler.handle(beanType); - } - } - } - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/UniqueBeanNameGenerator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/UniqueBeanNameGenerator.java deleted file mode 100644 index 6a1d64f67..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/UniqueBeanNameGenerator.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * - */ -package br.com.caelum.vraptor.ioc.spring; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanNameGenerator; - -public class UniqueBeanNameGenerator implements BeanNameGenerator { - - private final BeanNameGenerator delegate; - - public UniqueBeanNameGenerator(BeanNameGenerator delegate) { - this.delegate = delegate; - } - - public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) { - String name = delegate.generateBeanName(definition, registry); - while (registry.containsBeanDefinition(name) && - !registry.getBeanDefinition(name).getBeanClassName().equals(definition.getBeanClassName())) { - name = name + "$"; - } - return name; - } -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorRequestHolder.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorRequestHolder.java deleted file mode 100644 index ea8a4c26d..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorRequestHolder.java +++ /dev/null @@ -1,38 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.spring; - -import br.com.caelum.vraptor.core.RequestInfo; - -/** - * @author Fabio Kung - */ -public class VRaptorRequestHolder { - private static final ThreadLocal vraptorRequests = new ThreadLocal(); - - public static RequestInfo currentRequest() { - return vraptorRequests.get(); - } - - public static void setRequestForCurrentThread(RequestInfo request) { - vraptorRequests.set(request); - } - - public static void resetRequestForCurrentThread() { - vraptorRequests.set(null); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorRequestProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorRequestProvider.java deleted file mode 100644 index a8b196a20..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorRequestProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import org.springframework.beans.factory.FactoryBean; - -import br.com.caelum.vraptor.core.RequestInfo; -import br.com.caelum.vraptor.ioc.ApplicationScoped; - -/** - * @author Fabio Kung - */ -@ApplicationScoped -class VRaptorRequestProvider implements FactoryBean { - - public RequestInfo getObject() throws Exception { - return VRaptorRequestHolder.currentRequest(); - } - - public Class getObjectType() { - return RequestInfo.class; - } - - public boolean isSingleton() { - return false; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorScopeResolver.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorScopeResolver.java deleted file mode 100644 index a67b40ffc..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/VRaptorScopeResolver.java +++ /dev/null @@ -1,64 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.ioc.spring; - -import java.util.LinkedHashMap; -import java.util.Map; - -import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.ScopeMetadata; -import org.springframework.context.annotation.ScopeMetadataResolver; -import org.springframework.core.type.AnnotationMetadata; -import org.springframework.web.context.WebApplicationContext; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.PrototypeScoped; -import br.com.caelum.vraptor.ioc.RequestScoped; -import br.com.caelum.vraptor.ioc.SessionScoped; - -/** - * @author Fabio Kung - */ -class VRaptorScopeResolver implements ScopeMetadataResolver { - private final Map scopes = new LinkedHashMap(); - - public VRaptorScopeResolver() { - scopes.put(RequestScoped.class.getName(), WebApplicationContext.SCOPE_REQUEST); - scopes.put(SessionScoped.class.getName(), WebApplicationContext.SCOPE_SESSION); - scopes.put(ApplicationScoped.class.getName(), BeanDefinition.SCOPE_SINGLETON); - scopes.put(PrototypeScoped.class.getName(), BeanDefinition.SCOPE_PROTOTYPE); - } - - public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) { - AnnotationMetadata metadata = ((AnnotatedBeanDefinition) definition).getMetadata(); - for (Map.Entry scope : scopes.entrySet()) { - if (metadata.hasAnnotation(scope.getKey())) { - ScopeMetadata scopeMetadata = new ScopeMetadata(); - scopeMetadata.setScopeName(scope.getValue()); - return scopeMetadata; - } - } - return requestScopeAsDefault(); - } - - private ScopeMetadata requestScopeAsDefault() { - ScopeMetadata singleton = new ScopeMetadata(); - singleton.setScopeName(WebApplicationContext.SCOPE_REQUEST); - return singleton; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/WebinfClassesPatternResolver.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/WebinfClassesPatternResolver.java deleted file mode 100644 index 7b49c0bd3..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/ioc/spring/WebinfClassesPatternResolver.java +++ /dev/null @@ -1,46 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package br.com.caelum.vraptor.ioc.spring; - -import java.io.IOException; - -import org.springframework.core.io.Resource; -import org.springframework.core.io.UrlResource; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; - -public class WebinfClassesPatternResolver extends - PathMatchingResourcePatternResolver { - - private final String webinfClassesDirectory; - - public WebinfClassesPatternResolver(String webinfClassesDirectory) { - if (webinfClassesDirectory == null) { - throw new NullPointerException( - "web inf class directory cant be null"); - } - this.webinfClassesDirectory = webinfClassesDirectory; - - } - - protected Resource[] findAllClassPathResources(String location) - throws IOException { - return new Resource[] { new UrlResource("file:/" - + webinfClassesDirectory) }; - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/BootstrapGenerator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/BootstrapGenerator.java deleted file mode 100644 index a5ed997e5..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/BootstrapGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.util.Collection; - -/** - * Generates a static WebAppBootstrap implementation with the scanned classes. - * - * @author Sérgio Lopes - * @since 3.2 - */ -public interface BootstrapGenerator { - - void generate(Collection components, ClasspathResolver resolver); - -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ClasspathResolver.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ClasspathResolver.java deleted file mode 100644 index 07aff8175..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ClasspathResolver.java +++ /dev/null @@ -1,47 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.net.URL; -import java.util.List; - -/** - * A helper to help locate WEB-INF/classes and all base packages to be scanned - * - * @author Sérgio Lopes - * @since 3.2 - */ -public interface ClasspathResolver { - - /** - * Where is WEB-INF/classes? - * - * @return WEB-INF/classes location - */ - URL findWebInfClassesLocation(); - - /** - * Find all base packages, including the ones using the new META-INF configuration - * @return an array of base packages - */ - List findBasePackages(); - - /** - * @return the class loader - */ - ClassLoader getClassLoader(); - -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ComponentScanner.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ComponentScanner.java deleted file mode 100644 index c7dfd25ea..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ComponentScanner.java +++ /dev/null @@ -1,37 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.util.Collection; - -/** - * - * @author Sergio Lopes - * @since 3.2 - * - */ -public interface ComponentScanner { - - /** - * Scan all classes in WEB-INF/classes and all classes from - * JARs from WEB-INF/lib belonging to specific packages. - * - * @param basePackages Base packages to register JARs. - * @return All class names found. - */ - Collection scan(ClasspathResolver resolver); - -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/DynamicWebAppBootstrap.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/DynamicWebAppBootstrap.java deleted file mode 100644 index 66afaaec3..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/DynamicWebAppBootstrap.java +++ /dev/null @@ -1,53 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.util.Collection; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ComponentRegistry; - -/** - * A dynamic impl of DynamicWebAppBootstrap for use in dev time. - * - * @author Sérgio Lopes - * @since 3.2 - */ -public class DynamicWebAppBootstrap implements WebAppBootstrap { - - private static final Logger logger = LoggerFactory.getLogger(DynamicWebAppBootstrap.class); - private final Collection classNames; - - public DynamicWebAppBootstrap(Collection classNames) { - this.classNames = classNames; - } - - public void configure(ComponentRegistry registry) { - for (String className : classNames) { - logger.trace("Registering class {}", className); - - try { - Class clazz = Class.forName(className); - registry.deepRegister(clazz); - } catch (ClassNotFoundException e) { - throw new ScannerException("Error while registering classes", e); - } - } - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/JavassistBootstrapGenerator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/JavassistBootstrapGenerator.java deleted file mode 100644 index 96202e8b3..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/JavassistBootstrapGenerator.java +++ /dev/null @@ -1,99 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.util.Collection; - -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtConstructor; -import javassist.CtMethod; -import javassist.CtNewMethod; -import javassist.bytecode.AnnotationsAttribute; -import javassist.bytecode.ClassFile; -import javassist.bytecode.ConstPool; -import javassist.bytecode.annotation.Annotation; - -import javax.annotation.Generated; - -/** - * A BoostrapGenerator based on Javassist. - * - * @author Sérgio Lopes - * @since 3.2 - */ -public class JavassistBootstrapGenerator implements BootstrapGenerator { - - public void generate(Collection components, ClasspathResolver resolver) { - // many initial variables - final String fullName = WebAppBootstrap.STATIC_BOOTSTRAP_NAME; - final String simpleName = fullName.substring(WebAppBootstrap.STATIC_BOOTSTRAP_NAME.lastIndexOf('.') + 1); - final String packageName = fullName.substring(0, fullName.lastIndexOf('.')); - final String webInfClasses = resolver.findWebInfClassesLocation().getPath(); - final String path = webInfClasses + "/" + packageName.replace('.', '/') + "/"; - final String filename = path + simpleName + ".class"; - - // create the entire package path - new File(path).mkdirs(); - - // construct the method implementation - StringBuilder methodDef = new StringBuilder() - .append("public void configure (br.com.caelum.vraptor.ComponentRegistry registry){"); - - for (String componentName : components) { - methodDef.append("registry.deepRegister(") - .append(componentName).append(".class") - .append(");"); - } - - methodDef.append("}"); - - // generate class file - try { - // new class - ClassPool pool = ClassPool.getDefault(); - CtClass clazz = pool.makeClass(fullName); - - // add a default constructor - CtConstructor constructor = new CtConstructor(null, clazz); - constructor.setBody("{super();}"); - clazz.addConstructor(constructor); - - // add the method implementation - CtMethod m = CtNewMethod.make(methodDef.toString(), clazz); - clazz.addMethod(m); - - // make this class implements WebAppBootstrap - ClassFile cf = clazz.getClassFile(); - cf.setVersionToJava5(); - cf.setInterfaces(new String[]{WebAppBootstrap.class.getName()}); - - // add @Generated - ConstPool cp = cf.getConstPool(); - AnnotationsAttribute attr = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag); - attr.setAnnotation(new Annotation(Generated.class.getName(), cp)); - cf.addAttribute(attr); - - // write the file - cf.write(new DataOutputStream(new FileOutputStream(filename))); - } catch (Exception e) { - throw new ScannerException("Error while generating the class file", e); - } - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/NullWebAppBootstrap.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/NullWebAppBootstrap.java deleted file mode 100644 index c752154c4..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/NullWebAppBootstrap.java +++ /dev/null @@ -1,16 +0,0 @@ -package br.com.caelum.vraptor.scan; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ComponentRegistry; - -public class NullWebAppBootstrap implements WebAppBootstrap { - - private static final Logger logger = LoggerFactory.getLogger(NullWebAppBootstrap.class); - - public void configure(ComponentRegistry registry) { - logger.info("Classpath scanning is disabled."); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ScannerException.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ScannerException.java deleted file mode 100644 index 2fa55ee94..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ScannerException.java +++ /dev/null @@ -1,34 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -/** - * Unchecked exception used in the scanner package - * - * @author Sérgio Lopes - * @since 3.2 - */ -public class ScannerException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public ScannerException(String message) { - super(message); - } - - public ScannerException(String message, Throwable t) { - super(message, t); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ScannotationComponentScanner.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ScannotationComponentScanner.java deleted file mode 100644 index eed000686..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/ScannotationComponentScanner.java +++ /dev/null @@ -1,193 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import static com.google.common.base.Objects.firstNonNull; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.net.URL; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.scannotation.AnnotationDB; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.core.BaseComponents; -import br.com.caelum.vraptor.ioc.Stereotype; - -/** - * A Scannotation based Component Scanner - * - * @author Sérgio Lopes - * @since 3.2 - */ -public class ScannotationComponentScanner implements ComponentScanner { - - private static final Logger logger = LoggerFactory.getLogger(ScannotationComponentScanner.class); - - public Collection scan(ClasspathResolver resolver) { - final URL webInfClasses = resolver.findWebInfClassesLocation(); - final List basePackages = resolver.findBasePackages(); - - HashSet results = new HashSet(); - - Map> webInfClassesAnnotationMap = scanWebInfClasses(webInfClasses); - Map> basePackagesAnnotationMap = scanBasePackages(basePackages, resolver); - - Set stereotypeNames = findStereotypes(webInfClassesAnnotationMap, basePackagesAnnotationMap, basePackages); - - findComponentsFromWebInfClasses(webInfClassesAnnotationMap, stereotypeNames, results); - findComponentsFromBasePackages(basePackagesAnnotationMap, basePackages, results); - - return results; - } - - private Map> scanWebInfClasses(URL webInfClasses) { - try { - AnnotationDB db = createAnnotationDB(); - db.scanArchives(webInfClasses); - return db.getAnnotationIndex(); - } catch (FileNotFoundException e) { - return Collections.emptyMap(); - } catch (IOException e) { - throw new ScannerException("Could not scan WEB-INF/classes", e); - } - } - - private Map> scanBasePackages(List basePackages, ClasspathResolver resolver) { - try { - AnnotationDB db = createAnnotationDB(); - - for (String basePackage : basePackages) { - scanPackage(basePackage, db, resolver); - } - - return db.getAnnotationIndex(); - } catch (IOException e) { - throw new ScannerException("Could not scan base packages", e); - } - } - - - - private void scanPackage(String basePackage, AnnotationDB db, ClasspathResolver resolver) throws IOException { - String resource = basePackage.replace('.', '/'); - Enumeration urls = resolver.getClassLoader().getResources(resource); - if (!urls.hasMoreElements()) { - logger.error("There's no occurence of package {} in classpath", basePackage); - return; - } - do { - URL url = urls.nextElement(); - - String file = toFileName(resource, url); - - db.scanArchives(new URL(file)); - } while (urls.hasMoreElements()); - } - - private String toFileName(String resource, URL url) { - String file = url.getFile().substring(0, url.getFile().length() - resource.length() - 1).replaceAll("(!)(/)?$", ""); - - if (!file.startsWith("file:")) { - file = "file:" + file; - } - return file; - } - - private Set findStereotypes(Map> webInfClassesAnnotationMap, Map> basePackagesAnnotationMap, List basePackages) { - HashSet results = new HashSet(); - - addVRaptorStereotypes(results); - - addWebInfClassesStereotypes(webInfClassesAnnotationMap, results); - - addBasePackagesStereotypes(basePackagesAnnotationMap, basePackages, results); - - return results; - } - - private void addBasePackagesStereotypes(Map> basePackagesAnnotationMap, - List basePackages, HashSet results) { - Set libStereotypes = nullToEmpty(basePackagesAnnotationMap.get(Stereotype.class.getName())); - for (String stereotype : libStereotypes) { - if (packagesContains(basePackages, stereotype)) { - results.add(stereotype); - } - } - } - - private boolean packagesContains(List basePackages, String clazz) { - for (String basePackage : basePackages) { - if (clazz.startsWith(basePackage)) { - return true; - } - } - return false; - } - - private void addWebInfClassesStereotypes(Map> webInfClassesAnnotationMap, - HashSet results) { - Set myStereotypes = nullToEmpty(webInfClassesAnnotationMap.get(Stereotype.class.getName())); - results.addAll(myStereotypes); - } - - private void addVRaptorStereotypes(HashSet results) { - for (Class stereotype : BaseComponents.getStereotypes()) { - results.add(stereotype.getName()); - } - } - - private void findComponentsFromWebInfClasses(Map> index, Set stereotypeNames, Set results) { - for (String stereotype : stereotypeNames) { - Set classes = nullToEmpty(index.get(stereotype)); - results.addAll(classes); - } - } - - private void findComponentsFromBasePackages(Map> index, List basePackages, Set results) { - for (Class stereotype : BaseComponents.getStereotypes()) { - Set classes = nullToEmpty(index.get(stereotype.getName())); - - for (String clazz : classes) { - if (packagesContains(basePackages, clazz)) { - results.add(clazz); - } - } - } - } - - private Set nullToEmpty(Set set) { - return firstNonNull(set, Collections.emptySet()); - } - - private AnnotationDB createAnnotationDB() { - AnnotationDB db = new AnnotationDB(); - db.setScanClassAnnotations(true); - db.setScanFieldAnnotations(false); - db.setScanMethodAnnotations(false); - db.setScanParameterAnnotations(false); - return db; - } -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/StandaloneClasspathResolver.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/StandaloneClasspathResolver.java deleted file mode 100644 index 18e1402a3..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/StandaloneClasspathResolver.java +++ /dev/null @@ -1,143 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.Scanner; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -/** - * A ClasspathResolver for static use, without a web context. - * - * @author Sérgio Lopes - * @since 3.2 - */ -public class StandaloneClasspathResolver implements ClasspathResolver { - - private static final Logger logger = LoggerFactory.getLogger(StandaloneClasspathResolver.class); - private final File webxml; - - public StandaloneClasspathResolver() { - // try to discover web.xml location related to vraptor.jar - String vraptor = "br/com/caelum/vraptor/VRaptor.class"; - URL vraptorJAR = getClassLoader().getResource(vraptor); - String filename = vraptorJAR.getPath(); - - int jarSeparationIndex = filename.lastIndexOf('!'); - filename = filename.substring(filename.indexOf(':') + 1, jarSeparationIndex == -1 ? filename.length() - 1: jarSeparationIndex); - filename = filename.substring(0, filename.lastIndexOf('/')); - - this.webxml = new File(filename.substring(0, filename.lastIndexOf('/')) + "/web.xml"); - } - - public StandaloneClasspathResolver(String webxml) { - this.webxml = new File(webxml); - } - - public ClassLoader getClassLoader() { - return Thread.currentThread().getContextClassLoader(); - } - - // find WEB-INF classes related to web.xml - public URL findWebInfClassesLocation() { - try { - File webInfClasses = new File(this.getWebxml().getParent() + "/classes"); - if (webInfClasses.exists()) { - return new URL("file:" + webInfClasses.getAbsolutePath() + "/"); - } - throw new ScannerException("Could not determine WEB-INF/classes location"); - } catch (MalformedURLException e) { - throw new ScannerException("Could not determine WEB-INF/classes location", e); - } - } - - public List findBasePackages() { - ArrayList packages = new ArrayList(); - getPackagesFromWebXml(packages); - getPackagesFromPluginsJARs(packages); - return packages; - } - - void getPackagesFromWebXml(List result) { - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.parse(this.getWebxml()); - - NodeList params = doc.getElementsByTagName("context-param"); - for (int i = 0; i < params.getLength(); i++) { - Element param = (Element) params.item(i); - NodeList paramName = param.getElementsByTagName("param-name"); - if ("br.com.caelum.vraptor.packages".equals(paramName.item(0).getTextContent())) { - NodeList paramValue = param.getElementsByTagName("param-value"); - String packages = paramValue.item(0).getTextContent(); - - Collections.addAll(result, packages.trim().split("\\s*,\\s*")); - return; - } - } - logger.debug("No found in web.xml"); - } catch (Exception e) { - throw new ScannerException("Problems while parsing web.xml", e); - } - } - - /** - * find plugin packages - * @param result - */ - void getPackagesFromPluginsJARs(List result) { - try { - ClassLoader classLoader = getClassLoader(); - Enumeration urls = classLoader.getResources("META-INF/br.com.caelum.vraptor.packages"); - - while (urls.hasMoreElements()) { - URL url = urls.nextElement(); - String packagesConfig = new Scanner(url.openStream()).useDelimiter("\\Z").next(); - if (packagesConfig != null) { - Collections.addAll(result, packagesConfig.trim().split("\\s*,\\s*")); - } else { - logger.warn("Plugin packages file was empty: {}", url.getPath()); - } - } - } catch (IOException e) { - logger.error("Exception while searching for packages file inside JARs", e); - } - } - - private File getWebxml() { - if (!this.webxml.exists()) { - throw new ScannerException("Could not locate web.xml. Please use the proper argument in command-line."); - } - return webxml; - } -} \ No newline at end of file diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/VRaptorStaticScanning.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/VRaptorStaticScanning.java deleted file mode 100644 index ae82c2b11..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/VRaptorStaticScanning.java +++ /dev/null @@ -1,56 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.util.Collection; - -/** - * A static Scanner that generates an static WebAppBootstrap - * - * @author Sérgio Lopes - * @since 3.2 - */ -public class VRaptorStaticScanning { - - /** - * @param args[0] (optional) The WEB-INF/web.xml location - */ - public static void main(String[] args) { - VRaptorStaticScanning app = new VRaptorStaticScanning(); - app.start(args.length == 1 ? args[0] : null); - } - - void start(String webxml) { - System.out.println("Starting VRaptor's static classpath scanning"); - - ClasspathResolver cpr; - if (webxml == null) { - cpr = new StandaloneClasspathResolver(); - } else { - cpr = new StandaloneClasspathResolver(webxml); - } - - System.out.print("Initiating the scanning..."); - ComponentScanner scanner = new ScannotationComponentScanner(); - Collection classes = scanner.scan(cpr); - System.out.println(" done."); - - System.out.print("Generating the static registry..."); - BootstrapGenerator generator = new JavassistBootstrapGenerator(); - generator.generate(classes, cpr); - System.out.println(" done."); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebAppBootstrap.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebAppBootstrap.java deleted file mode 100644 index a60b8610a..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebAppBootstrap.java +++ /dev/null @@ -1,38 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import br.com.caelum.vraptor.ComponentRegistry; - -/** - * Register all application components. - * - * @author Sérgio Lopes - * @since 3.2 - */ -public interface WebAppBootstrap { - - /** - * Configure all components using ComponentRegistry - * @param registry - */ - void configure (ComponentRegistry registry); - - /** - * Class name of the generated WebAppBootStrap impl - */ - String STATIC_BOOTSTRAP_NAME = "br.com.caelum.vraptor.generated.StaticProjectBootstrap"; -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebAppBootstrapFactory.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebAppBootstrapFactory.java deleted file mode 100644 index 5f4c755e5..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebAppBootstrapFactory.java +++ /dev/null @@ -1,86 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.util.Collection; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.config.BasicConfiguration; - -/** - * Creates the right WebAppBootstrap - * - * @author Sérgio Lopes - * @author Guilherme Silveira - * @since 3.2 - */ -public class WebAppBootstrapFactory { - - private static final Logger logger = LoggerFactory - .getLogger(WebAppBootstrapFactory.class); - - /** - * Returns the WebAppBootstrap for this web application - * - * @param servletContext - * @return - */ - public WebAppBootstrap create(BasicConfiguration config) { - WebAppBootstrap strap = tryStaticBootstrap(); - - if (strap != null) { - return strap; - } - - if (config.isClasspathScanningEnabled()) { - return scannerFor(config); - } - - return new NullWebAppBootstrap(); - } - - private WebAppBootstrap tryStaticBootstrap() { - try { - Class clazz = Class - .forName(WebAppBootstrap.STATIC_BOOTSTRAP_NAME); - - logger.info("Found a static WebAppBootstrap; using it and skipping classpath scanning."); - return (WebAppBootstrap) clazz.newInstance(); - } catch (ClassNotFoundException e) { - return null; - } catch (Exception e) { - throw new ScannerException( - "Error while creating the StaticWebAppBootstrap", e); - } - } - - private WebAppBootstrap scannerFor(BasicConfiguration config) { - logger.info("Dynamic WebAppBootstrap found."); - - // dinamically scan the classpath if there's no static cache generated - ClasspathResolver resolver = new WebBasedClasspathResolver( - config.getServletContext()); - - logger.trace("Start classpath scanning"); - ComponentScanner scanner = new ScannotationComponentScanner(); - Collection classNames = scanner.scan(resolver); - logger.trace("End classpath scanning"); - - return new DynamicWebAppBootstrap(classNames); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebBasedClasspathResolver.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebBasedClasspathResolver.java deleted file mode 100644 index 992c1af69..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/WebBasedClasspathResolver.java +++ /dev/null @@ -1,75 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.scan; - -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.servlet.ServletContext; - -import br.com.caelum.vraptor.config.BasicConfiguration; - -/** - * A classpath resolver based on ServletContext - * - * @author Sérgio Lopes - * @since 3.2 - */ -public class WebBasedClasspathResolver implements ClasspathResolver { - - private final ServletContext servletContext; - - public WebBasedClasspathResolver(ServletContext servletContext) { - this.servletContext = servletContext; - } - - public ClassLoader getClassLoader() { - if (servletContext.getMajorVersion() == 3) { - return servletContext.getClassLoader(); - } - return Thread.currentThread().getContextClassLoader(); - } - - public URL findWebInfClassesLocation() { - try { - String webInfClassesDir = servletContext.getRealPath("/WEB-INF/classes"); - if (webInfClassesDir != null) { - return new URL("file:" + webInfClassesDir + "/"); - } else { - // try to guess WEB-INF/classes from vraptor.jar location - return new StandaloneClasspathResolver().findWebInfClassesLocation(); - } - } catch (Exception e) { - throw new ScannerException("Could not determine WEB-INF/classes location", e); - } - } - - public List findBasePackages() { - ArrayList packages = new ArrayList(); - - // find packages from web.xml - String packagesParam = servletContext.getInitParameter(BasicConfiguration.BASE_PACKAGES_PARAMETER_NAME); - if (packagesParam != null) { - Collections.addAll(packages, packagesParam.trim().split("\\s*,\\s*")); - } - - // find plugin packages - new StandaloneClasspathResolver().getPackagesFromPluginsJARs(packages); - return packages; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/package-info.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/package-info.java deleted file mode 100644 index 30508bac7..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/scan/package-info.java +++ /dev/null @@ -1,36 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -/** - * Classpath scanning for VRaptor projects. It can scan everything dynamically when - * the context starts or can scan in build time and generate proper artifacts to prevent - * performance degradation in runtime. - * - * VRaptor will scan: - * - * - all components in WEB-INF/classes/ - * - all base packages from JARs in WEB-INF/classes - * - * There are two options to configure the base packages: - * - * - configure the br.com.caelum.vraptor.packages context-param in web.xml - * - create a META-INF/br.com.caelum.vraptor.packages file inside some JARs - * - * @author Sérgio Lopes - * @since 3.2 - */ -package br.com.caelum.vraptor.scan; - diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/DefaultExtJson.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/DefaultExtJson.java deleted file mode 100644 index 6b42b5dad..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/DefaultExtJson.java +++ /dev/null @@ -1,107 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - guilherme.silveira@caelum.com.br - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.extjs; - -import java.io.IOException; -import java.io.Writer; - -import javax.servlet.http.HttpServletResponse; - -import br.com.caelum.vraptor.interceptor.TypeNameExtractor; -import br.com.caelum.vraptor.ioc.Component; -import br.com.caelum.vraptor.serialization.ProxyInitializer; -import br.com.caelum.vraptor.serialization.xstream.XStreamSerializer; - -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; -import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; -import com.thoughtworks.xstream.io.json.JsonWriter; - -/** - * Implementation for {@link ExtJSJson}. - * @author Daniel Kist - * @author Lucas Cavalcanti - * - */ -@Component -public class DefaultExtJson implements ExtJSJson { - - private XStreamSerializer serializer; - private XStream xstream; - private ExtJSWrapper wrapper; - - public DefaultExtJson(HttpServletResponse response, TypeNameExtractor extractor, ProxyInitializer initializer) - throws IOException { - xstream = new XStream(new JsonHierarchicalStreamDriver() { - @Override - public HierarchicalStreamWriter createWriter(Writer writer) { - return new JsonWriter(writer, new char[0], "", JsonWriter.DROP_ROOT_MODE) { - @Override - public void addAttribute(String key, String value) { - if (!key.equals("class")) { - super.addAttribute(key, value); - } - } - }; - } - }); - xstream.setMode(XStream.NO_REFERENCES); - xstream.aliasField("data", ExtJSWrapper.class, "list"); - serializer = new XStreamSerializer(xstream, response.getWriter(), extractor, initializer); - } - - public ExtJSJson from(Object object) { - wrapper = new ExtJSWrapper(object); - serializer.from(object); - return this; - } - - public ExtJSJson exclude(String... names) { - serializer.exclude(names); - return this; - } - - public ExtJSJson include(String... fields) { - serializer.include(fields); - return this; - } - - public ExtJSJson selected(Object value) { - wrapper.setSelected(value); - return this; - } - - public ExtJSJson serialize() { - serializer.from(wrapper).recursive().serialize(); - return this; - } - - public ExtJSJson success() { - wrapper.setSuccess(true); - return this; - } - - public ExtJSJson success(boolean success) { - wrapper.setSuccess(success); - return this; - } - - public ExtJSJson total(Integer total) { - wrapper.setTotal(total); - return this; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/ExtJSJson.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/ExtJSJson.java deleted file mode 100644 index 41696546c..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/ExtJSJson.java +++ /dev/null @@ -1,44 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - guilherme.silveira@caelum.com.br - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.extjs; - -import br.com.caelum.vraptor.View; - -/** - * Interface for json serialization in ExtJS standard - * - * @author Daniel Kist - */ -public interface ExtJSJson extends View { - - public ExtJSJson from(Object object); - - public ExtJSJson success(); - - public ExtJSJson success(boolean success); - - public ExtJSJson selected(Object value); - - public ExtJSJson exclude(String... names); - - public ExtJSJson include(String... fields); - - public ExtJSJson serialize(); - - public ExtJSJson total(Integer total); - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/ExtJSWrapper.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/ExtJSWrapper.java deleted file mode 100644 index cfc6a1e44..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/extjs/ExtJSWrapper.java +++ /dev/null @@ -1,82 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.util.extjs; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * - * @author Daniel Kist - * @since 3.4.0 - */ -class ExtJSWrapper { - - private Object data; - private List list; - private Boolean success; - private Integer total; - private Object selected; - - public ExtJSWrapper(Object object) { - if (object instanceof Collection) { - this.list = new ArrayList((Collection) object); - } else { - this.data = object; - } - } - - public Object getData() { - return data; - } - - public void setData(Object data) { - this.data = data; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Boolean getSuccess() { - return success; - } - - public void setSuccess(Boolean success) { - this.success = success; - } - - public Integer getTotal() { - return total; - } - - public void setTotal(Integer total) { - this.total = total; - } - - public Object getSelected() { - return selected; - } - - public void setSelected(Object selected) { - this.selected = selected; - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/HibernateCustomProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/HibernateCustomProvider.java deleted file mode 100644 index 2b2d9dcbf..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/HibernateCustomProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.util.hibernate; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; - -import br.com.caelum.vraptor.ComponentRegistry; -import br.com.caelum.vraptor.ioc.spring.SpringProvider; - -/** - * A Custom provider that registers Hibernate optional components: - * - *
    - *
  • {@link SessionCreator} that creates hibernate {@link Session}
  • - *
  • {@link SessionFactoryCreator} that creates hibernate {@link SessionFactory} from - * default hibernate.cfg.xml on classpath
  • - *
  • {@link HibernateTransactionInterceptor} that opens a transaction at the beginning of - * the request, and commits (or rollbacks) that transaction at the end of the request.
  • - *
- * - * You can register this class as your provider on web.xml: - * - * - * br.com.caelum.vraptor.provider - * br.com.caelum.vraptor.util.hibernate.HibernateCustomProvider - * - * - * @author Lucas Cavalcanti - * - */ -public class HibernateCustomProvider extends SpringProvider { - - @Override - protected void registerCustomComponents(ComponentRegistry registry) { - registry.register(SessionCreator.class, SessionCreator.class); - registry.register(SessionFactoryCreator.class, SessionFactoryCreator.class); - registry.register(HibernateTransactionInterceptor.class, HibernateTransactionInterceptor.class); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/HibernateTransactionInterceptor.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/HibernateTransactionInterceptor.java deleted file mode 100644 index bb181d21a..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/HibernateTransactionInterceptor.java +++ /dev/null @@ -1,62 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.hibernate; - -import org.hibernate.Session; -import org.hibernate.Transaction; - -import br.com.caelum.vraptor.Intercepts; -import br.com.caelum.vraptor.Validator; -import br.com.caelum.vraptor.core.InterceptorStack; -import br.com.caelum.vraptor.interceptor.Interceptor; -import br.com.caelum.vraptor.resource.ResourceMethod; - -/** - * An example of Hibernate Transaction management on VRaptor - * @author Lucas Cavalcanti - * - */ -@Intercepts -public class HibernateTransactionInterceptor implements Interceptor { - - private final Session session; - private final Validator validator; - - public HibernateTransactionInterceptor(Session session, Validator validator) { - this.session = session; - this.validator = validator; - } - - public void intercept(InterceptorStack stack, ResourceMethod method, Object instance) { - Transaction transaction = null; - try { - transaction = session.beginTransaction(); - stack.next(method, instance); - if (!validator.hasErrors()) { - transaction.commit(); - } - } finally { - if (transaction != null && transaction.isActive()) { - transaction.rollback(); - } - } - } - - public boolean accepts(ResourceMethod method) { - return true; // Will intercept all requests - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/SessionCreator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/SessionCreator.java deleted file mode 100644 index 1819e32ae..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/SessionCreator.java +++ /dev/null @@ -1,59 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.hibernate; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.hibernate.Session; -import org.hibernate.SessionFactory; - -import br.com.caelum.vraptor.ioc.Component; -import br.com.caelum.vraptor.ioc.ComponentFactory; -import br.com.caelum.vraptor.ioc.RequestScoped; - -/** - * Opens and closes a Session from a SessionFactory and - * provides it to container - * @author Lucas Cavalcanti - */ -@Component -@RequestScoped -public class SessionCreator implements ComponentFactory { - - private final SessionFactory factory; - private Session session; - - public SessionCreator(SessionFactory factory) { - this.factory = factory; - } - - @PostConstruct - public void create() { - this.session = factory.openSession(); - } - - public Session getInstance() { - return session; - } - - @PreDestroy - public void destroy() { - this.session.close(); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/SessionFactoryCreator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/SessionFactoryCreator.java deleted file mode 100644 index 69b99e85f..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/SessionFactoryCreator.java +++ /dev/null @@ -1,55 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.hibernate; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.hibernate.SessionFactory; -import org.hibernate.cfg.AnnotationConfiguration; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.Component; -import br.com.caelum.vraptor.ioc.ComponentFactory; - -/** - * Creates a SessionFactory from default resource /hibernate.cfg.xml, using - * AnnotationConfiguration, and provides it to container - * @author Lucas Cavalcanti - * - */ -@Component -@ApplicationScoped -public class SessionFactoryCreator implements ComponentFactory { - - private SessionFactory factory; - - @PostConstruct - public void create() { - factory = new AnnotationConfiguration().configure().buildSessionFactory(); - } - - public SessionFactory getInstance() { - return factory; - } - - @PreDestroy - public void destroy() { - factory.close(); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/extra/Load.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/extra/Load.java deleted file mode 100644 index 9c4319b41..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/extra/Load.java +++ /dev/null @@ -1,32 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.util.hibernate.extra; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * To annotate parameters to be loaded before the controller is executed - * - * @author Lucas Cavalcanti - * @since 3.4.0 - */ -@Target(ElementType.PARAMETER) -@Retention(RetentionPolicy.RUNTIME) -public @interface Load { -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/extra/ParameterLoaderInterceptor.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/extra/ParameterLoaderInterceptor.java deleted file mode 100644 index d316e5223..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/hibernate/extra/ParameterLoaderInterceptor.java +++ /dev/null @@ -1,139 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.util.hibernate.extra; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Predicates.instanceOf; -import static com.google.common.collect.Iterables.any; -import static com.google.common.collect.Iterables.isEmpty; -import static java.util.Arrays.asList; - -import java.io.Serializable; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; - -import javax.servlet.http.HttpServletRequest; - -import net.vidageek.mirror.dsl.Mirror; - -import org.hibernate.Session; - -import br.com.caelum.vraptor.Converter; -import br.com.caelum.vraptor.InterceptionException; -import br.com.caelum.vraptor.Intercepts; -import br.com.caelum.vraptor.Lazy; -import br.com.caelum.vraptor.Result; -import br.com.caelum.vraptor.core.Converters; -import br.com.caelum.vraptor.core.InterceptorStack; -import br.com.caelum.vraptor.core.Localization; -import br.com.caelum.vraptor.http.ParameterNameProvider; -import br.com.caelum.vraptor.interceptor.Interceptor; -import br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor; -import br.com.caelum.vraptor.resource.ResourceMethod; -import br.com.caelum.vraptor.view.FlashScope; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; - -/** - * Interceptor that loads given entity from the database. - * - * @author Lucas Cavalcanti - * @author Cecilia Fernandes - * @since 3.4.0 - * - */ -@Intercepts(before=ParametersInstantiatorInterceptor.class) -@Lazy -public class ParameterLoaderInterceptor implements Interceptor { - - private final Session session; - private final HttpServletRequest request; - private final ParameterNameProvider provider; - private final Result result; - private final Converters converters; - private final Localization localization; - private final FlashScope flash; - - public ParameterLoaderInterceptor(Session session, HttpServletRequest request, ParameterNameProvider provider, - Result result, Converters converters, Localization localization, FlashScope flash) { - this.session = session; - this.request = request; - this.provider = provider; - this.result = result; - this.converters = converters; - this.localization = localization; - this.flash = flash; - } - - public boolean accepts(ResourceMethod method) { - return any(asList(method.getMethod().getParameterAnnotations()), hasLoadAnnotation()); - } - - public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) - throws InterceptionException { - Annotation[][] annotations = method.getMethod().getParameterAnnotations(); - - String[] names = provider.parameterNamesFor(method.getMethod()); - - Class[] types = method.getMethod().getParameterTypes(); - - Object[] args = flash.consumeParameters(method); - - for (int i = 0; i < names.length; i++) { - Iterable loads = Iterables.filter(asList(annotations[i]), Load.class); - if (!isEmpty(loads)) { - Object loaded = load(names[i], types[i]); - - if (loaded == null) { result.notFound(); return; } - - if (args != null) - args[i] = loaded; - else - request.setAttribute(names[i], loaded); - } - } - flash.includeParameters(method, args); - - stack.next(method, resourceInstance); - } - - private Object load(String name, Class type) { - String parameter = request.getParameter(name + ".id"); - if (parameter == null) { - return null; - } - Field field = new Mirror().on(type).reflect().field("id"); - checkArgument(field != null, "Entity " + type.getSimpleName() + " must have an id property for @Load."); - - Class idType = field.getType(); - Converter converter = converters.to(idType); - checkArgument(converter != null, "Entity " + type.getSimpleName() + " id type " + idType + " must have a converter"); - - Serializable id = (Serializable) converter.convert(parameter, type, localization.getBundle()); - return session.get(type, id); - } - - private Predicate hasLoadAnnotation() { - return new Predicate() { - public boolean apply(Annotation[] param) { - return any(asList(param), instanceOf(Load.class)); - } - }; - } - - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/interceptors/EncodingInterceptor.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/interceptors/EncodingInterceptor.java deleted file mode 100644 index c137acb36..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/interceptors/EncodingInterceptor.java +++ /dev/null @@ -1,55 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.interceptors; - -import java.io.UnsupportedEncodingException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import br.com.caelum.vraptor.InterceptionException; -import br.com.caelum.vraptor.core.InterceptorStack; -import br.com.caelum.vraptor.interceptor.Interceptor; -import br.com.caelum.vraptor.resource.ResourceMethod; - -public class EncodingInterceptor implements Interceptor { - - private static final String UTF_8 = "UTF-8"; - private final HttpServletRequest request; - private final HttpServletResponse response; - - public EncodingInterceptor(HttpServletRequest request, HttpServletResponse response) { - this.request = request; - this.response = response; - } - - public boolean accepts(ResourceMethod method) { - return true; - } - - public void intercept(InterceptorStack stack, ResourceMethod method, - Object resourceInstance) throws InterceptionException { - try { - request.setCharacterEncoding(UTF_8); - response.setCharacterEncoding(UTF_8); - } catch (UnsupportedEncodingException e) { - throw new InterceptionException(e); - } - stack.next(method, resourceInstance); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/EntityManagerCreator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/EntityManagerCreator.java deleted file mode 100644 index 041ed13ac..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/EntityManagerCreator.java +++ /dev/null @@ -1,58 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.jpa; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; - -import br.com.caelum.vraptor.ioc.Component; -import br.com.caelum.vraptor.ioc.ComponentFactory; -import br.com.caelum.vraptor.ioc.RequestScoped; - -/** - * An example of how to create EntityManager's for your components - * @author Lucas Cavalcanti - * - */ -@Component -@RequestScoped -public class EntityManagerCreator implements ComponentFactory{ - - private final EntityManagerFactory factory; - private EntityManager entityManager; - - public EntityManagerCreator(EntityManagerFactory factory) { - this.factory = factory; - } - - @PostConstruct - public void create() { - entityManager = factory.createEntityManager(); - } - - public EntityManager getInstance() { - return entityManager; - } - - @PreDestroy - public void destroy() { - entityManager.close(); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/EntityManagerFactoryCreator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/EntityManagerFactoryCreator.java deleted file mode 100644 index b2780df5a..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/EntityManagerFactoryCreator.java +++ /dev/null @@ -1,53 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.jpa; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.Component; -import br.com.caelum.vraptor.ioc.ComponentFactory; - -/** - * An example of how to create EntityManagerFactory's for your components - * @author Lucas Cavalcanti - * - */ -@Component -@ApplicationScoped -public class EntityManagerFactoryCreator implements ComponentFactory{ - - private EntityManagerFactory factory; - - @PostConstruct - public void create() { - factory = Persistence.createEntityManagerFactory("default"); - } - - public EntityManagerFactory getInstance() { - return factory; - } - - @PreDestroy - public void destroy() { - factory.close(); - } - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/JPACustomProvider.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/JPACustomProvider.java deleted file mode 100644 index 4fcfb95b1..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/JPACustomProvider.java +++ /dev/null @@ -1,53 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.util.jpa; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; - -import br.com.caelum.vraptor.ComponentRegistry; -import br.com.caelum.vraptor.ioc.spring.SpringProvider; - -/** - * A Custom provider that registers Hibernate optional components: - * - *
    - *
  • {@link EntityManagerCreator} that creates JPA {@link EntityManager}s
  • - *
  • {@link EntityManagerFactoryCreator} that creates JPA {@link EntityManagerFactory} from - * a persistence-unit named "default"
  • - *
  • {@link JPATransactionInterceptor} that opens a transaction at the beginning of - * the request, and commits (or rollbacks) that transaction at the end of the request.
  • - *
- * - * You can register this class as your provider on web.xml: - * - * - * br.com.caelum.vraptor.provider - * br.com.caelum.vraptor.util.jpa.JPACustomProvider - * - * - * @author Lucas Cavalcanti - * - */ -public class JPACustomProvider extends SpringProvider { - - @Override - protected void registerCustomComponents(ComponentRegistry registry) { - registry.register(EntityManagerCreator.class, EntityManagerCreator.class); - registry.register(EntityManagerFactoryCreator.class, EntityManagerFactoryCreator.class); - registry.register(JPATransactionInterceptor.class, JPATransactionInterceptor.class); - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/JPATransactionInterceptor.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/JPATransactionInterceptor.java deleted file mode 100644 index 9e8033e4e..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/JPATransactionInterceptor.java +++ /dev/null @@ -1,65 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - * All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package br.com.caelum.vraptor.util.jpa; - -import javax.persistence.EntityManager; -import javax.persistence.EntityTransaction; - -import br.com.caelum.vraptor.Intercepts; -import br.com.caelum.vraptor.Validator; -import br.com.caelum.vraptor.core.InterceptorStack; -import br.com.caelum.vraptor.interceptor.Interceptor; -import br.com.caelum.vraptor.ioc.Component; -import br.com.caelum.vraptor.resource.ResourceMethod; - -/** - * An example of JPA Transaction management on VRaptor - * @author Lucas Cavalcanti - * - */ -@Component -@Intercepts -public class JPATransactionInterceptor implements Interceptor { - - private final EntityManager manager; - private final Validator validator; - - public JPATransactionInterceptor(EntityManager manager, Validator validator) { - this.manager = manager; - this.validator = validator; - } - - public void intercept(InterceptorStack stack, ResourceMethod method, Object instance) { - EntityTransaction transaction = null; - try { - transaction = manager.getTransaction(); - transaction.begin(); - stack.next(method, instance); - if (!validator.hasErrors()) { - transaction.commit(); - } - } finally { - if (transaction != null && transaction.isActive()) { - transaction.rollback(); - } - } - } - - public boolean accepts(ResourceMethod method) { - return true; // Will intercept all requests - } -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/extra/Load.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/extra/Load.java deleted file mode 100644 index 0d82a234c..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/extra/Load.java +++ /dev/null @@ -1,32 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.util.jpa.extra; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * To annotate parameters to be loaded before the controller is executed - * - * @author Lucas Cavalcanti - * @since 3.4.0 - */ -@Target(ElementType.PARAMETER) -@Retention(RetentionPolicy.RUNTIME) -public @interface Load { -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/extra/ParameterLoaderInterceptor.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/extra/ParameterLoaderInterceptor.java deleted file mode 100644 index 639336de6..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/jpa/extra/ParameterLoaderInterceptor.java +++ /dev/null @@ -1,137 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.util.jpa.extra; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Predicates.instanceOf; -import static com.google.common.collect.Iterables.any; -import static com.google.common.collect.Iterables.isEmpty; -import static java.util.Arrays.asList; - -import java.io.Serializable; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; - -import javax.persistence.EntityManager; -import javax.servlet.http.HttpServletRequest; - -import net.vidageek.mirror.dsl.Mirror; -import br.com.caelum.vraptor.Converter; -import br.com.caelum.vraptor.InterceptionException; -import br.com.caelum.vraptor.Intercepts; -import br.com.caelum.vraptor.Lazy; -import br.com.caelum.vraptor.Result; -import br.com.caelum.vraptor.core.Converters; -import br.com.caelum.vraptor.core.InterceptorStack; -import br.com.caelum.vraptor.core.Localization; -import br.com.caelum.vraptor.http.ParameterNameProvider; -import br.com.caelum.vraptor.interceptor.Interceptor; -import br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor; -import br.com.caelum.vraptor.resource.ResourceMethod; -import br.com.caelum.vraptor.view.FlashScope; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; - -/** - * Interceptor that loads given entity from the database. - * - * @author Lucas Cavalcanti - * @author Cecilia Fernandes - * @since 3.3.2 - * - */ -@Intercepts(before=ParametersInstantiatorInterceptor.class) -@Lazy -public class ParameterLoaderInterceptor implements Interceptor { - - private final EntityManager em; - private final HttpServletRequest request; - private final ParameterNameProvider provider; - private final Result result; - private final Converters converters; - private final Localization localization; - private final FlashScope flash; - - public ParameterLoaderInterceptor(EntityManager em, HttpServletRequest request, ParameterNameProvider provider, - Result result, Converters converters, Localization localization, FlashScope flash) { - this.em = em; - this.request = request; - this.provider = provider; - this.result = result; - this.converters = converters; - this.localization = localization; - this.flash = flash; - } - - public boolean accepts(ResourceMethod method) { - return any(asList(method.getMethod().getParameterAnnotations()), hasLoadAnnotation()); - } - - public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) - throws InterceptionException { - Annotation[][] annotations = method.getMethod().getParameterAnnotations(); - - String[] names = provider.parameterNamesFor(method.getMethod()); - - Class[] types = method.getMethod().getParameterTypes(); - - Object[] args = flash.consumeParameters(method); - - for (int i = 0; i < names.length; i++) { - Iterable loads = Iterables.filter(asList(annotations[i]), Load.class); - if (!isEmpty(loads)) { - Object loaded = load(names[i], types[i]); - - if (loaded == null) { result.notFound(); return; } - - if (args != null) - args[i] = loaded; - else - request.setAttribute(names[i], loaded); - } - } - flash.includeParameters(method, args); - - stack.next(method, resourceInstance); - } - - private Object load(String name, Class type) { - String parameter = request.getParameter(name + ".id"); - if (parameter == null) { - return null; - } - Field field = new Mirror().on(type).reflect().field("id"); - checkArgument(field != null, "Entity " + type.getSimpleName() + " must have an id property for @Load."); - - Class idType = field.getType(); - Converter converter = converters.to(idType); - checkArgument(converter != null, "Entity " + type.getSimpleName() + " id type " + idType + " must have a converter"); - - Serializable id = (Serializable) converter.convert(parameter, type, localization.getBundle()); - return em.find(type, id); - } - - private Predicate hasLoadAnnotation() { - return new Predicate() { - public boolean apply(Annotation[] param) { - return any(asList(param), instanceOf(Load.class)); - } - }; - } - - -} diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/test/HibernateMockValidator.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/util/test/HibernateMockValidator.java deleted file mode 100644 index dff532509..000000000 --- a/vraptor-core/src/main/java/br/com/caelum/vraptor/util/test/HibernateMockValidator.java +++ /dev/null @@ -1,41 +0,0 @@ -/*** - * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ -package br.com.caelum.vraptor.util.test; - -import br.com.caelum.vraptor.validator.HibernateValidator3; - -/** - * Mocked Validator that uses Hibernate validator for validate method - * - * @author Wagner Ferreira and leandros - * @see MockValidator - * @deprecated Use {@link JSR303MockValidator} instead. - */ -@Deprecated -public class HibernateMockValidator extends MockValidator { - - private HibernateValidator3 hibernateValidator3; - - public HibernateMockValidator() { - hibernateValidator3 = new HibernateValidator3(new MockLocalization()); - } - - @Override - public void validate(Object bean) { - addAll(hibernateValidator3.validate(bean)); - } - -}