001/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*- 002 * 003 * Copyright © 2018 microBean. 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 014 * implied. See the License for the specific language governing 015 * permissions and limitations under the License. 016 */ 017package org.microbean.narayana.jta.cdi; 018 019import javax.enterprise.context.ApplicationScoped; 020 021import javax.enterprise.event.Observes; 022 023import javax.enterprise.inject.CreationException; 024import javax.enterprise.inject.Produces; 025 026import javax.enterprise.inject.spi.AfterBeanDiscovery; 027import javax.enterprise.inject.spi.CDI; 028import javax.enterprise.inject.spi.Extension; 029 030import javax.transaction.SystemException; 031import javax.transaction.Transaction; 032import javax.transaction.TransactionManager; 033import javax.transaction.TransactionScoped; 034import javax.transaction.TransactionSynchronizationRegistry; 035 036import com.arjuna.ats.jta.common.jtaPropertyManager; 037 038/** 039 * A <a 040 * href="http://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#spi">CDI 2.0 041 * portable extension</a> that adapts the <a 042 * href="https://narayana.io/">Narayana transaction engine</a> to a <a 043 * href="http://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#part_2">CDI 044 * 2.0 SE environment</a>. 045 * 046 * @author <a href="https://about.me/lairdnelson" 047 * target="_parent">Laird Nelson</a> 048 */ 049public final class NarayanaExtension implements Extension { 050 051 052 /* 053 * Constructors. 054 */ 055 056 057 /** 058 * Creates a new {@link NarayanaExtension}. 059 */ 060 public NarayanaExtension() { 061 super(); 062 } 063 064 065 /* 066 * Instance methods. 067 */ 068 069 070 /** 071 * Adds a synthetic bean that creates a {@link Transaction} in 072 * {@linkplain TransactionScoped transaction scope}. 073 * 074 * @param event the {@link AfterBeanDiscovery} event fired by the 075 * CDI container; may be {@code null} in which case no action will 076 * be taken 077 */ 078 private final void afterBeanDiscovery(@Observes final AfterBeanDiscovery event) { 079 if (event != null) { 080 081 event.addBean() 082 .types(Transaction.class) 083 .scope(TransactionScoped.class) 084 .createWith(cc -> { 085 try { 086 return CDI.current().select(TransactionManager.class).get().getTransaction(); 087 } catch (final SystemException systemException) { 088 throw new CreationException(systemException.getMessage(), systemException); 089 } 090 }); 091 092 } 093 } 094 095}