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.component.bean;
018
019import org.apache.camel.AsyncCallback;
020import org.apache.camel.Exchange;
021import org.apache.camel.NoSuchBeanException;
022import org.apache.camel.impl.DefaultAsyncProducer;
023import org.apache.camel.util.ServiceHelper;
024
025/**
026 * Bean {@link org.apache.camel.Producer}
027 */
028public class BeanProducer extends DefaultAsyncProducer {
029
030    private final BeanProcessor processor;
031    private boolean beanStarted;
032
033    public BeanProducer(BeanEndpoint endpoint, BeanProcessor processor) {
034        super(endpoint);
035        this.processor = processor;
036        this.beanStarted = false;
037    }
038
039    @Override
040    public boolean process(Exchange exchange, AsyncCallback callback) {
041        return processor.process(exchange, callback);
042    }
043
044    @Override
045    protected void doStart() throws Exception {
046        super.doStart();
047
048        if (processor.getBeanHolder() instanceof ConstantBeanHolder) {
049            try {
050                // Start the bean if it implements Service interface and if cached
051                // so meant to be reused
052                ServiceHelper.startService(processor.getBean());
053                beanStarted = true;
054            } catch (NoSuchBeanException e) {
055            }
056        }
057    }
058
059    @Override
060    protected void doStop() throws Exception {
061        if (beanStarted) {
062            try {
063                // Stop the bean if it implements Service interface and if cached
064                // so meant to be reused
065                ServiceHelper.stopService(processor.getBean());
066                beanStarted = false;
067            } catch (NoSuchBeanException e) {
068            }
069        }
070
071        super.doStop();
072    }
073}