001/* 002 * (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bstefanescu 018 */ 019package org.nuxeo.ecm.automation.client; 020 021import java.lang.reflect.ParameterizedType; 022import java.lang.reflect.Type; 023import java.util.HashSet; 024import java.util.Set; 025 026/** 027 * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> 028 */ 029public class AdapterManager { 030 031 protected final Set<AdapterFactory<?>> factories = new HashSet<AdapterFactory<?>>(); 032 033 // put(BusinessObjectService.class, 034 public <T> T getAdapter(Session session, Class<T> adapterType) { 035 for (AdapterFactory<?> f : factories) { 036 if (!factoryAccept(f, adapterType)) { 037 continue; 038 } 039 @SuppressWarnings("unchecked") 040 AdapterFactory<T> tFactory = (AdapterFactory<T>) f; 041 return adapterType.cast(tFactory.getAdapter(session, adapterType)); 042 } 043 return null; 044 } 045 046 protected boolean factoryAccept(AdapterFactory<?> factory, Class<?> adapterType) { 047 ParameterizedType itf = (ParameterizedType) factory.getClass().getGenericInterfaces()[0]; 048 Type type = itf.getActualTypeArguments()[0]; 049 Class<?> clazz; 050 if (type instanceof Class) { 051 clazz = (Class<?>) type; 052 } else if (type instanceof ParameterizedType) { 053 clazz = (Class<?>) ((ParameterizedType) type).getRawType(); 054 } else { 055 throw new UnsupportedOperationException("Don't know how to handle " + type.getClass()); 056 } 057 return clazz.isAssignableFrom(adapterType); 058 } 059 060 public void registerAdapter(AdapterFactory<?> factory) { 061 factories.add(factory); 062 } 063 064 public void clear() { 065 factories.clear(); 066 } 067 068}