|
| 1 | +/* |
| 2 | + * Copyright 2018 M. Isuru Tharanga Chrishantha Perera |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package com.github.chrishantha.sample.base; |
| 17 | + |
| 18 | +import com.beust.jcommander.JCommander; |
| 19 | +import com.beust.jcommander.Parameter; |
| 20 | +import com.beust.jcommander.ParameterException; |
| 21 | + |
| 22 | +import java.util.Iterator; |
| 23 | +import java.util.ServiceLoader; |
| 24 | + |
| 25 | +public class App { |
| 26 | + |
| 27 | + private static class CommonArgs { |
| 28 | + @Parameter(names = "--help", description = "Display Help", help = true) |
| 29 | + private boolean help; |
| 30 | + } |
| 31 | + |
| 32 | + public static void main(String[] args) { |
| 33 | + // There should be only one application |
| 34 | + Iterator<SampleApplication> applicationIterator = ServiceLoader.load(SampleApplication.class).iterator(); |
| 35 | + if (!applicationIterator.hasNext()) { |
| 36 | + throw new IllegalStateException("Could not load Sample Application"); |
| 37 | + } |
| 38 | + SampleApplication sampleApplication = applicationIterator.next(); |
| 39 | + CommonArgs commonArgs = new CommonArgs(); |
| 40 | + final JCommander jcmdr = JCommander.newBuilder() |
| 41 | + .programName(sampleApplication.getClass().getSimpleName()) |
| 42 | + .addObject(sampleApplication) |
| 43 | + .addObject(commonArgs) |
| 44 | + .build(); |
| 45 | + |
| 46 | + try { |
| 47 | + jcmdr.parse(args); |
| 48 | + } catch (ParameterException ex) { |
| 49 | + System.err.println(ex.getMessage()); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + if (commonArgs.help) { |
| 54 | + jcmdr.usage(); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + System.out.println(sampleApplication); |
| 59 | + sampleApplication.start(); |
| 60 | + } |
| 61 | +} |
0 commit comments