001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.ecm.automation.client;
018
019import java.lang.reflect.ParameterizedType;
020import java.lang.reflect.Type;
021import java.util.HashSet;
022import java.util.Set;
023
024/**
025 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
026 */
027public class AdapterManager {
028
029    protected final Set<AdapterFactory<?>> factories = new HashSet<AdapterFactory<?>>();
030
031    // put(BusinessObjectService.class,
032    public <T> T getAdapter(Session session, Class<T> adapterType) {
033        for (AdapterFactory<?> f : factories) {
034            if (!factoryAccept(f, adapterType)) {
035                continue;
036            }
037            @SuppressWarnings("unchecked")
038            AdapterFactory<T> tFactory = (AdapterFactory<T>) f;
039            return adapterType.cast(tFactory.getAdapter(session, adapterType));
040        }
041        return null;
042    }
043
044    protected boolean factoryAccept(AdapterFactory<?> factory, Class<?> adapterType) {
045        ParameterizedType itf = (ParameterizedType) factory.getClass().getGenericInterfaces()[0];
046        Type type = itf.getActualTypeArguments()[0];
047        Class<?> clazz;
048        if (type instanceof Class) {
049            clazz = (Class<?>) type;
050        } else if (type instanceof ParameterizedType) {
051            clazz = (Class<?>) ((ParameterizedType) type).getRawType();
052        } else {
053            throw new UnsupportedOperationException("Don't know how to handle " + type.getClass());
054        }
055        return clazz.isAssignableFrom(adapterType);
056    }
057
058    public void registerAdapter(AdapterFactory<?> factory) {
059        factories.add(factory);
060    }
061
062    public void clear() {
063        factories.clear();
064    }
065
066}