001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Florent Guillaume
011 */
012
013package org.nuxeo.runtime.jtajca;
014
015import java.util.Collections;
016import java.util.Hashtable;
017
018import javax.naming.Context;
019import javax.naming.Name;
020import javax.naming.RefAddr;
021import javax.naming.Reference;
022import javax.naming.spi.ObjectFactory;
023import javax.transaction.TransactionManager;
024
025import org.apache.commons.beanutils.BeanUtils;
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.nuxeo.runtime.jtajca.NuxeoContainer.TransactionManagerConfiguration;
029
030/**
031 * Factory for the TransactionManager.
032 */
033public class NuxeoTransactionManagerFactory implements ObjectFactory {
034
035    private static final Log log = LogFactory.getLog(NuxeoTransactionManagerFactory.class);
036
037    @Override
038    public Object getObjectInstance(Object obj, Name objName, Context nameCtx, Hashtable<?, ?> env) {
039        Reference ref = (Reference) obj;
040        if (!TransactionManager.class.getName().equals(ref.getClassName())) {
041            return null;
042        }
043        if (NuxeoContainer.tm != null) {
044            return NuxeoContainer.tm;
045        }
046
047        // initialize
048        TransactionManagerConfiguration config = new TransactionManagerConfiguration();
049        for (RefAddr addr : Collections.list(ref.getAll())) {
050            String name = addr.getType();
051            String value = (String) addr.getContent();
052            try {
053                BeanUtils.setProperty(config, name, value);
054            } catch (ReflectiveOperationException e) {
055                log.error(String.format("NuxeoTransactionManagerFactory cannot set %s = %s", name, value));
056            }
057        }
058        return NuxeoContainer.initTransactionManager(config);
059    }
060
061}