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.impl; 018 019import java.util.Set; 020import java.util.concurrent.CopyOnWriteArraySet; 021 022import org.apache.camel.CamelContext; 023import org.apache.camel.Endpoint; 024import org.apache.camel.Ordered; 025import org.apache.camel.ResolveEndpointFailedException; 026import org.apache.camel.Service; 027import org.apache.camel.StartupListener; 028import org.apache.camel.util.ServiceHelper; 029 030/** 031 * A {@link org.apache.camel.StartupListener} that defers starting {@link Service}s, until as late as possible during 032 * the startup process of {@link CamelContext}. 033 */ 034public class DeferServiceStartupListener implements StartupListener, Ordered { 035 036 private final Set<Service> services = new CopyOnWriteArraySet<Service>(); 037 038 public void addService(Service service) { 039 services.add(service); 040 } 041 042 @Override 043 public void onCamelContextStarted(CamelContext context, boolean alreadyStarted) throws Exception { 044 // new services may be added while starting a service 045 // so use a while loop to get the newly added services as well 046 while (!services.isEmpty()) { 047 Service service = services.iterator().next(); 048 try { 049 ServiceHelper.startService(service); 050 } catch (Exception e) { 051 if (service instanceof Endpoint) { 052 Endpoint endpoint = (Endpoint) service; 053 throw new ResolveEndpointFailedException(endpoint.getEndpointUri(), e); 054 } else { 055 throw e; 056 } 057 } finally { 058 services.remove(service); 059 } 060 } 061 } 062 063 public int getOrder() { 064 // we want to be last, so the other startup listeners run first 065 return Ordered.LOWEST; 066 } 067}