001/*
002 * Copyright 2011 Atteo.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014package org.atteo.moonshine.jta;
015
016import javax.inject.Singleton;
017import javax.xml.bind.annotation.XmlElement;
018import javax.xml.bind.annotation.XmlIDREF;
019import javax.xml.bind.annotation.XmlRootElement;
020
021import org.atteo.evo.config.XmlDefaultValue;
022import org.atteo.moonshine.services.ImportService;
023import org.atteo.moonshine.TopLevelService;
024
025import com.google.inject.Module;
026import com.google.inject.matcher.Matchers;
027import com.google.inject.servlet.ServletModule;
028
029/**
030 * Adds support for {@link Transactional} annotation.
031 * <p>
032 * Provides support for &#064;{@link Transactional} annotation,
033 * {@link Transaction} helper and optionally registers web filter which wraps servlet request
034 * in separate transaction.
035 * </p>
036 */
037@XmlRootElement(name = "transactional")
038@Singleton
039public class TransactionalService extends TopLevelService {
040    @XmlIDREF
041    @ImportService
042    private JtaService jtaService;
043
044    /**
045     * Register {@link JtaFilter} which wraps web requests handling inside JTA transaction.
046     */
047    @XmlElement
048    private boolean registerWebFilter = false;
049
050    /**
051     * Filter pattern matching urls for which {@link JtaFilter} will be registered.
052     */
053    @XmlElement
054    @XmlDefaultValue("/*")
055    private String filterPattern;
056
057    @Override
058    public Module configure() {
059        return new ServletModule() {
060            @Override
061            protected void configureServlets() {
062                bind(JtaFilter.class);
063
064                requestStaticInjection(Transaction.class);
065                TransactionalInterceptor interceptor = new TransactionalInterceptor();
066                bindInterceptor(Matchers.any(), Matchers.annotatedWith(Transactional.class), interceptor);
067                bindInterceptor(Matchers.annotatedWith(Transactional.class), Matchers.any(), interceptor);
068
069                if (registerWebFilter) {
070                    filter(filterPattern).through(JtaFilter.class);
071                }
072            }
073        };
074    }
075}