Example usage for org.apache.commons.cli OptionBuilder create

List of usage examples for org.apache.commons.cli OptionBuilder create

Introduction

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

Prototype

public static Option create(String opt) throws IllegalArgumentException 

Source Link

Document

Create an Option using the current settings and with the specified Option char.

Usage

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFMapQuerySpecificInvisibleMethodDeclarations.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//  w  w w .ja  v a2 s.  c o m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = NeoEMFMapQuerySpecificInvisibleMethodDeclarations.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(MapResourceOptions.EStoreMapOption.AUTOCOMMIT);
        storeOptions.add(PersistentResourceOptions.EStoreOption.ESTRUCUTRALFEATURE_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.IS_SET_CACHING);
        storeOptions.add(PersistentResourceOptions.EStoreOption.SIZE_CACHING);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        resource.load(loadOpts);
        {
            Runtime.getRuntime().gc();
            long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                    MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = ASE2015JavaQueries.getSpecificInvisibleMethodDeclarations(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            Runtime.getRuntime().gc();
            long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
            LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFGraphQueryInvisibleMethodDeclarations.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);//from   w  ww . j  a v  a  2 s. c o  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = NeoEMFGraphQueryInvisibleMethodDeclarations.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        System.out.println(loadOpts);
        resource.load(loadOpts);
        {
            Runtime.getRuntime().gc();
            long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                    MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = ASE2015JavaQueries.getInvisibleMethodDeclarations(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            Runtime.getRuntime().gc();
            long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
            LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFGraphQueryGrabats09.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*from  w  ww  .  j a v  a2 s . c  o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = NeoEMFGraphQueryGrabats09.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        resource.load(loadOpts);
        {
            Runtime.getRuntime().gc();
            long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                    MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<ClassDeclaration> list = ASE2015JavaQueries.grabats09(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            Runtime.getRuntime().gc();
            long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
            LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFGraphQuerySpecificInvisibleMethodDeclarations.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*www  . ja va2 s.co m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = NeoEMFGraphQuerySpecificInvisibleMethodDeclarations.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        resource.load(loadOpts);
        {
            Runtime.getRuntime().gc();
            long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                    MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<MethodDeclaration> list = ASE2015JavaQueries.getSpecificInvisibleMethodDeclarations(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            Runtime.getRuntime().gc();
            long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
            LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.ase2015.NeoEMFGraphQueryThrownExceptions.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);// w  w  w .j a v  a2s  . c  o  m
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = NeoEMFGraphQueryThrownExceptions.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        // Add the LoadedObjectCounter store
        List<StoreOption> storeOptions = new ArrayList<StoreOption>();
        //         storeOptions.add(PersistentResourceOptions.EStoreOption.LOADED_OBJECT_COUNTER_LOGGING);
        storeOptions.add(BlueprintsResourceOptions.EStoreGraphOption.AUTOCOMMIT);
        loadOpts.put(PersistentResourceOptions.STORE_OPTIONS, storeOptions);
        resource.load(loadOpts);
        {
            Runtime.getRuntime().gc();
            long initialUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory before query: {0}",
                    MessageUtil.byteCountToDisplaySize(initialUsedMemory)));
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<TypeAccess> list = ASE2015JavaQueries.getThrownExceptions(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
            Runtime.getRuntime().gc();
            long finalUsedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
            LOG.log(Level.INFO, MessageFormat.format("Used memory after query: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory)));
            LOG.log(Level.INFO, MessageFormat.format("Memory use increase: {0}",
                    MessageUtil.byteCountToDisplaySize(finalUsedMemory - initialUsedMemory)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args//ww w .  j  av  a 2s .  c o m
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:com.comcast.oscar.cli.commands.FullTLVDisplay.java

/**
 * Set option parameters for command Full TLV display
 * @return Option//from  w  w w .j  av  a 2s .  c  o  m
 */
public static final Option OptionParameters() {
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withLongOpt("fulltlvdisplay");
    OptionBuilder
            .withDescription("Display all TLVs available in the dictionary for the defined specification.");
    return OptionBuilder.create("ftd");
}

From source file:com.comcast.oscar.cli.commands.Key.java

/**
 * Set option parameters for command Key
 * @return Option/*from   w w  w.j  a  v  a  2 s  .c om*/
 */
public static Option OptionParameters() {
    OptionBuilder.withArgName("key filename");
    OptionBuilder.hasArgs(1);
    OptionBuilder.hasOptionalArgs();
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withLongOpt("key");
    OptionBuilder.withDescription("Use this sharedsecret to compile the file - DOCSIS ONLY.");
    return OptionBuilder.create("k");
}

From source file:com.comcast.oscar.cli.commands.TLV.java

/**
 * Set option parameters for command TLV
 * @return Option/*  w ww .  j  av a 2  s .c  om*/
 */
public static final Option OptionParameters() {
    OptionBuilder.withArgName("TLV");
    OptionBuilder.hasArgs(1);
    OptionBuilder.hasOptionalArgs();
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withLongOpt("tlv");
    OptionBuilder.withDescription("Insert this TLV during file compilation.");
    return OptionBuilder.create("t");
}

From source file:com.comcast.oscar.cli.commands.Firmware.java

/**
 * Set option parameters for command Firmware
 * @return Option//from w  ww . j  a  va2s  .com
 */
public static final Option OptionParameters() {
    OptionBuilder.withArgName("filename");
    OptionBuilder.hasArgs(1);
    OptionBuilder.hasOptionalArgs();
    OptionBuilder.withValueSeparator(' ');
    OptionBuilder.withLongOpt("firmware");
    OptionBuilder.withDescription("Insert this firmware during file compilation.");
    return OptionBuilder.create("f");
}