001    /*
002     * Copyright 2011 Christian Kumpe http://kumpe.de/christian/java
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     *     http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package de.kumpe.hadooptimizer.examples;
017    
018    import java.util.Arrays;
019    
020    import org.apache.commons.cli.MissingArgumentException;
021    
022    /**
023     * The main entry class for the generated jar file. It's specified in the
024     * corresponding MANIFEST.MF entry. If the jar is started it takes the first
025     * argument as a {@link Example} subclass instantiates it and invokes its
026     * {@link Example#run(String[])} method.
027     * 
028     * @author <a href="http://kumpe.de/christian/java">Christian Kumpe</a>
029     */
030    public class CliExamplesRunner {
031            public static void main(final String[] args) throws Exception {
032                    if (args.length < 1) {
033                            throw new MissingArgumentException(
034                                            "The example's main class was not specified.");
035                    }
036    
037                    final String exampleClassName = args[0];
038    
039                    final Class<?> exampleClass = findClass(exampleClassName,
040                                    CliExamplesRunner.class.getPackage().getName() + "."
041                                                    + exampleClassName);
042    
043                    final Example example = (Example) exampleClass.newInstance();
044    
045                    example.run(Arrays.copyOfRange(args, 1, args.length));
046            }
047    
048            private static Class<?> findClass(final String... classNames)
049                            throws ClassNotFoundException {
050                    ClassNotFoundException firstException = null;
051                    for (final String className : classNames) {
052                            try {
053                                    return Class.forName(className);
054                            } catch (final ClassNotFoundException e) {
055                                    if (null == firstException) {
056                                            firstException = e;
057                                    }
058                            }
059                    }
060                    throw firstException;
061            }
062    }