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

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

Introduction

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

Prototype

public static OptionBuilder withValueSeparator(char sep) 

Source Link

Document

The next Option created uses sep as a means to separate argument values.

Usage

From source file:org.dspace.app.mediafilter.MediaFilterCLITool.java

public static void main(String[] argv) throws Exception {
    // set headless for non-gui workstations
    System.setProperty("java.awt.headless", "true");

    // create an options object and populate it
    CommandLineParser parser = new PosixParser();

    int status = 0;

    Options options = new Options();

    options.addOption("v", "verbose", false, "print all extracted text and other details to STDOUT");
    options.addOption("q", "quiet", false, "do not print anything except in the event of errors.");
    options.addOption("f", "force", false, "force all bitstreams to be processed");
    options.addOption("i", "identifier", true, "ONLY process bitstreams belonging to identifier");
    options.addOption("m", "maximum", true, "process no more than maximum items");
    options.addOption("h", "help", false, "help");

    //create a "plugin" option (to specify specific MediaFilter plugins to run)
    OptionBuilder.withLongOpt("plugins");
    OptionBuilder.withValueSeparator(',');
    OptionBuilder.withDescription("ONLY run the specified Media Filter plugin(s)\n" + "listed from '"
            + MEDIA_FILTER_PLUGINS_KEY + "' in dspace.cfg.\n" + "Separate multiple with a comma (,)\n"
            + "(e.g. MediaFilterManager -p \n\"Word Text Extractor\",\"PDF Text Extractor\")");
    Option pluginOption = OptionBuilder.create('p');
    pluginOption.setArgs(Option.UNLIMITED_VALUES); //unlimited number of args
    options.addOption(pluginOption);//from   ww  w  .  ja v a  2s.  co  m

    //create a "skip" option (to specify communities/collections/items to skip)
    OptionBuilder.withLongOpt("skip");
    OptionBuilder.withValueSeparator(',');
    OptionBuilder.withDescription(
            "SKIP the bitstreams belonging to identifier\n" + "Separate multiple identifiers with a comma (,)\n"
                    + "(e.g. MediaFilterManager -s \n 123456789/34,123456789/323)");
    Option skipOption = OptionBuilder.create('s');
    skipOption.setArgs(Option.UNLIMITED_VALUES); //unlimited number of args
    options.addOption(skipOption);

    boolean isVerbose = false;
    boolean isQuiet = false;
    boolean isForce = false; // default to not forced
    String identifier = null; // object scope limiter
    int max2Process = Integer.MAX_VALUE;
    Map<String, List<String>> filterFormats = new HashMap<>();

    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (MissingArgumentException e) {
        System.out.println("ERROR: " + e.getMessage());
        HelpFormatter myhelp = new HelpFormatter();
        myhelp.printHelp("MediaFilterManager\n", options);
        System.exit(1);
    }

    if (line.hasOption('h')) {
        HelpFormatter myhelp = new HelpFormatter();
        myhelp.printHelp("MediaFilterManager\n", options);

        System.exit(0);
    }

    if (line.hasOption('v')) {
        isVerbose = true;
    }

    isQuiet = line.hasOption('q');

    if (line.hasOption('f')) {
        isForce = true;
    }

    if (line.hasOption('i')) {
        identifier = line.getOptionValue('i');
    }

    if (line.hasOption('m')) {
        max2Process = Integer.parseInt(line.getOptionValue('m'));
        if (max2Process <= 1) {
            System.out.println("Invalid maximum value '" + line.getOptionValue('m') + "' - ignoring");
            max2Process = Integer.MAX_VALUE;
        }
    }

    String filterNames[] = null;
    if (line.hasOption('p')) {
        //specified which media filter plugins we are using
        filterNames = line.getOptionValues('p');

        if (filterNames == null || filterNames.length == 0) { //display error, since no plugins specified
            System.err.println("\nERROR: -p (-plugin) option requires at least one plugin to be specified.\n"
                    + "(e.g. MediaFilterManager -p \"Word Text Extractor\",\"PDF Text Extractor\")\n");
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("MediaFilterManager\n", options);
            System.exit(1);
        }
    } else {
        //retrieve list of all enabled media filter plugins!
        filterNames = DSpaceServicesFactory.getInstance().getConfigurationService()
                .getArrayProperty(MEDIA_FILTER_PLUGINS_KEY);
    }

    MediaFilterService mediaFilterService = MediaFilterServiceFactory.getInstance().getMediaFilterService();
    mediaFilterService.setForce(isForce);
    mediaFilterService.setQuiet(isQuiet);
    mediaFilterService.setVerbose(isVerbose);
    mediaFilterService.setMax2Process(max2Process);

    //initialize an array of our enabled filters
    List<FormatFilter> filterList = new ArrayList<FormatFilter>();

    //set up each filter
    for (int i = 0; i < filterNames.length; i++) {
        //get filter of this name & add to list of filters
        FormatFilter filter = (FormatFilter) CoreServiceFactory.getInstance().getPluginService()
                .getNamedPlugin(FormatFilter.class, filterNames[i]);
        if (filter == null) {
            System.err.println(
                    "\nERROR: Unknown MediaFilter specified (either from command-line or in dspace.cfg): '"
                            + filterNames[i] + "'");
            System.exit(1);
        } else {
            filterList.add(filter);

            String filterClassName = filter.getClass().getName();

            String pluginName = null;

            //If this filter is a SelfNamedPlugin,
            //then the input formats it accepts may differ for
            //each "named" plugin that it defines.
            //So, we have to look for every key that fits the
            //following format: filter.<class-name>.<plugin-name>.inputFormats
            if (SelfNamedPlugin.class.isAssignableFrom(filter.getClass())) {
                //Get the plugin instance name for this class
                pluginName = ((SelfNamedPlugin) filter).getPluginInstanceName();
            }

            //Retrieve our list of supported formats from dspace.cfg
            //For SelfNamedPlugins, format of key is:
            //  filter.<class-name>.<plugin-name>.inputFormats
            //For other MediaFilters, format of key is:
            //  filter.<class-name>.inputFormats
            String[] formats = DSpaceServicesFactory.getInstance().getConfigurationService()
                    .getArrayProperty(FILTER_PREFIX + "." + filterClassName
                            + (pluginName != null ? "." + pluginName : "") + "." + INPUT_FORMATS_SUFFIX);

            //add to internal map of filters to supported formats
            if (ArrayUtils.isNotEmpty(formats)) {
                //For SelfNamedPlugins, map key is:
                //  <class-name><separator><plugin-name>
                //For other MediaFilters, map key is just:
                //  <class-name>
                filterFormats.put(filterClassName
                        + (pluginName != null ? MediaFilterService.FILTER_PLUGIN_SEPARATOR + pluginName : ""),
                        Arrays.asList(formats));
            }
        } //end if filter!=null
    } //end for

    //If verbose, print out loaded mediafilter info
    if (isVerbose) {
        System.out.println("The following MediaFilters are enabled: ");
        Iterator<String> i = filterFormats.keySet().iterator();
        while (i.hasNext()) {
            String filterName = i.next();
            System.out.println("Full Filter Name: " + filterName);
            String pluginName = null;
            if (filterName.contains(MediaFilterService.FILTER_PLUGIN_SEPARATOR)) {
                String[] fields = filterName.split(MediaFilterService.FILTER_PLUGIN_SEPARATOR);
                filterName = fields[0];
                pluginName = fields[1];
            }

            System.out.println(filterName + (pluginName != null ? " (Plugin: " + pluginName + ")" : ""));
        }
    }

    mediaFilterService.setFilterFormats(filterFormats);
    //store our filter list into an internal array
    mediaFilterService.setFilterClasses(filterList);

    //Retrieve list of identifiers to skip (if any)
    String skipIds[] = null;
    if (line.hasOption('s')) {
        //specified which identifiers to skip when processing
        skipIds = line.getOptionValues('s');

        if (skipIds == null || skipIds.length == 0) { //display error, since no identifiers specified to skip
            System.err.println("\nERROR: -s (-skip) option requires at least one identifier to SKIP.\n"
                    + "Make sure to separate multiple identifiers with a comma!\n"
                    + "(e.g. MediaFilterManager -s 123456789/34,123456789/323)\n");
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("MediaFilterManager\n", options);
            System.exit(0);
        }

        //save to a global skip list
        mediaFilterService.setSkipList(Arrays.asList(skipIds));
    }

    Context c = null;

    try {
        c = new Context();

        // have to be super-user to do the filtering
        c.turnOffAuthorisationSystem();

        // now apply the filters
        if (identifier == null) {
            mediaFilterService.applyFiltersAllItems(c);
        } else // restrict application scope to identifier
        {
            DSpaceObject dso = HandleServiceFactory.getInstance().getHandleService().resolveToObject(c,
                    identifier);
            if (dso == null) {
                throw new IllegalArgumentException("Cannot resolve " + identifier + " to a DSpace object");
            }

            switch (dso.getType()) {
            case Constants.COMMUNITY:
                mediaFilterService.applyFiltersCommunity(c, (Community) dso);
                break;
            case Constants.COLLECTION:
                mediaFilterService.applyFiltersCollection(c, (Collection) dso);
                break;
            case Constants.ITEM:
                mediaFilterService.applyFiltersItem(c, (Item) dso);
                break;
            }
        }

        c.complete();
        c = null;
    } catch (Exception e) {
        status = 1;
    } finally {
        if (c != null) {
            c.abort();
        }
    }
    System.exit(status);
}

From source file:org.dspace.app.mediafilter.MediaFilterManager.java

public static void main(String[] argv) throws Exception {
    // set headless for non-gui workstations
    System.setProperty("java.awt.headless", "true");

    // create an options object and populate it
    CommandLineParser parser = new PosixParser();

    int status = 0;

    Options options = new Options();

    options.addOption("v", "verbose", false, "print all extracted text and other details to STDOUT");
    options.addOption("q", "quiet", false, "do not print anything except in the event of errors.");
    options.addOption("f", "force", false, "force all bitstreams to be processed");
    options.addOption("n", "noindex", false, "do NOT update the search index after filtering bitstreams");
    options.addOption("i", "identifier", true, "ONLY process bitstreams belonging to identifier");
    options.addOption("m", "maximum", true, "process no more than maximum items");
    options.addOption("h", "help", false, "help");

    //create a "plugin" option (to specify specific MediaFilter plugins to run)
    OptionBuilder.withLongOpt("plugins");
    OptionBuilder.withValueSeparator(',');
    OptionBuilder.withDescription("ONLY run the specified Media Filter plugin(s)\n" + "listed from '"
            + MEDIA_FILTER_PLUGINS_KEY + "' in dspace.cfg.\n" + "Separate multiple with a comma (,)\n"
            + "(e.g. MediaFilterManager -p \n\"Word Text Extractor\",\"PDF Text Extractor\")");
    Option pluginOption = OptionBuilder.create('p');
    pluginOption.setArgs(Option.UNLIMITED_VALUES); //unlimited number of args
    options.addOption(pluginOption);// ww  w  .  j a v a  2s .  c o  m

    //create a "skip" option (to specify communities/collections/items to skip)
    OptionBuilder.withLongOpt("skip");
    OptionBuilder.withValueSeparator(',');
    OptionBuilder.withDescription(
            "SKIP the bitstreams belonging to identifier\n" + "Separate multiple identifiers with a comma (,)\n"
                    + "(e.g. MediaFilterManager -s \n 123456789/34,123456789/323)");
    Option skipOption = OptionBuilder.create('s');
    skipOption.setArgs(Option.UNLIMITED_VALUES); //unlimited number of args
    options.addOption(skipOption);

    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (MissingArgumentException e) {
        System.out.println("ERROR: " + e.getMessage());
        HelpFormatter myhelp = new HelpFormatter();
        myhelp.printHelp("MediaFilterManager\n", options);
        System.exit(1);
    }

    if (line.hasOption('h')) {
        HelpFormatter myhelp = new HelpFormatter();
        myhelp.printHelp("MediaFilterManager\n", options);

        System.exit(0);
    }

    if (line.hasOption('v')) {
        isVerbose = true;
    }

    isQuiet = line.hasOption('q');

    if (line.hasOption('n')) {
        updateIndex = false;
    }

    if (line.hasOption('f')) {
        isForce = true;
    }

    if (line.hasOption('i')) {
        identifier = line.getOptionValue('i');
    }

    if (line.hasOption('m')) {
        max2Process = Integer.parseInt(line.getOptionValue('m'));
        if (max2Process <= 1) {
            System.out.println("Invalid maximum value '" + line.getOptionValue('m') + "' - ignoring");
            max2Process = Integer.MAX_VALUE;
        }
    }

    String filterNames[] = null;
    if (line.hasOption('p')) {
        //specified which media filter plugins we are using
        filterNames = line.getOptionValues('p');

        if (filterNames == null || filterNames.length == 0) { //display error, since no plugins specified
            System.err.println("\nERROR: -p (-plugin) option requires at least one plugin to be specified.\n"
                    + "(e.g. MediaFilterManager -p \"Word Text Extractor\",\"PDF Text Extractor\")\n");
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("MediaFilterManager\n", options);
            System.exit(1);
        }
    } else {
        //retrieve list of all enabled media filter plugins!
        String enabledPlugins = ConfigurationManager.getProperty(MEDIA_FILTER_PLUGINS_KEY);
        filterNames = enabledPlugins.split(",\\s*");
    }

    //initialize an array of our enabled filters
    List<FormatFilter> filterList = new ArrayList<FormatFilter>();

    //set up each filter
    for (int i = 0; i < filterNames.length; i++) {
        //get filter of this name & add to list of filters
        FormatFilter filter = (FormatFilter) PluginManager.getNamedPlugin(FormatFilter.class, filterNames[i]);
        if (filter == null) {
            System.err.println(
                    "\nERROR: Unknown MediaFilter specified (either from command-line or in dspace.cfg): '"
                            + filterNames[i] + "'");
            System.exit(1);
        } else {
            filterList.add(filter);

            String filterClassName = filter.getClass().getName();

            String pluginName = null;

            //If this filter is a SelfNamedPlugin,
            //then the input formats it accepts may differ for
            //each "named" plugin that it defines.
            //So, we have to look for every key that fits the
            //following format: filter.<class-name>.<plugin-name>.inputFormats
            if (SelfNamedPlugin.class.isAssignableFrom(filter.getClass())) {
                //Get the plugin instance name for this class
                pluginName = ((SelfNamedPlugin) filter).getPluginInstanceName();
            }

            //Retrieve our list of supported formats from dspace.cfg
            //For SelfNamedPlugins, format of key is:  
            //  filter.<class-name>.<plugin-name>.inputFormats
            //For other MediaFilters, format of key is: 
            //  filter.<class-name>.inputFormats
            String formats = ConfigurationManager.getProperty(FILTER_PREFIX + "." + filterClassName
                    + (pluginName != null ? "." + pluginName : "") + "." + INPUT_FORMATS_SUFFIX);

            //add to internal map of filters to supported formats   
            if (formats != null) {
                //For SelfNamedPlugins, map key is:  
                //  <class-name><separator><plugin-name>
                //For other MediaFilters, map key is just:
                //  <class-name>
                filterFormats.put(
                        filterClassName + (pluginName != null ? FILTER_PLUGIN_SEPARATOR + pluginName : ""),
                        Arrays.asList(formats.split(",[\\s]*")));
            }
        } //end if filter!=null
    } //end for

    //If verbose, print out loaded mediafilter info
    if (isVerbose) {
        System.out.println("The following MediaFilters are enabled: ");
        Iterator<String> i = filterFormats.keySet().iterator();
        while (i.hasNext()) {
            String filterName = i.next();
            System.out.println("Full Filter Name: " + filterName);
            String pluginName = null;
            if (filterName.contains(FILTER_PLUGIN_SEPARATOR)) {
                String[] fields = filterName.split(FILTER_PLUGIN_SEPARATOR);
                filterName = fields[0];
                pluginName = fields[1];
            }

            System.out.println(filterName + (pluginName != null ? " (Plugin: " + pluginName + ")" : ""));
        }
    }

    //store our filter list into an internal array
    filterClasses = (FormatFilter[]) filterList.toArray(new FormatFilter[filterList.size()]);

    //Retrieve list of identifiers to skip (if any)
    String skipIds[] = null;
    if (line.hasOption('s')) {
        //specified which identifiers to skip when processing
        skipIds = line.getOptionValues('s');

        if (skipIds == null || skipIds.length == 0) { //display error, since no identifiers specified to skip
            System.err.println("\nERROR: -s (-skip) option requires at least one identifier to SKIP.\n"
                    + "Make sure to separate multiple identifiers with a comma!\n"
                    + "(e.g. MediaFilterManager -s 123456789/34,123456789/323)\n");
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("MediaFilterManager\n", options);
            System.exit(0);
        }

        //save to a global skip list
        skipList = Arrays.asList(skipIds);
    }

    Context c = null;

    try {
        c = new Context();

        // have to be super-user to do the filtering
        c.turnOffAuthorisationSystem();

        // now apply the filters
        if (identifier == null) {
            applyFiltersAllItems(c);
        } else // restrict application scope to identifier
        {
            DSpaceObject dso = HandleManager.resolveToObject(c, identifier);
            if (dso == null) {
                throw new IllegalArgumentException("Cannot resolve " + identifier + " to a DSpace object");
            }

            switch (dso.getType()) {
            case Constants.COMMUNITY:
                applyFiltersCommunity(c, (Community) dso);
                break;
            case Constants.COLLECTION:
                applyFiltersCollection(c, (Collection) dso);
                break;
            case Constants.ITEM:
                applyFiltersItem(c, (Item) dso);
                break;
            }
        }

        // update search index?
        if (updateIndex) {
            if (!isQuiet) {
                System.out.println("Updating search index:");
            }
            DSIndexer.setBatchProcessingMode(true);
            try {
                DSIndexer.updateIndex(c);
            } finally {
                DSIndexer.setBatchProcessingMode(false);
            }
        }

        c.complete();
        c = null;
    } catch (Exception e) {
        status = 1;
    } finally {
        if (c != null) {
            c.abort();
        }
    }
    System.exit(status);
}

From source file:org.dspace.papaya.mediafilter.PapayaMediaFilterManager.java

public static void main(String[] argv) throws Exception {
    // set headless for non-gui workstations
    System.setProperty("java.awt.headless", "true");

    // create an options object and populate it
    CommandLineParser parser = new PosixParser();

    int status = 0;

    Options options = new Options();

    options.addOption("v", "verbose", false, "print all extracted text and other details to STDOUT");
    options.addOption("q", "quiet", false, "do not print anything except in the event of errors.");
    options.addOption("f", "force", false, "force all bitstreams to be processed");
    options.addOption("i", "identifier", true, "ONLY process bitstreams belonging to identifier");
    options.addOption("m", "maximum", true, "process no more than maximum items");
    options.addOption("h", "help", false, "help");

    //create a "plugin" option (to specify specific MediaFilter plugins to run)
    OptionBuilder.withLongOpt("plugins");
    OptionBuilder.withValueSeparator(',');
    OptionBuilder.withDescription("ONLY run the specified Media Filter plugin(s)\n" + "listed from '"
            + MEDIA_FILTER_PLUGINS_KEY + "' in dspace.cfg.\n" + "Separate multiple with a comma (,)\n"
            + "(e.g. MediaFilterManager -p \n\"Word Text Extractor\",\"PDF Text Extractor\")");
    Option pluginOption = OptionBuilder.create('p');
    pluginOption.setArgs(Option.UNLIMITED_VALUES); //unlimited number of args
    options.addOption(pluginOption);/*w  ww  .j a  va 2  s  .  c om*/

    //create a "skip" option (to specify communities/collections/items to skip)
    OptionBuilder.withLongOpt("skip");
    OptionBuilder.withValueSeparator(',');
    OptionBuilder.withDescription(
            "SKIP the bitstreams belonging to identifier\n" + "Separate multiple identifiers with a comma (,)\n"
                    + "(e.g. MediaFilterManager -s \n 123456789/34,123456789/323)");
    Option skipOption = OptionBuilder.create('s');
    skipOption.setArgs(Option.UNLIMITED_VALUES); //unlimited number of args
    options.addOption(skipOption);

    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (MissingArgumentException e) {
        System.out.println("ERROR: " + e.getMessage());
        HelpFormatter myhelp = new HelpFormatter();
        myhelp.printHelp("MediaFilterManager\n", options);
        System.exit(1);
    }

    if (line.hasOption('h')) {
        HelpFormatter myhelp = new HelpFormatter();
        myhelp.printHelp("MediaFilterManager\n", options);

        System.exit(0);
    }

    if (line.hasOption('v')) {
        isVerbose = true;
    }

    isQuiet = line.hasOption('q');

    if (line.hasOption('f')) {
        isForce = true;
    }

    if (line.hasOption('i')) {
        identifier = line.getOptionValue('i');
    }

    if (line.hasOption('m')) {
        max2Process = Integer.parseInt(line.getOptionValue('m'));
        if (max2Process <= 1) {
            System.out.println("Invalid maximum value '" + line.getOptionValue('m') + "' - ignoring");
            max2Process = Integer.MAX_VALUE;
        }
    }

    String filterNames[] = null;
    if (line.hasOption('p')) {
        //specified which media filter plugins we are using
        filterNames = line.getOptionValues('p');

        if (filterNames == null || filterNames.length == 0) { //display error, since no plugins specified
            System.err.println("\nERROR: -p (-plugin) option requires at least one plugin to be specified.\n"
                    + "(e.g. MediaFilterManager -p \"Word Text Extractor\",\"PDF Text Extractor\")\n");
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("MediaFilterManager\n", options);
            System.exit(1);
        }
    } else {
        //retrieve list of all enabled media filter plugins!
        String enabledPlugins = ConfigurationManager.getProperty(MEDIA_FILTER_PLUGINS_KEY);
        filterNames = enabledPlugins.split(",\\s*");
    }

    //initialize an array of our enabled filters
    List<FormatFilter> filterList = new ArrayList<FormatFilter>();

    //set up each filter
    for (int i = 0; i < filterNames.length; i++) {
        //get filter of this name & add to list of filters
        FormatFilter filter = (FormatFilter) PluginManager.getNamedPlugin(FormatFilter.class, filterNames[i]);
        if (filter == null) {
            System.err.println(
                    "\nERROR: Unknown MediaFilter specified (either from command-line or in dspace.cfg): '"
                            + filterNames[i] + "'");
            System.exit(1);
        } else {
            filterList.add(filter);

            String filterClassName = filter.getClass().getName();

            String pluginName = null;
            //If this filter is a SelfNamedPlugin,
            //then the input formats it accepts may differ for
            //each "named" plugin that it defines.
            //So, we have to look for every key that fits the
            //following format: filter.<class-name>.<plugin-name>.inputFormats
            if (SelfNamedPlugin.class.isAssignableFrom(filter.getClass())) {
                //Get the plugin instance name for this class
                pluginName = ((SelfNamedPlugin) filter).getPluginInstanceName();
            }

            //Retrieve our list of supported formats from dspace.cfg
            //For SelfNamedPlugins, format of key is:  
            //  filter.<class-name>.<plugin-name>.inputFormats
            //For other MediaFilters, format of key is: 
            //  filter.<class-name>.inputFormats
            String formats = ConfigurationManager.getProperty(FILTER_PREFIX + "." + filterClassName
                    + (pluginName != null ? "." + pluginName : "") + "." + INPUT_FORMATS_SUFFIX);

            //add to internal map of filters to supported formats   
            if (formats != null) {
                //For SelfNamedPlugins, map key is:  
                //  <class-name><separator><plugin-name>
                //For other MediaFilters, map key is just:
                //  <class-name>
                filterFormats.put(
                        filterClassName + (pluginName != null ? FILTER_PLUGIN_SEPARATOR + pluginName : ""),
                        Arrays.asList(formats.split(",[\\s]*")));
            }
        } //end if filter!=null
    } //end for

    //If verbose, print out loaded mediafilter info
    if (isVerbose) {
        System.out.println("The following MediaFilters are enabled: ");
        Iterator<String> i = filterFormats.keySet().iterator();
        while (i.hasNext()) {
            String filterName = i.next();
            System.out.println("Full Filter Name: " + filterName);
            String pluginName = null;
            if (filterName.contains(FILTER_PLUGIN_SEPARATOR)) {
                String[] fields = filterName.split(FILTER_PLUGIN_SEPARATOR);
                filterName = fields[0];
                pluginName = fields[1];
            }

            System.out.println(filterName + (pluginName != null ? " (Plugin: " + pluginName + ")" : ""));
        }
    }

    //store our filter list into an internal array
    filterClasses = (FormatFilter[]) filterList.toArray(new FormatFilter[filterList.size()]);

    //Retrieve list of identifiers to skip (if any)
    String skipIds[] = null;
    if (line.hasOption('s')) {
        //specified which identifiers to skip when processing
        skipIds = line.getOptionValues('s');

        if (skipIds == null || skipIds.length == 0) { //display error, since no identifiers specified to skip
            System.err.println("\nERROR: -s (-skip) option requires at least one identifier to SKIP.\n"
                    + "Make sure to separate multiple identifiers with a comma!\n"
                    + "(e.g. MediaFilterManager -s 123456789/34,123456789/323)\n");
            HelpFormatter myhelp = new HelpFormatter();
            myhelp.printHelp("MediaFilterManager\n", options);
            System.exit(0);
        }

        //save to a global skip list
        skipList = Arrays.asList(skipIds);
    }

    Context c = null;

    try {
        c = new Context();
        // have to be super-user to do the filtering
        c.turnOffAuthorisationSystem();

        // now apply the filters
        if (identifier == null) {
            applyFiltersAllItems(c);
        } else // restrict application scope to identifier
        {
            DSpaceObject dso = HandleManager.resolveToObject(c, identifier);
            if (dso == null) {
                throw new IllegalArgumentException("Cannot resolve " + identifier + " to a DSpace object");
            }

            switch (dso.getType()) {
            case Constants.COMMUNITY:
                applyFiltersCommunity(c, (Community) dso);
                break;
            case Constants.COLLECTION:
                applyFiltersCollection(c, (Collection) dso);
                break;
            case Constants.ITEM:
                applyFiltersItem(c, (Item) dso);
                break;
            }
        }

        c.complete();
        c = null;
    } catch (Exception e) {
        status = 1;
    } finally {
        if (c != null) {
            c.abort();
        }
    }
    System.exit(status);
}

From source file:org.lib4j.cli.Options.java

public static Options parse(final Cli binding, final Class<?> mainClass, final String[] args) {
    final Set<String> requiredNames = new HashSet<>();
    final Map<String, String> nameToAltName = new HashMap<>();
    final org.apache.commons.cli.Options apacheOptions = new org.apache.commons.cli.Options();
    apacheOptions.addOption(null, "help", false, "Print help and usage.");
    short argumentsMinOccurs = 0;
    short argumentsMaxOccurs = 0;
    final Cli.Arguments cliArguments;
    if (binding != null) {
        cliArguments = binding.getArguments();
        if (cliArguments != null) {
            argumentsMinOccurs = cliArguments.getMinOccurs();
            argumentsMaxOccurs = "unbounded".equals(cliArguments.getMaxOccurs()) ? Short.MAX_VALUE
                    : Short.parseShort(cliArguments.getMaxOccurs());
            if (argumentsMaxOccurs < argumentsMinOccurs) {
                logger.error("minOccurs > maxOccurs on <arguments> element");
                System.exit(1);//from  w  w w .j av a 2 s. com
            }
        }

        if (binding.getOption() != null) {
            for (final Cli.Option option : binding.getOption()) {
                final Cli.Option.Name optionName = option.getName();
                final String longName = optionName.getLong() == null ? null : optionName.getLong();
                final String shortName = optionName.getShort() == null ? null : optionName.getShort();
                final String name = longName != null ? longName : shortName;
                if (longName == null && shortName == null) {
                    logger.error("both [long] and [short] option names are null in cli spec");
                    System.exit(1);
                }

                nameToAltName.put(name, shortName != null ? shortName : longName);
                OptionBuilder.withLongOpt(name == longName ? longName : null);

                // Record which options are required
                if (option.getArgument() != null) {
                    final Cli.Option.Argument argument = option.getArgument();
                    final boolean isRequired = Use.REQUIRED == argument.getUse();
                    if (isRequired) {
                        OptionBuilder.isRequired();
                        requiredNames.add(longName);
                    }

                    final int maxOccurs = argument.getMaxOccurs() == null ? 1
                            : "unbounded".equals(argument.getMaxOccurs()) ? Integer.MAX_VALUE
                                    : Integer.parseInt(argument.getMaxOccurs());
                    if (maxOccurs == 1) {
                        if (isRequired)
                            OptionBuilder.hasArgs(1);
                        else
                            OptionBuilder.hasOptionalArgs(1);
                    } else if (maxOccurs == Integer.MAX_VALUE) {
                        if (isRequired)
                            OptionBuilder.hasArgs();
                        else
                            OptionBuilder.hasOptionalArgs();
                    } else {
                        if (isRequired)
                            OptionBuilder.hasArgs(maxOccurs);
                        else
                            OptionBuilder.hasOptionalArgs(maxOccurs);
                    }

                    final char valueSeparator = argument.getValueSeparator() != null
                            ? argument.getValueSeparator().charAt(0)
                            : ' ';
                    OptionBuilder
                            .withArgName(formatArgumentName(argument.getLabel(), maxOccurs, valueSeparator));
                    OptionBuilder.withValueSeparator(valueSeparator);
                    if (option.getDescription() == null) {
                        logger.error("missing <description> for " + name + " option");
                        System.exit(1);
                    }

                    final StringBuilder description = new StringBuilder(option.getDescription());
                    if (option.getArgument().getDefault() != null)
                        description.append("\nDefault: ").append(option.getArgument().getDefault());

                    OptionBuilder.withDescription(description.toString());
                }

                apacheOptions.addOption(OptionBuilder.create(shortName));
            }
        }
    } else {
        cliArguments = null;
    }

    final Map<String, Option> optionsMap = new HashMap<>();
    final Set<String> specifiedLongNames;
    CommandLine commandLine = null;
    if (args != null && args.length != 0) {
        specifiedLongNames = new HashSet<>();
        final CommandLineParser parser = new PosixParser();
        do {
            try {
                commandLine = parser.parse(apacheOptions, args);
            } catch (final UnrecognizedOptionException e) {
                if (e.getMessage().startsWith("Unrecognized option: ")) {
                    final String unrecognizedOption = e.getMessage().substring(21);
                    logger.error("Unrecognized option: " + unrecognizedOption);
                    for (int i = 0; i < args.length; i++)
                        if (args[i].equals(unrecognizedOption))
                            args[i] = "--help";
                } else {
                    throw new IllegalArgumentException(e);
                }
            } catch (final org.apache.commons.cli.ParseException e) {
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
            }
        } while (commandLine == null);
    } else {
        specifiedLongNames = null;
    }

    final Collection<String> arguments = commandLine != null ? commandLine.getArgList() : null;
    if (arguments != null && arguments.size() > 0) {
        if (argumentsMaxOccurs < arguments.size() || arguments.size() < argumentsMinOccurs) {
            Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
        }
    } else if (argumentsMinOccurs > 0) {
        Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
    }

    if (commandLine != null) {
        for (final org.apache.commons.cli.Option option : commandLine.getOptions()) {
            specifiedLongNames.add(option.getLongOpt());
            if ("help".equals(option.getLongOpt()))
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.out);

            final String optionName = option.getLongOpt() != null ? option.getLongOpt() : option.getOpt();
            optionsMap.put(optionName,
                    option.getValue() != null
                            ? new Option(optionName, option.getValueSeparator(), option.getValues())
                            : new Option(optionName, option.getValueSeparator(), "true"));
        }
    }

    // See if some arguments are missing
    if (requiredNames.size() != 0) {
        if (specifiedLongNames != null)
            requiredNames.removeAll(specifiedLongNames);

        if (requiredNames.size() != 0) {
            final StringBuilder builder = new StringBuilder();
            for (final String longName : requiredNames) {
                final String shortName = nameToAltName.get(longName);
                if (shortName.equals(longName))
                    builder.append("\nMissing argument: -").append(shortName);
                else
                    builder.append("\nMissing argument: -").append(shortName).append(",--").append(longName);
            }

            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
        }
    }

    // Include default values for options that are not specified
    if (binding.getOption() != null) {
        for (final Cli.Option option : binding.getOption()) {
            if (option.getArgument() != null && option.getArgument().getDefault() != null) {
                final String optionName = option.getName().getLong() != null ? option.getName().getLong()
                        : option.getName().getShort();
                if (!optionsMap.containsKey(optionName)) {
                    final String valueSeparator = option.getArgument().getValueSeparator();
                    final String defaultValue = option.getArgument().getDefault();
                    optionsMap.put(optionName,
                            valueSeparator != null
                                    ? new Option(optionName, valueSeparator.charAt(0), defaultValue)
                                    : new Option(optionName, defaultValue));
                }
            }
        }
    }

    // Check pattern for specified and default options
    if (binding.getOption() != null) {
        final StringBuilder builder = new StringBuilder();
        for (final Cli.Option option : binding.getOption()) {
            if (option.getArgument() != null && option.getArgument().getPattern() != null) {
                final String optionName = option.getName().getLong() != null ? option.getName().getLong()
                        : option.getName().getShort();
                final Option opt = optionsMap.get(optionName);
                if (opt != null) {
                    for (final String value : opt.getValues()) {
                        if (!value.matches(option.getArgument().getPattern())) {
                            if (option.getName().getLong() == null || option.getName().getShort() == null)
                                builder.append("\nIncorrect argument form: -").append(optionName);
                            else
                                builder.append("\nIncorrect argument form: -")
                                        .append(option.getName().getShort()).append(",--")
                                        .append(option.getName().getLong());

                            builder.append(' ').append(value).append("\n  Required: ")
                                    .append(option.getArgument().getPattern());
                        }
                    }
                }
            }
        }

        if (builder.length() > 0)
            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
    }

    return new Options(mainClass, args, optionsMap.values(), arguments == null || arguments.size() == 0 ? null
            : arguments.toArray(new String[arguments.size()]));
}

From source file:org.libx4j.cli.Options.java

public static Options parse(final cli_cli binding, final Class<?> mainClass, final String[] args)
        throws OptionsException {
    final Set<String> requiredNames = new HashSet<String>();
    final Map<String, String> nameToAltName = new HashMap<String, String>();
    final org.apache.commons.cli.Options apacheOptions = new org.apache.commons.cli.Options();
    apacheOptions.addOption(null, "help", false, "Print help and usage.");
    int argumentsMinOccurs = 0;
    int argumentsMaxOccurs = 0;
    final cli_cli._arguments cliArguments;
    if (binding != null) {
        cliArguments = binding._arguments(0);
        if (!cliArguments.isNull()) {
            argumentsMinOccurs = cliArguments._minOccurs$().text();
            argumentsMaxOccurs = "unbounded".equals(cliArguments._maxOccurs$().text()) ? Integer.MAX_VALUE
                    : Integer.parseInt(cliArguments._maxOccurs$().text());
            if (argumentsMaxOccurs < argumentsMinOccurs) {
                logger.error("minOccurs > maxOccurs on <arguments> element");
                System.exit(1);//ww  w.j  a v  a  2s  . c o m
            }
        }

        if (binding._option() != null) {
            for (final cli_cli._option option : binding._option()) {
                final cli_cli._option._name optionName = option._name(0);
                final String longName = optionName._long$().isNull() ? null : optionName._long$().text();
                final String shortName = optionName._short$().isNull() ? null : optionName._short$().text();
                final String name = longName != null ? longName : shortName;
                if (longName == null && shortName == null) {
                    logger.error("both [long] and [short] option names are null in cli spec");
                    System.exit(1);
                }

                nameToAltName.put(name, shortName != null ? shortName : longName);
                OptionBuilder.withLongOpt(name == longName ? longName : null);

                // Record which options are required
                if (option._argument() != null && option._argument().size() != 0) {
                    final cli_cli._option._argument argument = option._argument(0);
                    final boolean isRequired = $cli_use.required.text().equals(argument._use$().text());
                    if (isRequired) {
                        OptionBuilder.isRequired();
                        requiredNames.add(longName);
                    }

                    final int maxOccurs = argument._maxOccurs$().isNull() ? 1
                            : "unbounded".equals(argument._maxOccurs$().text()) ? Integer.MAX_VALUE
                                    : Integer.parseInt(argument._maxOccurs$().text());
                    if (maxOccurs == 1) {
                        if (isRequired)
                            OptionBuilder.hasArgs(1);
                        else
                            OptionBuilder.hasOptionalArgs(1);
                    } else if (maxOccurs == Integer.MAX_VALUE) {
                        if (isRequired)
                            OptionBuilder.hasArgs();
                        else
                            OptionBuilder.hasOptionalArgs();
                    } else {
                        if (isRequired)
                            OptionBuilder.hasArgs(maxOccurs);
                        else
                            OptionBuilder.hasOptionalArgs(maxOccurs);
                    }

                    final char valueSeparator = argument._valueSeparator$().text() != null
                            ? argument._valueSeparator$().text().charAt(0)
                            : ' ';
                    OptionBuilder.withArgName(
                            formatArgumentName(argument._label$().text(), maxOccurs, valueSeparator));
                    OptionBuilder.withValueSeparator(valueSeparator);
                    if (option._description(0).isNull()) {
                        logger.error("missing <description> for " + name + " option");
                        System.exit(1);
                    }

                    final StringBuilder description = new StringBuilder(option._description(0).text());
                    if (!option._argument(0)._default$().isNull())
                        description.append("\nDefault: ").append(option._argument(0)._default$().text());

                    OptionBuilder.withDescription(description.toString());
                }

                apacheOptions.addOption(OptionBuilder.create(shortName));
            }
        }
    } else {
        cliArguments = null;
    }

    final Map<String, Option> optionsMap = new HashMap<String, Option>();
    final Set<String> specifiedLongNames;
    CommandLine commandLine = null;
    if (args != null && args.length != 0) {
        specifiedLongNames = new HashSet<String>();
        final CommandLineParser parser = new PosixParser();
        do {
            try {
                commandLine = parser.parse(apacheOptions, args);
            } catch (final UnrecognizedOptionException e) {
                if (e.getMessage().startsWith("Unrecognized option: ")) {
                    final String unrecognizedOption = e.getMessage().substring(21);
                    logger.error("Unrecognized option: " + unrecognizedOption);
                    for (int i = 0; i < args.length; i++)
                        if (args[i].equals(unrecognizedOption))
                            args[i] = "--help";
                } else {
                    throw new OptionsException(e);
                }
            } catch (final org.apache.commons.cli.ParseException e) {
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
            }
        } while (commandLine == null);
    } else {
        specifiedLongNames = null;
    }

    final Collection<String> arguments = commandLine != null ? commandLine.getArgList() : null;
    if (arguments != null && arguments.size() > 0) {
        if (argumentsMaxOccurs < arguments.size() || arguments.size() < argumentsMinOccurs) {
            Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
        }
    } else if (argumentsMinOccurs > 0) {
        Options.trapPrintHelp(apacheOptions, cliArguments, null, System.err);
    }

    if (commandLine != null) {
        for (final org.apache.commons.cli.Option option : commandLine.getOptions()) {
            specifiedLongNames.add(option.getLongOpt());
            if ("help".equals(option.getLongOpt()))
                Options.trapPrintHelp(apacheOptions, cliArguments, null, System.out);

            final String optionName = option.getLongOpt() != null ? option.getLongOpt() : option.getOpt();
            optionsMap.put(optionName,
                    option.getValue() != null
                            ? new Option(optionName, option.getValueSeparator(), option.getValues())
                            : new Option(optionName, option.getValueSeparator(), "true"));
        }
    }

    // See if some arguments are missing
    if (requiredNames.size() != 0) {
        if (specifiedLongNames != null)
            requiredNames.removeAll(specifiedLongNames);

        if (requiredNames.size() != 0) {
            final StringBuilder builder = new StringBuilder();
            for (final String longName : requiredNames) {
                final String shortName = nameToAltName.get(longName);
                if (shortName.equals(longName))
                    builder.append("\nMissing argument: -").append(shortName);
                else
                    builder.append("\nMissing argument: -").append(shortName).append(",--").append(longName);
            }

            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
        }
    }

    // Include default values for options that are not specified
    if (binding._option() != null) {
        for (final cli_cli._option option : binding._option()) {
            if (!option._argument(0)._default$().isNull()) {
                final String optionName = !option._name(0)._long$().isNull() ? option._name(0)._long$().text()
                        : option._name(0)._short$().text();
                if (!optionsMap.containsKey(optionName)) {
                    final String valueSeparator = option._argument(0)._valueSeparator$().text();
                    final String defaultValue = option._argument(0)._default$().text();
                    optionsMap.put(optionName,
                            valueSeparator != null
                                    ? new Option(optionName, valueSeparator.charAt(0), defaultValue)
                                    : new Option(optionName, defaultValue));
                }
            }
        }
    }

    // Check pattern for specified and default options
    if (binding._option() != null) {
        final StringBuilder builder = new StringBuilder();
        for (final cli_cli._option option : binding._option()) {
            if (!option._argument(0)._pattern$().isNull()) {
                final String optionName = !option._name(0)._long$().isNull() ? option._name(0)._long$().text()
                        : option._name(0)._short$().text();
                final Option opt = optionsMap.get(optionName);
                if (opt != null) {
                    for (final String value : opt.getValues()) {
                        if (!value.matches(option._argument(0)._pattern$().text())) {
                            if (option._name(0)._long$().isNull() || option._name(0)._short$().isNull())
                                builder.append("\nIncorrect argument form: -").append(optionName);
                            else
                                builder.append("\nIncorrect argument form: -")
                                        .append(option._name(0)._short$().text()).append(",--")
                                        .append(option._name(0)._long$().text());

                            builder.append(" ").append(value).append("\n  Required: ")
                                    .append(option._argument(0)._pattern$().text());
                        }
                    }
                }
            }
        }

        if (builder.length() > 0)
            Options.trapPrintHelp(apacheOptions, cliArguments, builder.substring(1), System.out);
    }

    return new Options(mainClass, args, optionsMap.values(), arguments == null || arguments.size() == 0 ? null
            : arguments.toArray(new String[arguments.size()]));
}

From source file:org.neovera.jdiablo.internal.OptionAnnotatedProperty.java

@SuppressWarnings("static-access")
public org.apache.commons.cli.Option getCliOption() {
    if (_cliOption != null) {
        return _cliOption;
    } else {/*from  w  w w . ja  v  a  2  s.  co m*/
        Option option = getOption();
        OptionBuilder builder = OptionBuilder.withDescription(option.description());
        if (StringUtils.isNotBlank(option.argName())) {
            builder = builder.withArgName(option.argName());
        }
        if (option.args() != 0) {
            builder = builder.hasArgs(option.args());
        }
        if (option.hasArgs()) {
            builder = builder.hasArgs();
        }
        if (StringUtils.isNotBlank(option.longOption())) {
            builder = builder.withLongOpt(option.longOption());
        }
        if (option.optionalArgs() != 0) {
            builder = builder.hasOptionalArgs(option.optionalArgs());
        }
        if (option.required() && !getOptionProperty().isOptionNotRequiredOverride()) {
            builder = builder.isRequired();
        }
        if (option.valueSeparator() != ' ') {
            builder = builder.withValueSeparator(option.valueSeparator());
        }

        setCliOption(builder.create(option.shortOption()));
        return getCliOption();
    }
}

From source file:org.nuunframework.cli.NuunCliPlugin.java

private Option createOptionFromField(Field field) {
    Option option = null;//w w w.j ava 2  s  . c om
    // Cli Option Builder is completly static :-/
    // so we synchronized it ...
    synchronized (OptionBuilder.class) {
        // reset the builder creating a dummy option
        OptionBuilder.withLongOpt("dummy");
        OptionBuilder.create();

        // 
        NuunOption nuunOption = field.getAnnotation(NuunOption.class);

        if (nuunOption == null) {
            for (Annotation anno : field.getAnnotations()) {
                if (AssertUtils.hasAnnotationDeep(anno.annotationType(), NuunOption.class)) {
                    nuunOption = AssertUtils.annotationProxyOf(NuunOption.class, anno);
                    break;
                }
            }
        }

        // longopt
        if (!Strings.isNullOrEmpty(nuunOption.longOpt())) {
            OptionBuilder.withLongOpt(nuunOption.longOpt());
        }
        // description
        if (!Strings.isNullOrEmpty(nuunOption.description())) {
            OptionBuilder.withDescription(nuunOption.description());
        }
        // required
        OptionBuilder.isRequired((nuunOption.required()));

        // arg
        OptionBuilder.hasArg((nuunOption.arg()));

        // args
        if (nuunOption.args()) {
            if (nuunOption.numArgs() > 0) {
                OptionBuilder.hasArgs(nuunOption.numArgs());
            } else {
                OptionBuilder.hasArgs();
            }
        }
        // is optional 
        if (nuunOption.optionalArg()) {
            OptionBuilder.hasOptionalArg();
        }

        // nuun 
        OptionBuilder.withValueSeparator(nuunOption.valueSeparator());

        // opt 
        if (!Strings.isNullOrEmpty(nuunOption.opt())) {
            option = OptionBuilder.create(nuunOption.opt());
        } else {
            option = OptionBuilder.create();
        }
    }

    return option;

}

From source file:org.openscience.jmol.app.Jmol.java

public static void main(String[] args) {

    Dialog.setupUIManager();/*  w  w  w.j av a  2  s.  c o m*/

    Jmol jmol = null;

    String modelFilename = null;
    String scriptFilename = null;

    Options options = new Options();
    options.addOption("b", "backgroundtransparent", false, GT._("transparent background"));
    options.addOption("h", "help", false, GT._("give this help page"));
    options.addOption("n", "nodisplay", false, GT._("no display (and also exit when done)"));
    options.addOption("c", "check", false, GT._("check script syntax only"));
    options.addOption("i", "silent", false, GT._("silent startup operation"));
    options.addOption("l", "list", false, GT._("list commands during script execution"));
    options.addOption("o", "noconsole", false, GT._("no console -- all output to sysout"));
    options.addOption("t", "threaded", false, GT._("independent commmand thread"));
    options.addOption("x", "exit", false, GT._("exit after script (implicit with -n)"));

    OptionBuilder.withLongOpt("script");
    OptionBuilder.withDescription("script file to execute");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("s"));

    OptionBuilder.withLongOpt("menu");
    OptionBuilder.withDescription("menu file to use");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("m"));

    OptionBuilder.withArgName(GT._("property=value"));
    OptionBuilder.hasArg();
    OptionBuilder.withValueSeparator();
    OptionBuilder.withDescription(GT._("supported options are given below"));
    options.addOption(OptionBuilder.create("D"));

    OptionBuilder.withLongOpt("geometry");
    // OptionBuilder.withDescription(GT._("overall window width x height, e.g. {0}", "-g512x616"));
    OptionBuilder.withDescription(GT._("window width x height, e.g. {0}", "-g500x500"));
    OptionBuilder.withValueSeparator();
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("g"));

    OptionBuilder.withLongOpt("quality");
    // OptionBuilder.withDescription(GT._("overall window width x height, e.g. {0}", "-g512x616"));
    OptionBuilder.withDescription(GT._(
            "JPG image quality (1-100; default 75) or PNG image compression (0-9; default 2, maximum compression 9)"));
    OptionBuilder.withValueSeparator();
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("q"));

    OptionBuilder.withLongOpt("write");
    OptionBuilder
            .withDescription(GT._("{0} or {1}:filename", new Object[] { "CLIP", "GIF|JPG|JPG64|PNG|PPM" }));
    OptionBuilder.withValueSeparator();
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("w"));

    int startupWidth = 0, startupHeight = 0;

    CommandLine line = null;
    try {
        CommandLineParser parser = new PosixParser();
        line = parser.parse(options, args);
    } catch (ParseException exception) {
        System.err.println("Unexpected exception: " + exception.toString());
    }

    if (line.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jmol", options);

        // now report on the -D options
        System.out.println();
        System.out.println(GT._("For example:"));
        System.out.println();
        System.out.println("Jmol -ions myscript.spt -w JPEG:myfile.jpg > output.txt");
        System.out.println();
        System.out.println(GT._("The -D options are as follows (defaults in parenthesis):"));
        System.out.println();
        System.out.println("  cdk.debugging=[true|false] (false)");
        System.out.println("  cdk.debug.stdout=[true|false] (false)");
        System.out.println("  display.speed=[fps|ms] (ms)");
        System.out.println("  JmolConsole=[true|false] (true)");
        System.out.println("  jmol.logger.debug=[true|false] (false)");
        System.out.println("  jmol.logger.error=[true|false] (true)");
        System.out.println("  jmol.logger.fatal=[true|false] (true)");
        System.out.println("  jmol.logger.info=[true|false] (true)");
        System.out.println("  jmol.logger.logLevel=[true|false] (false)");
        System.out.println("  jmol.logger.warn=[true|false] (true)");
        System.out.println("  plugin.dir (unset)");
        System.out.println("  user.language=[CA|CS|DE|EN|ES|FR|NL|PT|TR] (EN)");

        System.exit(0);
    }

    args = line.getArgs();
    if (args.length > 0) {
        modelFilename = args[0];
    }

    // Process more command line arguments
    // these are also passed to viewer

    String commandOptions = "";

    //silent startup
    if (line.hasOption("i")) {
        commandOptions += "-i";
        isSilent = Boolean.TRUE;
    }

    // transparent background
    if (line.hasOption("b")) {
        commandOptions += "-b";
    }

    // independent command thread
    if (line.hasOption("t")) {
        commandOptions += "-t";
    }

    //list commands during script operation
    if (line.hasOption("l")) {
        commandOptions += "-l";
    }

    //output to sysout
    if (line.hasOption("o")) {
        commandOptions += "-o";
        haveConsole = Boolean.FALSE;
    }

    //no display (and exit)
    if (line.hasOption("n")) {
        // this ensures that noDisplay also exits
        commandOptions += "-n-x";
        haveDisplay = Boolean.FALSE;
    }

    //check script only
    if (line.hasOption("c")) {
        commandOptions += "-c";
    }

    //run script
    if (line.hasOption("s")) {
        commandOptions += "-s";
        scriptFilename = line.getOptionValue("s");
    }

    //menu file
    if (line.hasOption("m")) {
        menuFile = line.getOptionValue("m");
    }

    //exit when script completes (or file is read)
    if (line.hasOption("x")) {
        commandOptions += "-x";
    }
    String imageType_name = null;
    //write image to clipboard or image file  
    if (line.hasOption("w")) {
        imageType_name = line.getOptionValue("w");
    }

    Dimension size;
    try {
        String vers = System.getProperty("java.version");
        if (vers.compareTo("1.1.2") < 0) {
            System.out.println("!!!WARNING: Swing components require a " + "1.1.2 or higher version VM!!!");
        }

        size = historyFile.getWindowSize(JMOL_WINDOW_NAME);
        if (size != null && haveDisplay.booleanValue()) {
            startupWidth = size.width;
            startupHeight = size.height;
        }

        //OUTER window dimensions
        /*
         if (line.hasOption("g") && haveDisplay.booleanValue()) {
         String geometry = line.getOptionValue("g");
         int indexX = geometry.indexOf('x');
         if (indexX > 0) {
         startupWidth = parseInt(geometry.substring(0, indexX));
         startupHeight = parseInt(geometry.substring(indexX + 1));
         }
         }
         */

        Point b = historyFile.getWindowBorder(JMOL_WINDOW_NAME);
        //first one is just approximate, but this is set in doClose()
        //so it will reset properly -- still, not perfect
        //since it is always one step behind.
        if (b == null)
            border = new Point(12, 116);
        else
            border = new Point(b.x, b.y);
        //note -- the first time this is run after changes it will not work
        //because there is a bootstrap problem.

        int width = -1;
        int height = -1;
        int quality = 75;
        //INNER frame dimensions
        if (line.hasOption("g")) {
            String geometry = line.getOptionValue("g");
            int indexX = geometry.indexOf('x');
            if (indexX > 0) {
                width = Parser.parseInt(geometry.substring(0, indexX));
                height = Parser.parseInt(geometry.substring(indexX + 1));
                //System.out.println("setting geometry to " + geometry + " " + border + " " + startupWidth + startupHeight);
            }
            if (haveDisplay.booleanValue()) {
                startupWidth = width + border.x;
                startupHeight = height + border.y;
            }
        }

        if (line.hasOption("q"))
            quality = Parser.parseInt(line.getOptionValue("q"));

        if (imageType_name != null)
            commandOptions += "-w\1" + imageType_name + "\t" + width + "\t" + height + "\t" + quality + "\1";

        if (startupWidth <= 0 || startupHeight <= 0) {
            startupWidth = 500 + border.x;
            startupHeight = 500 + border.y;
        }
        JFrame jmolFrame = new JFrame();
        Point jmolPosition = historyFile.getWindowPosition(JMOL_WINDOW_NAME);
        if (jmolPosition != null) {
            jmolFrame.setLocation(jmolPosition);
        }

        //now pass these to viewer
        jmol = getJmol(jmolFrame, startupWidth, startupHeight, commandOptions);

        // Open a file if one is given as an argument -- note, this CAN be a script file
        if (modelFilename != null) {
            jmol.viewer.openFile(modelFilename);
            jmol.viewer.getOpenFileError();
        }

        // OK, by now it is time to execute the script
        if (scriptFilename != null) {
            report("Executing script: " + scriptFilename);
            if (haveDisplay.booleanValue())
                jmol.splash.showStatus(GT._("Executing script..."));
            jmol.viewer.evalFile(scriptFilename);
        }
    } catch (Throwable t) {
        System.out.println("uncaught exception: " + t);
        t.printStackTrace();
    }

    if (haveConsole.booleanValue()) {
        Point location = jmol.frame.getLocation();
        size = jmol.frame.getSize();
        // Adding console frame to grab System.out & System.err
        consoleframe = new JFrame(GT._("Jmol Java Console"));
        consoleframe.setIconImage(jmol.frame.getIconImage());
        try {
            final ConsoleTextArea consoleTextArea = new ConsoleTextArea();
            consoleTextArea.setFont(java.awt.Font.decode("monospaced"));
            consoleframe.getContentPane().add(new JScrollPane(consoleTextArea), java.awt.BorderLayout.CENTER);
            if (Boolean.getBoolean("clearConsoleButton")) {
                JButton buttonClear = new JButton(GT._("Clear"));
                buttonClear.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        consoleTextArea.setText("");
                    }
                });
                consoleframe.getContentPane().add(buttonClear, java.awt.BorderLayout.SOUTH);
            }
        } catch (IOException e) {
            JTextArea errorTextArea = new JTextArea();
            errorTextArea.setFont(java.awt.Font.decode("monospaced"));
            consoleframe.getContentPane().add(new JScrollPane(errorTextArea), java.awt.BorderLayout.CENTER);
            errorTextArea.append(GT._("Could not create ConsoleTextArea: ") + e);
        }

        Dimension consoleSize = historyFile.getWindowSize(CONSOLE_WINDOW_NAME);
        Point consolePosition = historyFile.getWindowPosition(CONSOLE_WINDOW_NAME);
        if ((consoleSize != null) && (consolePosition != null)) {
            consoleframe.setBounds(consolePosition.x, consolePosition.y, consoleSize.width, consoleSize.height);
        } else {
            consoleframe.setBounds(location.x, location.y + size.height, size.width, 200);
        }

        Boolean consoleVisible = historyFile.getWindowVisibility(CONSOLE_WINDOW_NAME);
        if ((consoleVisible != null) && (consoleVisible.equals(Boolean.TRUE))) {
            consoleframe.show();
        }
    }
}

From source file:org.openscience.jvxl.Jvxl.java

public static void main(String[] args) {

    boolean blockData = false;
    int fileIndex = Integer.MAX_VALUE;
    String inputFile = null;//  w  w w.  ja  va 2s  . com
    String mapFile = null;
    String outputFile = null;

    float cutoff = Float.NaN;
    boolean isPositiveOnly = false;

    P4 plane = null;

    boolean bicolor = false;
    boolean reverseColor = false;
    float min = Float.NaN;
    float max = Float.NaN;

    Options options = new Options();
    options.addOption("h", "help", false, "give this help page");

    /*
     *  examples: 
     *  
     *  jvxl ch3cl-density.cub --min=0.0 --max=0.2 --map ch3cl-esp.cub
     *  jvxl ethene-HOMO.cub --bicolor --output ethene.jvxl
     *  jvxl d_orbitals.jvxl --index 2 --phase yz
     *  jvxl d_orbitals.jvxl --map sets
     *  jvxl --plane xy  --min=0.0 --max=0.2 --map data/ch3cl-density.cub 
     */

    // file options
    options.addOption("B", "blockdata", false, "multiple cube data are in blocks, not interspersed");

    options.addOption("P", "progressive", false, "create JVXL+ progressive X low-to-high format");

    OptionBuilder.withLongOpt("file");
    OptionBuilder.withDescription("file containing surface data");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("f"));

    OptionBuilder.withLongOpt("index");
    OptionBuilder.withDescription("index of surface in file (starting with 1)");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("i"));

    OptionBuilder.withLongOpt("plane");
    OptionBuilder.withDescription("plane: x, y, z, xy, xz, yz, z2, x2-y2, or {a,b,c,d}");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("p"));

    OptionBuilder.withLongOpt("map");
    OptionBuilder.withDescription("file containing data to map onto the surface or \"sets\"");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("m"));

    OptionBuilder.withLongOpt("output");
    OptionBuilder.withDescription("JVXL output file");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("o"));

    // surface options

    OptionBuilder.withLongOpt("cutoff");
    OptionBuilder.withDescription("isosurface cutoff value");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("c"));

    // color mapping options

    options.addOption("b", "bicolor", false, "bicolor map (orbital)");
    options.addOption("r", "reversecolor", false, "reverse color");

    OptionBuilder.withLongOpt("colorScheme");
    OptionBuilder.withDescription("VRML color scheme: bw, wb, roygb, bgyor, rwb, bwr, low, high");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("s"));

    OptionBuilder.withLongOpt("phase");
    OptionBuilder.withDescription("color by phase: x, y, z, xy, xz, yz, z2, x2-y2");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("F"));

    OptionBuilder.withLongOpt("min");
    OptionBuilder.withDescription("color absolute minimum value");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("n"));

    OptionBuilder.withLongOpt("max");
    OptionBuilder.withDescription("color absolute maximum value");
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create("x"));

    CommandLine line = null;
    try {
        CommandLineParser parser = new PosixParser();
        line = parser.parse(options, args);
    } catch (ParseException exception) {
        Logger.error("Unexpected exception: " + exception.toString());
    }

    if (line.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jvxl", options);
        return;
    }

    args = line.getArgs();
    if (args.length > 0) {
        inputFile = args[0];
    }

    // files 

    blockData = (line.hasOption("B"));

    if (line.hasOption("i")) {
        fileIndex = PT.parseInt(line.getOptionValue("i"));
    }

    if (line.hasOption("f")) {
        inputFile = line.getOptionValue("f");
    }

    if (line.hasOption("m")) {
        mapFile = line.getOptionValue("m");
    }

    if (line.hasOption("p")) {
        plane = getPlane(line.getOptionValue("p"));
        if (plane == null) {
            Logger.error("invalid plane");
            return;
        }
        Logger.info("using plane " + plane);
        if (mapFile == null)
            mapFile = inputFile;
        if (inputFile == null)
            inputFile = mapFile;
    }

    if (line.hasOption("o")) {
        outputFile = line.getOptionValue("o");
    } else {
        outputFile = inputFile;
        if (outputFile.indexOf(".") < 0)
            outputFile += ".";
        String sIndex = (fileIndex == Integer.MAX_VALUE ? "" : "_" + fileIndex);
        if (sIndex.length() == 0 && outputFile.indexOf(".jvxl") >= 0)
            sIndex += "_new";
        outputFile = outputFile.substring(0, outputFile.lastIndexOf(".")) + sIndex + ".jvxl";
    }

    // Process more command line arguments
    // these are also passed to vwr

    bicolor = (line.hasOption("b"));
    reverseColor = (line.hasOption("r"));

    if (bicolor && mapFile != null) {
        Logger.warn("--map option ignored; incompatible with --bicolor");
        mapFile = null;
    }

    if (line.hasOption("c")) {
        String s = line.getOptionValue("c");
        if (s.indexOf("+") == 0) {
            isPositiveOnly = true;
            s = s.substring(1);
        }
        cutoff = PT.parseFloat(s);
    }

    if (line.hasOption("n")) {
        if (bicolor)
            Logger.warn("--min option ignored; incompatible with --bicolor");
        else
            min = PT.parseFloat(line.getOptionValue("n"));
    }

    if (line.hasOption("x")) {
        if (bicolor)
            Logger.warn("--max option ignored; incompatible with --bicolor");
        else
            max = PT.parseFloat(line.getOptionValue("x"));
    }

    //    if (line.hasOption("P")) {
    //      phase = line.getOptionValue("P");
    //    }

    boolean progressive = line.hasOption("P");

    // compose the surface

    SurfaceGenerator sg = new SurfaceGenerator(null, null, null, null);

    // input file

    sg.version = VERSION;
    if (blockData)
        sg.setProp("blockData", Boolean.TRUE, null);
    if (!Float.isNaN(cutoff))
        sg.setProp(isPositiveOnly ? "cutoffPositive" : "cutoff", Float.valueOf(cutoff), null);
    if (bicolor)
        sg.setProp("sign", null, null);
    if (reverseColor)
        sg.setProp("reverseColor", null, null);
    //if (phase != null)
    //sg.setProp("phase", phase);

    if (progressive)
        sg.setProp("progressive", null, null);

    if (plane != null)
        sg.setProp("plane", plane, null);
    else {
        if (fileIndex != Integer.MAX_VALUE)
            sg.setProp("fileIndex", Integer.valueOf(fileIndex), null);
        Object t = FileReader.getBufferedReaderOrErrorMessageFromName(inputFile);
        if (t instanceof String) {
            Logger.error((String) t);
            return;
        }
        BufferedReader br = (BufferedReader) t;
        sg.setProp("readFile", br, null);
        try {
            br.close();
        } catch (Exception e) {
            //
        }
    }

    sg.setProp("title", line.toString(), null);

    //color scheme is only for VMRL

    //if (colorScheme != null) {
    // ColorEncoder ce = new ColorEncoder(null);
    // ce.setColorScheme(colorScheme, false);
    // sg.setProp("colorScheme", ce);
    // }
    if (!Float.isNaN(min))
        sg.setProp("red", Float.valueOf(min), null);
    if (!Float.isNaN(max))
        sg.setProp("blue", Float.valueOf(max), null);
    if (mapFile != null) {
        Object t = FileReader.getBufferedReaderOrErrorMessageFromName(mapFile);
        if (t instanceof String) {
            Logger.error((String) t);
            return;
        }
        BufferedReader br2 = (BufferedReader) t;
        sg.setProp("mapColor", br2, null);
        try {
            br2.close();
        } catch (Exception e) {
            //
        }
    }

    writeFile(outputFile, (String) sg.getProperty("jvxlFileData", 0));
    Logger.info((String) sg.getProperty("jvxlFileInfo", 0));
    Logger.info("\ncreated " + outputFile);
}

From source file:org.psystems.dicomweb.Dcm2DcmCopy.java

private static CommandLine parse(String[] args) {
    Options opts = new Options();

    opts.addOption(null, "no-fmi", false, "Encode result without File Meta Information. At default, "
            + " File Meta Information is included.");
    opts.addOption("e", "explicit", false, "Encode result with Explicit VR Little Endian Transfer Syntax. "
            + "At default, Implicit VR Little Endian is used.");
    opts.addOption("b", "big-endian", false, "Encode result with Explicit VR Big Endian Transfer Syntax. "
            + "At default, Implicit VR Little Endian is used.");
    opts.addOption("z", "deflated", false, "Encode result with Deflated Explicit VR Little Endian Syntax. "
            + "At default, Implicit VR Little Endian is used.");

    OptionBuilder.withArgName("[seq/]attr=value");
    OptionBuilder.hasArgs(2);//  www  .  ja va  2s.  c  o m
    OptionBuilder.withValueSeparator('=');
    OptionBuilder.withDescription(
            "specify value to set in the output stream.  Currently only works when transcoding images.");
    opts.addOption(OptionBuilder.create("s"));

    opts.addOption("t", "syntax", true,
            "Encode result with the specified transfer syntax - recodes" + " the image typically.");

    OptionBuilder.withArgName("KB");
    OptionBuilder.hasArg();
    OptionBuilder.withDescription("transcoder buffer size in KB, 1KB by default");
    OptionBuilder.withLongOpt("buffer");
    opts.addOption(OptionBuilder.create(null));

    opts.addOption("h", "help", false, "print this message");
    opts.addOption("V", "version", false, "print the version information and exit");
    CommandLine cl = null;
    try {
        cl = new PosixParser().parse(opts, args);
    } catch (ParseException e) {
        exit("dcm2dcm: " + e.getMessage());
        throw new RuntimeException("unreachable");
    }
    if (cl.hasOption('V')) {
        Package p = Dcm2DcmCopy.class.getPackage();
        System.out.println("dcm2dcm v" + p.getImplementationVersion());
        System.exit(0);
    }
    if (cl.hasOption('h') || cl.getArgList().size() < 2) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
        System.exit(0);
    }
    return cl;
}