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.activemq.camel; 018 019import org.apache.activemq.broker.BrokerService; 020import org.apache.camel.CamelContext; 021import org.apache.camel.CamelContextAware; 022import org.slf4j.Logger; 023import org.slf4j.LoggerFactory; 024import org.springframework.beans.factory.annotation.Autowired; 025 026/** 027 * A shutdown hook that can be used to shutdown {@link CamelContext} before the 028 * ActiveMQ broker is shut down. This is sometimes important as if the broker is 029 * shutdown before Camel there could be a loss of data due to inflight exchanges 030 * not yet completed. 031 * <p> 032 * This hook can be added to ActiveMQ configuration ({@code activemq.xml}) as in 033 * the following example: 034 * <p> 035 * <code> 036 * <bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.camel.CamelShutdownHook" /> 037 * </code> 038 */ 039public final class CamelShutdownHook implements Runnable, CamelContextAware { 040 041 private static final Logger LOG = LoggerFactory.getLogger(CamelShutdownHook.class); 042 043 private CamelContext camelContext; 044 045 @Autowired 046 public CamelShutdownHook(final BrokerService brokerService) { 047 brokerService.addPreShutdownHook(this); 048 } 049 050 @Override 051 public CamelContext getCamelContext() { 052 return camelContext; 053 } 054 055 @Override 056 public void run() { 057 if (camelContext != null) { 058 try { 059 camelContext.stop(); 060 } catch (final Exception e) { 061 LOG.warn("Unable to stop CamelContext", e); 062 } 063 } else { 064 LOG.warn("Unable to stop CamelContext, no CamelContext was set!"); 065 } 066 } 067 068 @Override 069 public void setCamelContext(final CamelContext camelContext) { 070 this.camelContext = camelContext; 071 } 072 073}