All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.camel.main.MainSupport Maven / Gradle / Ivy

There is a newer version: 4.6.0
Show newest version
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.camel.main;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultModelJAXBContextFactory;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.spi.ModelJAXBContextFactory;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.ServiceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Base class for main implementations to allow starting up a JVM with Camel embedded.
 *
 * @version 
 */
public abstract class MainSupport extends ServiceSupport {
    protected static final Logger LOG = LoggerFactory.getLogger(MainSupport.class);
    protected final List listeners = new ArrayList();
    protected final List

* It is recommended to use {@link org.apache.camel.main.MainListener} instead. */ protected void afterStop() throws Exception { for (MainListener listener : listeners) { listener.afterStop(this); } } private void internalBeforeStop() { try { if (camelTemplate != null) { ServiceHelper.stopService(camelTemplate); camelTemplate = null; } } catch (Exception e) { LOG.debug("Error stopping camelTemplate due " + e.getMessage() + ". This exception is ignored.", e); } } /** * Marks this process as being completed. */ public void completed() { completed.set(true); latch.countDown(); } /** * Displays the command line options. */ public void showOptions() { showOptionsHeader(); for (Option option : options) { System.out.println(option.getInformation()); } } /** * Parses the command line arguments. */ public void parseArguments(String[] arguments) { LinkedList args = new LinkedList(Arrays.asList(arguments)); boolean valid = true; while (!args.isEmpty()) { String arg = args.removeFirst(); boolean handled = false; for (Option option : options) { if (option.processOption(arg, args)) { handled = true; break; } } if (!handled) { System.out.println("Unknown option: " + arg); System.out.println(); valid = false; break; } } if (!valid) { showOptions(); completed(); } } public void addOption(Option option) { options.add(option); } public long getDuration() { return duration; } /** * Sets the duration to run the application for in milliseconds until it * should be terminated. Defaults to -1. Any value <= 0 will run forever. */ public void setDuration(long duration) { this.duration = duration; } public TimeUnit getTimeUnit() { return timeUnit; } /** * Sets the time unit duration. */ public void setTimeUnit(TimeUnit timeUnit) { this.timeUnit = timeUnit; } public void setRouteBuilderClasses(String builders) { this.routeBuilderClasses = builders; } public String getRouteBuilderClasses() { return routeBuilderClasses; } public boolean isTrace() { return trace; } public void enableTrace() { this.trace = true; for (CamelContext context : camelContexts) { context.setTracing(true); } } protected void doStop() throws Exception { if (!isStopped()) { LOG.info("Apache Camel " + getVersion() + " stopping"); } // call completed to properly stop as we count down the waiting latch completed(); } protected void doStart() throws Exception { if (!isStarted()) { // only log if we are not already started as camel-spring-boot etc. has a different start ordering LOG.info("Apache Camel " + getVersion() + " starting"); } } protected void waitUntilCompleted() { while (!completed.get()) { try { if (duration > 0) { TimeUnit unit = getTimeUnit(); LOG.info("Waiting for: " + duration + " " + unit); latch.await(duration, unit); completed.set(true); } else { latch.await(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } /** * Parses the command line arguments then runs the program. */ public void run(String[] args) throws Exception { parseArguments(args); run(); } /** * Displays the header message for the command line options. */ public void showOptionsHeader() { System.out.println("Apache Camel Runner takes the following options"); System.out.println(); } public List getCamelContexts() { return camelContexts; } public List getRouteBuilders() { return routeBuilders; } public void setRouteBuilders(List routeBuilders) { this.routeBuilders = routeBuilders; } public List getRouteDefinitions() { List answer = new ArrayList(); for (CamelContext camelContext : camelContexts) { answer.addAll(((ModelCamelContext)camelContext).getRouteDefinitions()); } return answer; } public ProducerTemplate getCamelTemplate() throws Exception { if (camelTemplate == null) { camelTemplate = findOrCreateCamelTemplate(); } return camelTemplate; } protected abstract ProducerTemplate findOrCreateCamelTemplate(); protected abstract Map getCamelContextMap(); protected void postProcessContext() throws Exception { Map map = getCamelContextMap(); Set> entries = map.entrySet(); for (Map.Entry entry : entries) { CamelContext camelContext = entry.getValue(); camelContexts.add(camelContext); postProcessCamelContext(camelContext); } } public ModelJAXBContextFactory getModelJAXBContextFactory() { return new DefaultModelJAXBContextFactory(); } protected void loadRouteBuilders(CamelContext camelContext) throws Exception { if (routeBuilderClasses != null) { // get the list of route builder classes String[] routeClasses = routeBuilderClasses.split(","); for (String routeClass : routeClasses) { Class routeClazz = camelContext.getClassResolver().resolveClass(routeClass); RouteBuilder builder = (RouteBuilder) routeClazz.newInstance(); getRouteBuilders().add(builder); } } } protected void postProcessCamelContext(CamelContext camelContext) throws Exception { // try to load the route builders from the routeBuilderClasses loadRouteBuilders(camelContext); for (RouteBuilder routeBuilder : routeBuilders) { camelContext.addRoutes(routeBuilder); } // allow to do configuration before its started for (MainListener listener : listeners) { listener.configure(camelContext); } } public void addRouteBuilder(RouteBuilder routeBuilder) { getRouteBuilders().add(routeBuilder); } public abstract class Option { private String abbreviation; private String fullName; private String description; protected Option(String abbreviation, String fullName, String description) { this.abbreviation = "-" + abbreviation; this.fullName = "-" + fullName; this.description = description; } public boolean processOption(String arg, LinkedList remainingArgs) { if (arg.equalsIgnoreCase(abbreviation) || fullName.startsWith(arg)) { doProcess(arg, remainingArgs); return true; } return false; } public String getAbbreviation() { return abbreviation; } public String getDescription() { return description; } public String getFullName() { return fullName; } public String getInformation() { return " " + getAbbreviation() + " or " + getFullName() + " = " + getDescription(); } protected abstract void doProcess(String arg, LinkedList remainingArgs); } public abstract class ParameterOption extends Option { private String parameterName; protected ParameterOption(String abbreviation, String fullName, String description, String parameterName) { super(abbreviation, fullName, description); this.parameterName = parameterName; } protected void doProcess(String arg, LinkedList remainingArgs) { if (remainingArgs.isEmpty()) { System.err.println("Expected fileName for "); showOptions(); completed(); } else { String parameter = remainingArgs.removeFirst(); doProcess(arg, parameter, remainingArgs); } } public String getInformation() { return " " + getAbbreviation() + " or " + getFullName() + " <" + parameterName + "> = " + getDescription(); } protected abstract void doProcess(String arg, String parameter, LinkedList remainingArgs); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy