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.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

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.impl.FileWatcherReloadStrategy;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.spi.EventNotifier;
import org.apache.camel.spi.ModelJAXBContextFactory;
import org.apache.camel.spi.ReloadStrategy;
import org.apache.camel.support.ServiceSupport;
import org.apache.camel.util.ServiceHelper;
import org.apache.camel.util.concurrent.ThreadHelper;
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 static final int UNINITIALIZED_EXIT_CODE = Integer.MIN_VALUE;
    protected static final int DEFAULT_EXIT_CODE = 0;
    protected final List listeners = new ArrayList();
    protected final List

* Notice you cannot set this value and the fileWatchDirectory as well. */ public void setReloadStrategy(ReloadStrategy reloadStrategy) { this.reloadStrategy = reloadStrategy; } public boolean isTrace() { return trace; } public void enableTrace() { this.trace = true; } protected void doStop() throws Exception { // call completed to properly stop as we count down the waiting latch completed(); } protected void doStart() throws Exception { } protected void waitUntilCompleted() { while (!completed.get()) { try { if (duration > 0) { TimeUnit unit = getTimeUnit(); LOG.info("Waiting for: {} {}", duration, unit); latch.await(duration, unit); exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, durationHitExitCode); completed.set(true); } else if (durationIdle > 0) { TimeUnit unit = getTimeUnit(); LOG.info("Waiting to be idle for: {} {}", duration, unit); exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, durationHitExitCode); latch.await(); completed.set(true); } else if (durationMaxMessages > 0) { LOG.info("Waiting until: {} messages has been processed", durationMaxMessages); exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, durationHitExitCode); latch.await(); 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(); LOG.info("MainSupport exiting code: {}", getExitCode()); } /** * 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(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 { if (trace) { camelContext.setTracing(true); } if (fileWatchDirectory != null) { ReloadStrategy reload = new FileWatcherReloadStrategy(fileWatchDirectory, fileWatchDirectoryRecursively); camelContext.setReloadStrategy(reload); // ensure reload is added as service and started camelContext.addService(reload); // and ensure its register in JMX (which requires manually to be added because CamelContext is already started) Object managedObject = camelContext.getManagementStrategy().getManagementObjectStrategy().getManagedObjectForService(camelContext, reload); if (managedObject == null) { // service should not be managed return; } // skip already managed services, for example if a route has been restarted if (camelContext.getManagementStrategy().isManaged(managedObject, null)) { LOG.trace("The service is already managed: {}", reload); return; } try { camelContext.getManagementStrategy().manageObject(managedObject); } catch (Exception e) { LOG.warn("Could not register service: " + reload + " as Service MBean.", e); } } if (durationMaxMessages > 0 || durationIdle > 0) { // convert to seconds as that is what event notifier uses long seconds = timeUnit.toSeconds(durationIdle); // register lifecycle so we can trigger to shutdown the JVM when maximum number of messages has been processed EventNotifier notifier = new MainDurationEventNotifier(camelContext, durationMaxMessages, seconds, completed, latch, true); // register our event notifier ServiceHelper.startService(notifier); camelContext.getManagementStrategy().addEventNotifier(notifier); } // try to load the route builders from the routeBuilderClasses loadRouteBuilders(camelContext); for (RouteBuilder routeBuilder : routeBuilders) { camelContext.addRoutes(routeBuilder); } // register lifecycle so we are notified in Camel is stopped from JMX or somewhere else camelContext.addLifecycleStrategy(new MainLifecycleStrategy(completed, latch)); // 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