Example usage for org.apache.commons.cli BasicParser BasicParser

List of usage examples for org.apache.commons.cli BasicParser BasicParser

Introduction

In this page you can find the example usage for org.apache.commons.cli BasicParser BasicParser.

Prototype

BasicParser

Source Link

Usage

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());//from  w  w w . j  a  v a2  s .  c  o  m
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:com.example.geomesa.authorizations.GeoServerAuthorizationsTutorial.java

/**
 * Main entry point. Executes queries against an existing GDELT dataset.
 *
 * @param args/*w w w  .  j  av  a 2s . com*/
 *
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // read command line options - this contains the path to geoserver and the data store to query
    CommandLineParser parser = new BasicParser();
    Options options = SetupUtil.getWfsOptions();
    CommandLine cmd = parser.parse(options, args);

    String geoserverHost = cmd.getOptionValue(SetupUtil.GEOSERVER_URL);
    if (!geoserverHost.endsWith("/")) {
        geoserverHost += "/";
    }

    // create the URL to GeoServer. Note that we need to point to the 'GetCapabilities' request,
    // and that we are using WFS version 1.0.0
    String geoserverUrl = geoserverHost + "wfs?request=GetCapabilities&version=1.0.0";

    // create the geotools configuration for a WFS data store
    Map<String, String> configuration = new HashMap<String, String>();
    configuration.put(WFSDataStoreFactory.URL.key, geoserverUrl);
    configuration.put(WFSDataStoreFactory.WFS_STRATEGY.key, "geoserver");
    configuration.put(WFSDataStoreFactory.TIMEOUT.key, cmd.getOptionValue(SetupUtil.TIMEOUT, "99999"));

    System.out.println("Executing query against '" + geoserverHost + "' with client keystore '"
            + System.getProperty("javax.net.ssl.keyStore") + "'");

    // verify we have gotten the correct datastore
    WFSDataStore wfsDataStore = (WFSDataStore) DataStoreFinder.getDataStore(configuration);
    assert wfsDataStore != null;

    // the geoserver data store to query
    String geoserverDataStore = cmd.getOptionValue(SetupUtil.FEATURE_STORE);

    executeQuery(geoserverDataStore, wfsDataStore);
}

From source file:kieker.tools.bridge.cli.CLIServerMain.java

/**
 * CLI server main./* w  w w  .j  av  a 2 s. com*/
 *
 * @param args
 *            command line arguments
 */
public static void main(final String[] args) {
    Configuration configuration;

    int exitCode = 0;
    CLIServerMain.declareOptions();
    try {
        // parse the command line arguments
        commandLine = new BasicParser().parse(options, args);

        // verbosity setup
        verbose = commandLine.hasOption(CMD_VERBOSE);

        // statistics
        stats = commandLine.hasOption(CMD_STATS);

        // daemon mode
        if (commandLine.hasOption(CMD_DAEMON)) {
            System.out.close();
            System.err.close();
            CLIServerMain.getPidFile().deleteOnExit();
        }

        // Find libraries and setup mapping
        final ConcurrentMap<Integer, LookupEntity> lookupEntityMap = ServiceConnectorFactory
                .createLookupEntityMap(CLIServerMain.createRecordMap());

        // Kieker setup
        if (commandLine.hasOption(CMD_KIEKER_CONFIGURATION)) {
            configuration = ConfigurationFactory.createConfigurationFromFile(commandLine.getOptionValue("c"));
        } else {
            configuration = ConfigurationFactory.createSingletonConfiguration();
        }

        // reconfigure kieker configuration
        if (commandLine.hasOption(CMD_PORT) && commandLine.hasOption(CMD_TYPE)) {
            final String type = commandLine.getOptionValue(CMD_TYPE);
            if ("jms-embedded".equals(type)) {
                configuration.setProperty(JMSEmbeddedConnector.PORT, commandLine.getOptionValue(CMD_PORT));
            } else if ("tcp-single-server".equals(type)) {
                configuration.setProperty(TCPSingleServerConnector.PORT, commandLine.getOptionValue(CMD_PORT));
            } else if ("tcp-server".equals(type)) {
                configuration.setProperty(TCPMultiServerConnector.PORT, commandLine.getOptionValue(CMD_PORT));
            } else if ("tcp-client".equals(type)) {
                configuration.setProperty(TCPClientConnector.PORT, commandLine.getOptionValue(CMD_PORT));
            } else if ("http-rest".equals(type)) {
                configuration.setProperty(HTTPConnector.PORT, commandLine.getOptionValue(CMD_PORT));
            }
        }
        if (commandLine.hasOption(CMD_HOST)) {
            configuration.setProperty(TCPClientConnector.HOSTNAME, commandLine.getOptionValue(CMD_HOST));
        }
        if (commandLine.hasOption(CMD_USER)) {
            configuration.setProperty(JMSClientConnector.USERNAME, commandLine.getOptionValue(CMD_USER));
        }
        if (commandLine.hasOption(CMD_PASSWORD)) {
            configuration.setProperty(JMSClientConnector.PASSWORD, commandLine.getOptionValue(CMD_PASSWORD));
        }
        if (commandLine.hasOption(CMD_URL)) {
            configuration.setProperty(JMSClientConnector.URI, commandLine.getOptionValue(CMD_URL));
            configuration.setProperty(HTTPConnector.REST_URL, commandLine.getOptionValue(CMD_URL));
        }
        if (commandLine.hasOption(CMD_CONTEXT)) {
            configuration.setProperty(HTTPConnector.CONTEXT, commandLine.getOptionValue(CMD_CONTEXT));
        }
        if (commandLine.hasOption(CMD_TYPE)) {
            final Reflections reflections = new Reflections("kieker.tools.bridge.connector");
            final Set<Class<?>> connectors = reflections
                    .getTypesAnnotatedWith(kieker.tools.bridge.connector.ConnectorProperty.class);

            for (final Class<?> connector : connectors) {
                if (connector.getAnnotation(kieker.tools.bridge.connector.ConnectorProperty.class).cmdName()
                        .equals(commandLine.getOptionValue(CMD_TYPE))) {
                    configuration.setProperty(CLI_CONNECTOR, connector.getCanonicalName());
                    break;
                }
            }
        }

        // start service depending on type
        final IServiceConnector connector = CLIServerMain.createService(configuration, lookupEntityMap);
        CLIServerMain.getLog().info("Service " + connector.getClass()
                .getAnnotation(kieker.tools.bridge.connector.ConnectorProperty.class).name());
        CLIServerMain.runService(configuration, connector);

    } catch (final ParseException e) {
        CLIServerMain.usage("Parsing failed.  Reason: " + e.getMessage());
        exitCode = 4;
    } catch (final IOException e) {
        CLIServerMain.usage("Mapping file read error: " + e.getMessage());
        exitCode = 1;
    } catch (final CLIConfigurationErrorException e) {
        CLIServerMain.usage("Configuration error: " + e.getMessage());
        exitCode = 2;
    } catch (final ConnectorDataTransmissionException e) {
        CLIServerMain.usage("Communication error: " + e.getMessage());
        exitCode = 3;
    }
    // finally {
    // // The URLClassLoader does not have a close method in Java 1.5
    // // if (classLoader != null) {
    // // try {
    // // classLoader.close();
    // // } catch (final IOException e) {
    // // LOG.error("Classloader failed on close.");
    // // exitCode = 5;
    // // }
    // // }
    // }
    System.exit(exitCode);
}

From source file:com.example.geomesa.kafka08.KafkaLoadTester.java

public static void main(String[] args) throws Exception {
    // read command line args for a connection to Kafka
    CommandLineParser parser = new BasicParser();
    Options options = getCommonRequiredOptions();
    CommandLine cmd = parser.parse(options, args);
    String visibility = getVisibility(cmd);

    if (visibility == null) {
        System.out.println("visibility: null");
    } else {/*from ww w . j  a va 2  s . c o m*/
        System.out.println("visibility: '" + visibility + "'");
    }

    // create the producer and consumer KafkaDataStore objects
    Map<String, String> dsConf = getKafkaDataStoreConf(cmd);
    System.out.println("KDS config: " + dsConf);
    dsConf.put("isProducer", "true");
    DataStore producerDS = DataStoreFinder.getDataStore(dsConf);
    dsConf.put("isProducer", "false");
    DataStore consumerDS = DataStoreFinder.getDataStore(dsConf);

    // verify that we got back our KafkaDataStore objects properly
    if (producerDS == null) {
        throw new Exception("Null producer KafkaDataStore");
    }
    if (consumerDS == null) {
        throw new Exception("Null consumer KafkaDataStore");
    }

    // create the schema which creates a topic in Kafka
    // (only needs to be done once)
    final String sftName = "KafkaStressTest";
    final String sftSchema = "name:String,age:Int,step:Double,lat:Double,dtg:Date,*geom:Point:srid=4326";
    SimpleFeatureType sft = SimpleFeatureTypes.createType(sftName, sftSchema);
    // set zkPath to default if not specified
    String zkPath = (dsConf.get(ZK_PATH) == null) ? "/geomesa/ds/kafka" : dsConf.get(ZK_PATH);
    SimpleFeatureType preppedOutputSft = KafkaDataStoreHelper.createStreamingSFT(sft, zkPath);
    // only create the schema if it hasn't been created already
    if (!Arrays.asList(producerDS.getTypeNames()).contains(sftName))
        producerDS.createSchema(preppedOutputSft);

    System.out.println("Register KafkaDataStore in GeoServer (Press enter to continue)");
    System.in.read();

    // the live consumer must be created before the producer writes features
    // in order to read streaming data.
    // i.e. the live consumer will only read data written after its instantiation
    SimpleFeatureStore producerFS = (SimpleFeatureStore) producerDS.getFeatureSource(sftName);
    SimpleFeatureSource consumerFS = consumerDS.getFeatureSource(sftName);

    // creates and adds SimpleFeatures to the producer every 1/5th of a second
    System.out.println("Writing features to Kafka... refresh GeoServer layer preview to see changes");

    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(sft);

    Integer numFeats = getLoad(cmd);

    System.out.println("Building a list of " + numFeats + " SimpleFeatures.");
    List<SimpleFeature> features = IntStream.range(1, numFeats)
            .mapToObj(i -> createFeature(builder, i, visibility)).collect(Collectors.toList());

    // set variables to estimate feature production rate
    Long startTime = null;
    Long featuresSinceStartTime = 0L;
    int cycle = 0;
    int cyclesToSkip = 50000 / numFeats; // collect enough features
                                         // to get an accurate rate estimate

    while (true) {
        // write features
        features.forEach(feat -> {
            try {
                DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
                featureCollection.add(feat);
                producerFS.addFeatures(featureCollection);
            } catch (Exception e) {
                System.out.println("Caught an exception while writing features.");
                e.printStackTrace();
            }
            updateFeature(feat);
        });

        // count features written
        Integer consumerSize = consumerFS.getFeatures().size();
        cycle++;
        featuresSinceStartTime += consumerSize;
        System.out.println("At " + new Date() + " wrote " + consumerSize + " features");

        // if we've collected enough features, calculate the rate
        if (cycle >= cyclesToSkip || startTime == null) {
            Long endTime = System.currentTimeMillis();
            if (startTime != null) {
                Long diffTime = endTime - startTime;
                Double rate = (featuresSinceStartTime.doubleValue() * 1000.0) / diffTime.doubleValue();
                System.out.printf("%.1f feats/sec (%d/%d)\n", rate, featuresSinceStartTime, diffTime);
            }
            cycle = 0;
            startTime = endTime;
            featuresSinceStartTime = 0L;
        }
    }
}

From source file:autocorrelator.apps.SDFGroovy.java

public static void main(String[] args) throws Exception {
    long start = System.currentTimeMillis();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("in", true, "input sd file");
    options.addOption(opt);//from w ww.  java2s  .co m

    opt = new Option("out", true, "output file for return value true or null");
    options.addOption(opt);

    opt = new Option("falseOut", true, "output file for return value false");
    options.addOption(opt);

    opt = new Option("c", true, "groovy script line");
    options.addOption(opt);

    opt = new Option("f", true, "groovy script file");
    options.addOption(opt);

    opt = new Option("exception", true, "exception handling (Default: stop)");
    options.addOption(opt);

    opt = new Option("h", false, "print help message");
    options.addOption(opt);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        exitWithHelp(e.getMessage(), options);
    }
    if (!cmd.hasOption("c") && !cmd.hasOption("f"))
        exitWithHelp("-c or -f must be given!", options);

    if (cmd.hasOption("c") && cmd.hasOption("f"))
        exitWithHelp("Only one of -c or -f may be given!", options);

    String groovyStrg;
    if (cmd.hasOption("c"))
        groovyStrg = cmd.getOptionValue("c");
    else
        groovyStrg = fileToString(cmd.getOptionValue("f"));

    Set<String> inFileds = new HashSet<String>();
    Set<String> outFields = new HashSet<String>();
    Script script = getGroovyScript(groovyStrg, inFileds, outFields);

    if (cmd.hasOption("h")) {
        callScriptHelp(script);
        exitWithHelp("", options);
    }

    if (!cmd.hasOption("in") || !cmd.hasOption("out")) {
        callScriptHelp(script);
        exitWithHelp("-in and -out must be given", options);
    }

    String[] scriptArgs = cmd.getArgs();
    String inFile = cmd.getOptionValue("in");
    String outFile = cmd.getOptionValue("out");
    String falseOutFile = cmd.getOptionValue("falseOut");
    EXCEPTIONHandling eHandling = EXCEPTIONHandling.stop;
    if (cmd.hasOption("exception"))
        eHandling = EXCEPTIONHandling.getByName(cmd.getOptionValue("exception"));

    callScriptInit(script, scriptArgs);

    oemolistream ifs = new oemolistream(inFile);
    oemolostream ofs = new oemolostream(outFile);
    oemolostream falseOFS = null;
    if (falseOutFile != null)
        falseOFS = new oemolostream(falseOutFile);

    OEMolBase mol = new OEGraphMol();

    int iCounter = 0;
    int oCounter = 0;
    int foCounter = 0;
    while (oechem.OEReadMolecule(ifs, mol)) {
        iCounter++;

        Binding binding = getFieldBindings(mol, inFileds, outFields);

        script.setBinding(binding);
        boolean printToTrue = true;
        boolean printToFalse = true;
        try {
            Object ret = script.run();
            if (ret == null || !(ret instanceof Boolean)) {
                printToFalse = false;
            } else if (((Boolean) ret).booleanValue()) {
                printToFalse = false;
            } else // ret = false
            {
                printToTrue = false;
            }

            setOutputFields(mol, binding, outFields);
        } catch (Exception e) {
            switch (eHandling) {
            case stop:
                throw e;
            case printToTrue:
                printToFalse = false;
                System.err.println(e.getMessage());
                break;
            case printToFalse:
                printToTrue = false;
                System.err.println(e.getMessage());
                break;
            case dropRecord:
                printToTrue = false;
                printToFalse = false;
                System.err.println(e.getMessage());
                break;
            default:
                assert false;
                break;
            }
        }

        if (printToTrue) {
            oechem.OEWriteMolecule(ofs, mol);
            oCounter++;
        }
        if (falseOFS != null && printToFalse) {
            oechem.OEWriteMolecule(falseOFS, mol);
            foCounter++;
        }
    }

    System.err.printf("SDFGroovy: Input %d, output %d,%d structures in %dsec\n", iCounter, oCounter, foCounter,
            (System.currentTimeMillis() - start) / 1000);

    if (falseOFS != null)
        falseOFS.close();
    ofs.close();
    ifs.close();
    mol.delete();
}

From source file:Cresendo.java

public static void main(String[] args) {
    String cfgFileReceiver = null; // Path to config file for eif receiver agent
    String cfgFileEngine = null; // Path to config file for xml event engine
    Options opts = null; // Command line options
    HelpFormatter hf = null; // Command line help formatter

    // Setup the message record which will contain text written to the log file
    ///*from  www  .j a v a2  s .c o m*/
    // The message logger object is created when the "-l" is processed
    // as this object need to be associated with a log file
    //
    LogRecord msg = new LogRecord(LogRecord.TYPE_INFO, "Cresendo", "main", "", "", "", "", "");

    // Get the directory separator (defaults to "/")
    //
    dirSep = System.getProperty("file.separator", "/");

    // Initialise the structure containing the event handler objects
    //
    Vector<IEventHandler> eventHandler = new Vector<IEventHandler>(10, 10);

    // Process the command line arguments
    //
    try {
        opts = new Options();
        hf = new HelpFormatter();

        opts.addOption("h", "help", false, "Command line arguments help");
        opts.addOption("i", "instance name", true, "Name of cresendo instance");
        opts.addOption("l", "log dir", true, "Path to log file directory");
        opts.addOption("c", "config dir", true, "Path to configuarion file directory");

        opts.getOption("l").setRequired(true);
        opts.getOption("c").setRequired(true);

        BasicParser parser = new BasicParser();
        CommandLine cl = parser.parse(opts, args);

        // Print out some help and exit
        //
        if (cl.hasOption('h')) {
            hf.printHelp("Options", opts);
            System.exit(0);
        }

        // Set the instance name
        //
        if (cl.hasOption('i')) {
            instanceName = cl.getOptionValue('i'); // Set to something other than "default"
        }

        // Setup the message and trace logging objects for the EventEngine
        //
        if (cl.hasOption('l')) {
            // Setup the the paths to the message, trace and status log files
            //
            logDir = cl.getOptionValue("l");

            logPath = logDir + dirSep + instanceName + "-engine.log";
            tracePath = logDir + dirSep + instanceName + "-engine.trace";
            statusPath = logDir + dirSep + instanceName + "-engine.status";
        } else {
            // NOTE:  This should be picked up by the MissingOptionException catch below
            //        but I couldn't get this to work so I added the following code:
            //
            hf.printHelp("Option 'l' is a required option", opts);
            System.exit(1);
        }

        // Read the receiver and engine config files in the config directory
        //
        if (cl.hasOption('c')) {
            // Setup and check path to eif config file for TECAgent receiver object
            //
            configDir = cl.getOptionValue("c");
            cfgFileReceiver = configDir + dirSep + instanceName + ".conf";
            checkConfigFile(cfgFileReceiver);

            // Setup and check path to xml config file for the EventEngine
            //
            cfgFileEngine = cl.getOptionValue("c") + dirSep + instanceName + ".xml";
            checkConfigFile(cfgFileEngine);

        } else {
            // NOTE:  This should be picked up by the MissingOptionException catch below
            //        but I couldn't get this to work so I added the following code:
            //
            hf.printHelp("Option 'c' is a required option", opts);
            System.exit(1);
        }
    } catch (UnrecognizedOptionException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (MissingOptionException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (MissingArgumentException e) {
        hf.printHelp(e.toString(), opts);
        System.exit(1);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(1);
    } catch (Exception e) {
        System.err.println(e.toString());
        System.exit(1);
    }

    // Main program
    //
    try {
        // =====================================================================
        // Setup the message, trace and status logger objects
        //
        try {
            msgHandler = new FileHandler("cresendo", "message handler", logPath);
            msgHandler.openDevice();

            msgLogger = new MessageLogger("cresendo", "message log");
            msgLogger.addHandler(msgHandler);

            trcHandler = new FileHandler("cresendo", "trace handler", tracePath);
            trcHandler.openDevice();

            trcLogger = new TraceLogger("cresendo", "trace log");
            trcLogger.addHandler(trcHandler);

            statLogger = new StatusLogger(statusPath);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // Add the shutdown hook
        //
        Runtime.getRuntime().addShutdownHook(new ShutdownThread(msgLogger, instanceName));

        // ---------------------------------------------------------------------
        // =====================================================================
        // Load and parse the xml event engine configuration file
        //
        //
        msg.setText("Loading xml engine from: '" + cfgFileEngine + "'");

        try {
            XMLConfiguration xmlProcessor = new XMLConfiguration();
            xmlProcessor.setFileName(cfgFileEngine);

            // Validate the xml against a document type declaration
            //
            xmlProcessor.setValidating(true);

            // Don't interpolate the tag contents by splitting them on a delimiter
            // (ie by default a comma)
            //
            xmlProcessor.setDelimiterParsingDisabled(true);

            // This will throw a ConfigurationException if the xml document does not
            // conform to its dtd.  By doing this we hopefully catch any errors left
            // behind after the xml configuration file has been edited.
            //
            xmlProcessor.load();

            // Setup the trace flag
            //
            ConfigurationNode engine = xmlProcessor.getRootNode();
            List rootAttribute = engine.getAttributes();

            for (Iterator it = rootAttribute.iterator(); it.hasNext();) {
                ConfigurationNode attr = (ConfigurationNode) it.next();

                String attrName = attr.getName();
                String attrValue = (String) attr.getValue();

                if (attrValue == null || attrValue == "") {
                    System.err.println("\n  Error: The value of the attribute '" + attrName + "'"
                            + "\n         in the xml file '" + cfgFileEngine + "'" + "\n         is not set");
                    System.exit(1);
                }

                if (attrName.matches("trace")) {
                    if (attrValue.matches("true") || attrValue.matches("on")) {
                        trcLogger.setLogging(true);
                    }
                }

                if (attrName.matches("status")) {
                    if (attrValue.matches("true") || attrValue.matches("on")) {
                        statLogger.setLogging(true);
                    } else {
                        statLogger.setLogging(false);
                    }
                }

                if (attrName.matches("interval")) {
                    if (!attrValue.matches("[0-9]+")) {
                        System.err.println("\n  Error: The value of the interval attribute in: '"
                                + cfgFileEngine + "'" + "\n         should only contain digits from 0 to 9."
                                + "\n         It currently contains: '" + attrValue + "'");
                        System.exit(1);
                    }

                    statLogger.setInterval(Integer.parseInt(attrValue));
                }
            }

            // Now build and instantiate the list of classes that will process events
            // received by the TECAgent receiver in a chain like manner.
            //
            List classes = xmlProcessor.configurationsAt("class");

            for (Iterator it = classes.iterator(); it.hasNext();) {
                HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();

                // sub contains now all data contained in a single <class></class> tag set
                //
                String className = sub.getString("name");

                // Log message
                //
                msg.setText(msg.getText() + "\n  Instantiated event handler class: '" + className + "'");

                // The angle brackets describing the class of object held by the
                // Vector are implemented by Java 1.5 and have 2 effects.
                //
                // 1. The list accepts only elements of that class and nothing else
                // (Of course thanks to Auto-Wrap you can also add double-values)
                //
                // 2. the get(), firstElement() ... Methods don't return a Object, but
                //    they deliver an element of the class.
                //
                Vector<Class> optTypes = new Vector<Class>(10, 10);
                Vector<Object> optValues = new Vector<Object>(10, 10);

                for (int i = 0; i <= sub.getMaxIndex("option"); i++) {
                    Object optValue = null;
                    String optVarName = sub.getString("option(" + i + ")[@varname]");
                    String optJavaType = sub.getString("option(" + i + ")[@javatype]");

                    // Use the specified java type in order to make the method call
                    // to the heirarchical sub object [painful :-((]
                    //
                    if (optJavaType.matches("byte")) {
                        optTypes.addElement(byte.class);
                        optValue = sub.getByte("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("short")) {
                        optTypes.addElement(byte.class);
                        optValue = sub.getShort("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("int")) {
                        optTypes.addElement(int.class);
                        optValue = sub.getInt("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("long")) {
                        optTypes.addElement(long.class);
                        optValue = sub.getLong("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("float")) {
                        optTypes.addElement(float.class);
                        optValue = sub.getFloat("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0.0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("double")) {
                        optTypes.addElement(double.class);
                        optValue = sub.getDouble("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = 0.0; // Set to something nullish
                        }
                    } else if (optJavaType.matches("boolean")) {
                        optTypes.addElement(boolean.class);
                        optValue = sub.getBoolean("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = false; // Set to something nullish
                        }
                    } else if (optJavaType.matches("String")) {
                        optTypes.addElement(String.class);
                        optValue = sub.getString("option(" + i + ")");

                        if (optValue == null) // Catch nulls
                        {
                            optValue = ""; // Set it to something nullish
                        }
                    } else {
                        System.err.println(
                                "Error: Unsupported java type found in xml config: '" + optJavaType + "'");
                        System.exit(1);
                    }

                    // Add option value element
                    //
                    //              System.out.println("Option value is: '" + optValue.toString() + "'\n");
                    //
                    optValues.addElement(optValue);

                    // Append to message text
                    //
                    String msgTemp = msg.getText();
                    msgTemp += "\n      option name: '" + optVarName + "'";
                    msgTemp += "\n      option type: '" + optJavaType + "'";
                    msgTemp += "\n     option value: '" + optValues.lastElement().toString() + "'";
                    msg.setText(msgTemp);
                }

                try {
                    // Instantiate the class with the java reflection api
                    //
                    Class klass = Class.forName(className);

                    // Setup an array of paramater types in order to retrieve the matching constructor
                    //
                    Class[] types = optTypes.toArray(new Class[optTypes.size()]);

                    // Get the constructor for the class which matches the parameter types
                    //
                    Constructor konstruct = klass.getConstructor(types);

                    // Create an instance of the event handler
                    //
                    IEventHandler eventProcessor = (IEventHandler) konstruct.newInstance(optValues.toArray());

                    // Add the instance to the list of event handlers
                    //
                    eventHandler.addElement(eventProcessor);

                } catch (InvocationTargetException e) {
                    System.err.println("Error: " + e.toString());
                    System.exit(1);
                } catch (ClassNotFoundException e) {
                    System.err.println("Error: class name not found: '" + className + "' \n" + e.toString());
                    System.exit(1);
                } catch (Exception e) {
                    System.err.println(
                            "Error: failed to instantiate class: '" + className + "' \n" + e.toString());
                    System.exit(1);
                }
            }
        } catch (ConfigurationException cex) // Something went wrong loading the xml file
        {
            System.err.println("\n" + "Error loading XML file: " + cfgFileEngine + "\n" + cex.toString());
            System.exit(1);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // ---------------------------------------------------------------------
        // =====================================================================
        // Setup the TECAgent receiver 
        // 
        Reader cfgIn = null;

        try {
            cfgIn = new FileReader(cfgFileReceiver);
        } catch (Exception e) {
            System.err.println(e.toString());
            System.exit(1);
        }

        // Start the TECAgent receiver and register the event engine handler
        //
        TECAgent receiver = new TECAgent(cfgIn, TECAgent.RECEIVER_MODE, false);

        EventEngine ee = new EventEngine(eventHandler, msgLogger, trcLogger);

        receiver.registerListener(ee);

        // Construct message and send it to the message log
        //
        String text = "\n  Cresendo instance '" + instanceName + "' listening for events on port '"
                + receiver.getConfigVal("ServerPort") + "'";

        msg.setText(msg.getText() + text);
        msgLogger.log(msg); // Send message to log

        // ---------------------------------------------------------------------
        // =====================================================================
        // Initiate status logging
        //
        if (statLogger.isLogging()) {
            int seconds = statLogger.getInterval();

            while (true) {
                try {
                    statLogger.log();
                } catch (Exception ex) {
                    System.err.println("\n  An error occurred while writing to '" + statusPath + "'" + "\n  '"
                            + ex.toString() + "'");
                }

                Thread.sleep(seconds * 1000); // Convert sleep time to milliseconds
            }
        }

        // ---------------------------------------------------------------------
    } catch (Exception e) {
        System.err.println(e.toString());
        System.exit(1);
    }
}

From source file:com.ehi.carshare.Main.java

/**
 * @param args//  w ww .j  a  va 2  s .  co  m
 *            The commandline arguments
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
public static void main(final String[] args) throws Exception {
    // create the command line parser
    CommandLineParser parser = new BasicParser();

    // create the Options
    Options options = new Options();
    options.addOption(buildOption("l", "logFormat", "The apache logformat"));
    options.addOption(buildOption("i", "inputFile", "complete path to the input file"));
    options.addOption(buildOption("o", "outputFile", "complete path to the output file"));

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String logformat = line.getOptionValue('l');
        String inputFile = line.getOptionValue('i');
        String outputFile = line.getOptionValue('o');
        new Main().run(logformat, inputFile, outputFile);

    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("myapp", "", options, "", true);
    }

}

From source file:com.fatwire.dta.sscrawler.App.java

/**
 * @param args/*from ww  w .ja v  a2 s  .c om*/
 * @throws Exception
 */
public static void main(final String[] args) throws Exception {

    if (args.length < 1) {
        printUsage();
        System.exit(1);
    }
    DOMConfigurator.configure("conf/log4j.xml");
    final Options o = App.setUpCmd();
    final CommandLineParser p = new BasicParser();
    try {
        final CommandLine s = p.parse(o, args);
        if (s.hasOption('h')) {
            printUsage();
        } else if (s.getArgList().contains("crawler") && s.getArgList().size() > 1) {
            new App().doWork(s);
        } else if (s.getArgList().contains("warmer") && s.getArgList().size() > 1) {
            new CacheWarmer().doWork(s);
        } else {
            System.err.println("no subcommand and/or URI found on " + s.getArgList());
            printUsage();
            System.exit(1);
        }

    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        printUsage();
        System.exit(1);
    }

}

From source file:com.esri.geoevent.test.tools.RunTcpInTcpOutTest.java

public static void main(String args[]) {
    int numberEvents = 10000;
    //int brake = 1000;
    String server = "ags104";
    int in_port = 5565;
    int out_port = 5575;
    int start_rate = 5000;
    int end_rate = 5005;
    int rate_step = 1;

    Options opts = new Options();
    opts.addOption("n", true, "Number of Events");
    opts.addOption("s", true, "Server");
    opts.addOption("i", true, "Input TCP Port");
    opts.addOption("o", true, "Output TCP Port");
    opts.addOption("r", true, "Range");
    opts.addOption("h", false, "Help");
    try {//  w  w w.j  a v  a 2 s.c o m

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = null;

        try {
            cmd = parser.parse(opts, args, false);
        } catch (ParseException ignore) {
            System.err.println(ignore.getMessage());
        }

        String cmdInputErrorMsg = "";

        if (cmd.getOptions().length == 0 || cmd.hasOption("h")) {
            throw new ParseException("Show Help");
        }

        if (cmd.hasOption("n")) {
            String val = cmd.getOptionValue("n");
            try {
                numberEvents = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for n. Must be integer.\n";
            }
        }

        if (cmd.hasOption("s")) {
            server = cmd.getOptionValue("s");
        }

        if (cmd.hasOption("i")) {
            String val = cmd.getOptionValue("i");
            try {
                in_port = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for i. Must be integer.\n";
            }
        }

        if (cmd.hasOption("o")) {
            String val = cmd.getOptionValue("o");
            try {
                out_port = Integer.valueOf(val);
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for o. Must be integer.\n";
            }
        }

        if (cmd.hasOption("r")) {
            String val = cmd.getOptionValue("r");
            try {
                String parts[] = val.split(",");
                if (parts.length == 3) {
                    start_rate = Integer.parseInt(parts[0]);
                    end_rate = Integer.parseInt(parts[1]);
                    rate_step = Integer.parseInt(parts[2]);
                } else if (parts.length == 1) {
                    // Run single rate
                    start_rate = Integer.parseInt(parts[0]);
                    end_rate = start_rate;
                    rate_step = start_rate;
                } else {
                    throw new ParseException("Rate must be three comma seperated values or a single value");
                }

            } catch (ParseException e) {
                cmdInputErrorMsg += e.getMessage();
            } catch (NumberFormatException e) {
                cmdInputErrorMsg += "Invalid value for r. Must be integers.\n";
            }
        }

        if (!cmdInputErrorMsg.equalsIgnoreCase("")) {
            throw new ParseException(cmdInputErrorMsg);
        }
        DecimalFormat df = new DecimalFormat("##0");
        RunTcpInTcpOutTest t = new RunTcpInTcpOutTest();

        if (start_rate == end_rate) {
            // Single Rate Test
            System.out.println("*********************************");
            System.out.println("Incremental testing at requested rate: " + start_rate);
            System.out.println("Count,Incremental Rate");

            t.runTest(numberEvents, start_rate, server, in_port, out_port, true);
            if (t.send_rate < 0 || t.rcv_rate < 0) {
                throw new Exception("Test Run Failed!");
            }
            System.out.println("Overall Average Send Rate, Received Rate");
            System.out.println(df.format(t.send_rate) + "," + df.format(t.rcv_rate));

        } else {
            System.out.println("*********************************");
            System.out.println("rateRqstd,avgSendRate,avgRcvdRate");

            //for (int rate: rates) {
            for (int rate = start_rate; rate <= end_rate; rate += rate_step) {

                t.runTest(numberEvents, rate, server, in_port, out_port, false);
                if (t.send_rate < 0 || t.rcv_rate < 0) {
                    throw new Exception("Test Run Failed!");
                }
                System.out.println(
                        Integer.toString(rate) + "," + df.format(t.send_rate) + "," + df.format(t.rcv_rate));
            }

        }

    } catch (ParseException e) {
        System.out.println("Invalid Command Options: ");
        System.out.println(e.getMessage());
        System.out.println(
                "Command line options: -n NumEvents -s Server -i InputPort -o OutputPort -r StartRate,EndRate,Step");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:AwsConsoleApp.java

public static void main(String[] args) throws Exception {

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS VPN connection creator");
    System.out.println("===========================================");

    init();/*from w  w w .  ja  v  a2 s  .co  m*/
    List<String> CIDRblocks = new ArrayList<String>();
    String vpnType = null;
    String vpnGatewayId = null;
    String customerGatewayId = null;
    String customerGatewayInfoPath = null;
    String routes = null;

    options.addOption("h", "help", false, "show help.");
    options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)");
    options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)");
    options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)");
    options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24");
    options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    // Parse command line options
    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption("h"))
            help();

        if (cmd.hasOption("vt")) {
            log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt"));

            vpnType = cmd.getOptionValue("vt");

            // Whatever you want to do with the setting goes here
        } else {
            log.log(Level.SEVERE, "Missing vt option");
            help();
        }

        if (cmd.hasOption("vgw")) {
            log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw"));
            vpnGatewayId = cmd.getOptionValue("vgw");
        } else {
            log.log(Level.SEVERE, "Missing vgw option");
            help();
        }

        if (cmd.hasOption("cgw")) {
            log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw"));
            customerGatewayId = cmd.getOptionValue("cgw");

        } else {
            log.log(Level.SEVERE, "Missing cgw option");
            help();
        }

        if (cmd.hasOption("r")) {
            log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r"));
            routes = cmd.getOptionValue("r");

            String[] routeItems = routes.split(",");
            CIDRblocks = Arrays.asList(routeItems);

        } else {
            log.log(Level.SEVERE, "Missing r option");
            help();
        }

        if (cmd.hasOption("vi")) {
            log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi"));
            customerGatewayInfoPath = cmd.getOptionValue("vi");

        } else {
            log.log(Level.SEVERE, "Missing vi option");
            help();
        }

    } catch (ParseException e) {
        log.log(Level.SEVERE, "Failed to parse comand line properties", e);
        help();
    }

    /*
     * Amazon VPC
     * Create and delete VPN tunnel to customer VPN hardware
     */
    try {

        //String vpnType = "ipsec.1";
        //String vpnGatewayId = "vgw-eca54d85";
        //String customerGatewayId = "cgw-c16e87a8";
        //List<String> CIDRblocks = new ArrayList<String>();
        //CIDRblocks.add("10.77.77.0/24");
        //CIDRblocks.add("172.16.1.0/24");
        //CIDRblocks.add("172.18.1.0/24");
        //CIDRblocks.add("10.66.66.0/24");
        //CIDRblocks.add("10.8.1.0/24");

        //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml";

        Boolean staticRoutesOnly = true;

        List<String> connectionIds = new ArrayList<String>();
        List<String> connectionIdList = new ArrayList<String>();

        connectionIdList = vpnExists(connectionIds);

        if (connectionIdList.size() == 0) {
            CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId,
                    vpnGatewayId);
            CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult();

            VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification();
            vpnspec.setStaticRoutesOnly(staticRoutesOnly);
            vpnReq.setOptions(vpnspec);

            System.out.println("Creating VPN connection");
            vpnRes = ec2.createVpnConnection(vpnReq);
            String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId();
            String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration();

            //System.out.println("Customer Gateway Info:" + customerGatewayInfo);

            // Write Customer Gateway Info to file
            System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath);
            try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) {
                out.print(customerGatewayInfo);
            }

            System.out.println("Creating VPN routes");
            for (String destCIDR : CIDRblocks) {
                CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest();
                CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult();

                routeReq.setDestinationCidrBlock(destCIDR);
                routeReq.setVpnConnectionId(vpnConnId);

                routeRes = ec2.createVpnConnectionRoute(routeReq);
            }

            // Parse XML file
            File file = new File(customerGatewayInfoPath);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(customerGatewayInfoPath);

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression exprGetipAddress = xpath
                    .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address");
            NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET);
            if (vpnGateway != null) {
                for (int i = 0; i < vpnGateway.getLength(); i++) {
                    String vpnGatewayIP = vpnGateway.item(i).getTextContent();
                    System.out
                            .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP);
                }
            }

            System.out.println("==============================================");

            XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key");
            NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET);
            if (presharedKeyList != null) {
                for (int i = 0; i < presharedKeyList.getLength(); i++) {
                    String pre_shared_key = presharedKeyList.item(i).getTextContent();
                    System.out.println(
                            "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key);
                }
            }

            System.out.println("Creating VPN creation completed!");

        } else {
            boolean yn;
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter yes or no to delete VPN connection: ");
            String input = scan.next();
            String answer = input.trim().toLowerCase();
            while (true) {
                if (answer.equals("yes")) {
                    yn = true;
                    break;
                } else if (answer.equals("no")) {
                    yn = false;
                    System.exit(0);
                } else {
                    System.out.println("Sorry, I didn't catch that. Please answer yes/no");
                }
            }

            // Delete all existing VPN connections
            System.out.println("Deleting AWS VPN connection(s)");

            for (String vpnConID : connectionIdList) {
                DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult();
                DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest();
                delVPNreq.setVpnConnectionId(vpnConID);

                delVPNres = ec2.deleteVpnConnection(delVPNreq);
                System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID);

            }

        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}