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.spring.util;
018
019import java.lang.reflect.InvocationTargetException;
020import java.lang.reflect.Method;
021import java.lang.reflect.Modifier;
022import java.util.Arrays;
023
024import org.slf4j.Logger;
025import org.slf4j.LoggerFactory;
026import org.springframework.beans.factory.InitializingBean;
027
028import static org.apache.camel.util.ObjectHelper.name;
029
030/**
031 * A simple helper bean for running main classes from within the spring.xml usually asynchronous in a background thread;
032 * which is useful for demos such as running Swing programs in the same JVM.
033 */
034public class MainRunner implements InitializingBean, Runnable {
035    private static final Logger LOG = LoggerFactory.getLogger(MainRunner.class);
036
037    private Class<?> main;
038    private String[] args = {};
039    private boolean asyncRun = true;
040    private long delay;
041
042    @Override
043    public String toString() {
044        return "MainRunner(" + name(main) + " " + Arrays.asList(getArgs()) + ")";
045    }
046
047    @Override
048    public void run() {
049        try {
050            runMethodWithoutCatchingExceptions();
051        } catch (NoSuchMethodException e) {
052            LOG.error("Class: {} does not have a main method: {}", name(main), e.getMessage(), e);
053        } catch (IllegalAccessException e) {
054            LOG.error("Failed to run: {}. Reason: {}", this, e.getMessage(), e);
055        } catch (InvocationTargetException e) {
056            Throwable throwable = e.getTargetException();
057            LOG.error("Failed to run: {}. Reason: {}", this, throwable.getMessage(), throwable);
058        }
059    }
060
061    public void runMethodWithoutCatchingExceptions()
062            throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
063        if (delay > 0) {
064            try {
065                Thread.sleep(delay);
066            } catch (InterruptedException e) {
067                Thread.currentThread().interrupt();
068            }
069        }
070        Method method = main.getMethod("main", String[].class);
071        if (!Modifier.isStatic(method.getModifiers())) {
072            throw new IllegalArgumentException("The main method is not static!: " + method);
073        }
074        Object[] arguments = { getArgs() };
075        method.invoke(null, arguments);
076    }
077
078    public String[] getArgs() {
079        return args;
080    }
081
082    public void setArgs(String[] args) {
083        this.args = args;
084    }
085
086    public boolean isAsyncRun() {
087        return asyncRun;
088    }
089
090    public void setAsyncRun(boolean asyncRun) {
091        this.asyncRun = asyncRun;
092    }
093
094    public Class<?> getMain() {
095        return main;
096    }
097
098    public void setMain(Class<?> main) {
099        this.main = main;
100    }
101
102    public long getDelay() {
103        return delay;
104    }
105
106    public void setDelay(long delay) {
107        this.delay = delay;
108    }
109
110    @Override
111    public void afterPropertiesSet() throws Exception {
112        if (main == null) {
113            throw new IllegalArgumentException("You must specify a main class!");
114        }
115        if (isAsyncRun()) {
116            Thread thread = new Thread(this, "Thread for: " + this);
117            thread.start();
118        } else {
119            runMethodWithoutCatchingExceptions();
120        }
121    }
122}