001/*
002 * (C) Copyright 2006-2012 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 *     tmartins
018 *
019 */
020package org.nuxeo.ecm.directory.ldap;
021
022import java.lang.reflect.InvocationHandler;
023import java.lang.reflect.InvocationTargetException;
024import java.lang.reflect.Method;
025import java.lang.reflect.Proxy;
026
027import javax.naming.ServiceUnavailableException;
028import javax.naming.directory.DirContext;
029
030import org.apache.commons.logging.Log;
031import org.apache.commons.logging.LogFactory;
032
033/**
034 * Wrapper to encapsulate the calls to LDAP and retry the requests in case of ServiceUnavailableException errors
035 *
036 * @since 5.7
037 * @author Thierry Martins
038 */
039public class LdapRetryHandler implements InvocationHandler {
040
041    private static final Log log = LogFactory.getLog(LdapRetryHandler.class);
042
043    protected DirContext dirContext;
044
045    protected int attemptsNumber;
046
047    protected LdapRetryHandler(DirContext object, int attempts) {
048        dirContext = object;
049        attemptsNumber = attempts;
050    }
051
052    @Override
053    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
054        int attempts = attemptsNumber;
055        Throwable e = null;
056        while (attempts-- > 0) {
057            try {
058                return method.invoke(dirContext, args);
059            } catch (InvocationTargetException sue) {
060                e = sue.getTargetException();
061                if (!(e instanceof ServiceUnavailableException)) {
062                    throw sue.getTargetException();
063                } else {
064                    log.debug("Retrying ...", e);
065                }
066            }
067        }
068        throw e; // NOSONAR
069    }
070
071    public static DirContext wrap(DirContext dirContext, int retries) {
072        LdapRetryHandler handler = new LdapRetryHandler(dirContext, retries);
073        return (DirContext) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
074                new Class<?>[] { DirContext.class }, handler);
075    }
076}