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.spi; 018 019import java.io.Closeable; 020import java.util.List; 021import java.util.concurrent.CopyOnWriteArrayList; 022import java.util.function.Predicate; 023 024import org.apache.camel.CamelContext; 025import org.slf4j.Logger; 026import org.slf4j.LoggerFactory; 027 028/** 029 * A {@link CamelContext} creation tracker. 030 */ 031public class CamelContextTracker implements Closeable { 032 033 private static final Logger LOG = LoggerFactory.getLogger(CamelContextTracker.class); 034 035 private static final List<CamelContextTracker> TRACKERS = new CopyOnWriteArrayList<>(); 036 037 @FunctionalInterface 038 public interface Filter extends Predicate<CamelContext> { 039 040 boolean accept(CamelContext camelContext); 041 042 @Override 043 default boolean test(CamelContext camelContext) { 044 return accept(camelContext); 045 } 046 } 047 048 private final Filter filter; 049 050 public CamelContextTracker() { 051 filter = new Filter() { 052 public boolean accept(CamelContext camelContext) { 053 return !camelContext.getClass().getName().contains("Proxy"); 054 } 055 }; 056 } 057 058 public CamelContextTracker(Filter filter) { 059 this.filter = filter; 060 } 061 062 /** 063 * Called to determine whether this tracker should accept the given context. 064 */ 065 public boolean accept(CamelContext camelContext) { 066 return filter == null || filter.accept(camelContext); 067 } 068 069 /** 070 * Called when a context is created. 071 */ 072 public void contextCreated(CamelContext camelContext) { 073 // do nothing 074 } 075 076 public final void open() { 077 TRACKERS.add(this); 078 } 079 080 public final void close() { 081 TRACKERS.remove(this); 082 } 083 084 public static synchronized void notifyContextCreated(CamelContext camelContext) { 085 for (CamelContextTracker tracker : TRACKERS) { 086 try { 087 if (tracker.accept(camelContext)) { 088 tracker.contextCreated(camelContext); 089 } 090 } catch (Exception e) { 091 LOG.warn("Error calling CamelContext tracker. This exception is ignored.", e); 092 } 093 } 094 } 095}