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     */
017    package org.apache.camel.component.timer;
018    
019    import java.util.Collection;
020    import java.util.HashMap;
021    import java.util.Map;
022    import java.util.Timer;
023    
024    import org.apache.camel.Endpoint;
025    import org.apache.camel.Exchange;
026    import org.apache.camel.impl.DefaultComponent;
027    
028    /**
029     * Represents the component that manages {@link TimerEndpoint}.  It holds the
030     * list of {@link TimerConsumer} objects that are started.
031     *
032     * @version $Revision: 382 $
033     */
034    public class TimerComponent extends DefaultComponent<Exchange> {
035        private Map<String, Timer> timers = new HashMap<String, Timer>();
036    
037        public Timer getTimer(TimerEndpoint endpoint) {
038            String key = endpoint.getTimerName();
039            if (!endpoint.isDaemon()) {
040                key = "nonDaemon:" + key;
041            }
042    
043            Timer answer = timers.get(key);
044            if (answer == null) {
045                answer = new Timer(endpoint.getTimerName(), endpoint.isDaemon());
046                timers.put(key, answer);
047            }
048            return answer;
049        }
050    
051        @Override
052        protected Endpoint<Exchange> createEndpoint(String uri, String remaining, Map parameters) throws Exception {
053            TimerEndpoint answer = new TimerEndpoint(uri, this, remaining);
054            setProperties(answer, parameters);
055            return answer;
056        }
057    
058        @Override
059        protected void doStop() throws Exception {
060            Collection<Timer> collection = timers.values();
061            for (Timer timer : collection) {
062                timer.cancel();
063            }
064            timers.clear();
065        }
066    }