001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.processor.loadbalancer;
018
019import java.util.HashMap;
020import java.util.Iterator;
021import java.util.List;
022import java.util.Map;
023import java.util.concurrent.atomic.AtomicLong;
024
025/**
026 * Statistics about exception failures for load balancers that reacts on exceptions
027 */
028public class ExceptionFailureStatistics {
029
030    private final Map<Class<?>, AtomicLong> counters = new HashMap<Class<?>, AtomicLong>();
031    private final AtomicLong fallbackCounter = new AtomicLong();
032
033    public void init(List<Class<?>> exceptions) {
034        if (exceptions != null) {
035            for (Class<?> exception : exceptions) {
036                counters.put(exception, new AtomicLong());
037            }
038        }
039    }
040
041    public Iterator<Class<?>> getExceptions() {
042        return counters.keySet().iterator();
043    }
044
045    public long getFailureCounter(Class<?> exception) {
046        AtomicLong counter = counters.get(exception);
047        if (counter != null) {
048            return counter.get();
049        } else {
050            return fallbackCounter.get();
051        }
052    }
053
054    public void onHandledFailure(Exception exception) {
055        Class<?> clazz = exception.getClass();
056
057        AtomicLong counter = counters.get(clazz);
058        if (counter != null) {
059            counter.incrementAndGet();
060        } else {
061            fallbackCounter.incrementAndGet();
062        }
063    }
064
065    public void reset() {
066        for (AtomicLong counter : counters.values()) {
067            counter.set(0);
068        }
069        fallbackCounter.set(0);
070    }
071}
072