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 *     bstefanescu
011 */
012package org.nuxeo.ecm.webengine.jaxrs.login;
013
014import java.util.ArrayList;
015import java.util.Map;
016
017/**
018 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
019 */
020public class AuthenticationService {
021
022    protected Map<String, AuthenticationHandler> handlers;
023
024    public void addHander(AuthenticationHandlerDescriptor desc) throws ReflectiveOperationException {
025        handlers.put(desc.name, desc.newInstance());
026    }
027
028    public void removeHander(AuthenticationHandlerDescriptor desc) {
029        handlers.remove(desc.name);
030    }
031
032    public void addHandler(String name, AuthenticationHandler handler) {
033        handlers.put(name, handler);
034    }
035
036    public AuthenticationHandler removeHandler(String key) {
037        return handlers.remove(key);
038    }
039
040    public AuthenticationHandler getHandler(String name) {
041        return handlers.get(name);
042    }
043
044    /**
045     * Create a handler instance for the given comma separated list of handler names.
046     *
047     * @param names
048     * @return
049     */
050    public AuthenticationHandler createHandler(String names) {
051        int i = names.indexOf(',');
052        if (i == -1) {
053            AuthenticationHandler handler = handlers.get(names.trim());
054            return handler;
055        }
056        int s = 0;
057        ArrayList<AuthenticationHandler> result = new ArrayList<AuthenticationHandler>();
058        do {
059            String name = names.substring(s, i).trim();
060            AuthenticationHandler handler = getHandler(name);
061            result.add(handler);
062            s = i + 1;
063            i = names.indexOf(',', s);
064        } while (i > -1);
065        if (s < names.length()) {
066            String name = names.substring(s).trim();
067            if (name.length() > 0) {
068                AuthenticationHandler handler = getHandler(name);
069                result.add(handler);
070            }
071        }
072        return new CompositeAuthenticationHandler(result.toArray(new AuthenticationHandler[result.size()]));
073    }
074
075}