001/* 002 * Copyright (c) 2006-2012 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.resource.spi.ConnectionManager; 024 025import org.apache.commons.beanutils.BeanUtils; 026import org.apache.commons.logging.Log; 027import org.apache.commons.logging.LogFactory; 028 029/** 030 * Factory for the ConnectionManager. 031 */ 032public class NuxeoConnectionManagerFactory implements ObjectFactory { 033 034 private static final Log log = LogFactory.getLog(NuxeoConnectionManagerFactory.class); 035 036 @Override 037 public Object getObjectInstance(Object obj, Name objName, Context nameCtx, Hashtable<?, ?> env) { 038 Reference ref = (Reference) obj; 039 if (!ConnectionManager.class.getName().equals(ref.getClassName())) { 040 return null; 041 } 042 String name; 043 int size = objName.size(); 044 if (size == 1) { 045 name = "default"; 046 } else { 047 name = objName.get(size - 1); 048 } 049 050 final ConnectionManager cm = NuxeoContainer.connectionManagers.get(name); 051 if (cm != null) { 052 return cm; 053 } 054 055 NuxeoConnectionManagerConfiguration config = new NuxeoConnectionManagerConfiguration(); 056 for (RefAddr addr : Collections.list(ref.getAll())) { 057 String type = addr.getType(); 058 String content = (String) addr.getContent(); 059 try { 060 BeanUtils.setProperty(config, type, content); 061 } catch (ReflectiveOperationException e) { 062 log.error(String.format("NuxeoConnectionManagerFactory cannot set %s = %s", type, content)); 063 } 064 } 065 return NuxeoContainer.initConnectionManager(config); 066 } 067 068 public static NuxeoConnectionManagerConfiguration getConfig(Reference ref) { 069 NuxeoConnectionManagerConfiguration config = new NuxeoConnectionManagerConfiguration(); 070 IllegalArgumentException errors = new IllegalArgumentException("wrong naming config"); 071 for (RefAddr addr : Collections.list(ref.getAll())) { 072 String name = addr.getType(); 073 String value = (String) addr.getContent(); 074 try { 075 BeanUtils.setProperty(config, name, value); 076 } catch (ReflectiveOperationException cause) { 077 errors.addSuppressed(cause); 078 } 079 } 080 if (errors.getSuppressed().length > 0) { 081 throw errors; 082 } 083 return config; 084 } 085}