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.text.SimpleDateFormat;
020 import java.util.Collection;
021 import java.util.Date;
022 import java.util.HashMap;
023 import java.util.Map;
024 import java.util.Timer;
025
026 import org.apache.camel.Endpoint;
027 import org.apache.camel.Exchange;
028 import org.apache.camel.impl.DefaultComponent;
029
030 /**
031 * Represents the component that manages {@link TimerEndpoint}. It holds the
032 * list of {@link TimerConsumer} objects that are started.
033 *
034 * @version $Revision: 14007 $
035 */
036 public class TimerComponent extends DefaultComponent<Exchange> {
037 private Map<String, Timer> timers = new HashMap<String, Timer>();
038
039 public Timer getTimer(TimerEndpoint endpoint) {
040 String key = endpoint.getTimerName();
041 if (!endpoint.isDaemon()) {
042 key = "nonDaemon:" + key;
043 }
044
045 Timer answer = timers.get(key);
046 if (answer == null) {
047 answer = new Timer(endpoint.getTimerName(), endpoint.isDaemon());
048 timers.put(key, answer);
049 }
050 return answer;
051 }
052
053 @Override
054 protected Endpoint<Exchange> createEndpoint(String uri, String remaining, Map parameters) throws Exception {
055 TimerEndpoint answer = new TimerEndpoint(uri, this, remaining);
056
057 // convert time from String to a java.util.Date using the supported patterns
058 String time = getAndRemoveParameter(parameters, "time", String.class);
059 String pattern = getAndRemoveParameter(parameters, "pattern", String.class);
060 if (time != null) {
061 SimpleDateFormat sdf;
062 if (pattern != null) {
063 sdf = new SimpleDateFormat(pattern);
064 } else if (time.contains("T")) {
065 sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
066 } else {
067 sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
068 }
069 Date date = sdf.parse(time);
070 answer.setTime(date);
071 }
072
073 setProperties(answer, parameters);
074 return answer;
075 }
076
077 @Override
078 protected void doStop() throws Exception {
079 Collection<Timer> collection = timers.values();
080 for (Timer timer : collection) {
081 timer.cancel();
082 }
083 timers.clear();
084 }
085 }