Example usage for org.apache.commons.cli CommandLine getOptions

List of usage examples for org.apache.commons.cli CommandLine getOptions

Introduction

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

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:org.archive.io.warc.WARCReader.java

/**
 * Command-line interface to WARCReader.
 *
 * Here is the command-line interface://  w ww. j  a  va2s .c o m
 * <pre>
 * usage: java org.archive.io.arc.WARCReader [--offset=#] ARCFILE
 *  -h,--help      Prints this message and exits.
 *  -o,--offset    Outputs record at this offset into arc file.</pre>
 *
 * <p>Outputs using a pseudo-CDX format as described here:
 * <a href="http://www.archive.org/web/researcher/cdx_legend.php">CDX
 * Legent</a> and here
 * <a href="http://www.archive.org/web/researcher/example_cdx.php">Example</a>.
 * Legend used in below is: 'CDX b e a m s c V (or v if uncompressed) n g'.
 * Hash is hard-coded straight SHA-1 hash of content.
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = getOptions();
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    @SuppressWarnings("unchecked")
    List<String> cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() <= 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    long offset = -1;
    boolean digest = false;
    boolean strict = false;
    String format = CDX;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'o':
            offset = Long.parseLong(cmdlineOptions[i].getValue());
            break;

        case 's':
            strict = true;
            break;

        case 'd':
            digest = getTrueOrFalse(cmdlineOptions[i].getValue());
            break;

        case 'f':
            format = cmdlineOptions[i].getValue().toLowerCase();
            boolean match = false;
            // List of supported formats.
            final String[] supportedFormats = { CDX, DUMP, GZIP_DUMP, CDX_FILE };
            for (int ii = 0; ii < supportedFormats.length; ii++) {
                if (supportedFormats[ii].equals(format)) {
                    match = true;
                    break;
                }
            }
            if (!match) {
                usage(formatter, options, 1);
            }
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    if (offset >= 0) {
        if (cmdlineArgs.size() != 1) {
            System.out.println("Error: Pass one arcfile only.");
            usage(formatter, options, 1);
        }
        WARCReader r = WARCReaderFactory.get(new File((String) cmdlineArgs.get(0)), offset);
        r.setStrict(strict);
        outputRecord(r, format);
    } else {
        for (Iterator<String> i = cmdlineArgs.iterator(); i.hasNext();) {
            String urlOrPath = (String) i.next();
            try {
                WARCReader r = WARCReaderFactory.get(urlOrPath);
                r.setStrict(strict);
                r.setDigest(digest);
                output(r, format);
            } catch (RuntimeException e) {
                // Write out name of file we failed on to help with
                // debugging.  Then print stack trace and try to keep
                // going.  We do this for case where we're being fed
                // a bunch of ARCs; just note the bad one and move
                // on to the next.
                System.err.println("Exception processing " + urlOrPath + ": " + e.getMessage());
                e.printStackTrace(System.err);
                System.exit(1);
            }
        }
    }
}

From source file:org.archive.io.Warc2Arc.java

/**
 * Command-line interface to Arc2Warc./*from   w w w . j a va 2s. c om*/
 *
 * @param args Command-line arguments.
 * @throws ParseException Failed parse of the command line.
 * @throws IOException
 * @throws java.text.ParseException
 */
public static void main(String[] args) throws ParseException, IOException, java.text.ParseException {
    Options options = new Options();
    options.addOption(new Option("h", "help", false, "Prints this message and exits."));
    options.addOption(new Option("f", "force", false, "Force overwrite of target file."));
    options.addOption(
            new Option("p", "prefix", true, "Prefix to use on created ARC files, else uses default."));
    options.addOption(
            new Option("s", "suffix", true, "Suffix to use on created ARC files, else uses default."));
    PosixParser parser = new PosixParser();
    CommandLine cmdline = parser.parse(options, args, false);
    @SuppressWarnings("unchecked")
    List<String> cmdlineArgs = cmdline.getArgList();
    Option[] cmdlineOptions = cmdline.getOptions();
    HelpFormatter formatter = new HelpFormatter();

    // If no args, print help.
    if (cmdlineArgs.size() < 0) {
        usage(formatter, options, 0);
    }

    // Now look at options passed.
    boolean force = false;
    String prefix = "WARC2ARC";
    String suffix = null;
    for (int i = 0; i < cmdlineOptions.length; i++) {
        switch (cmdlineOptions[i].getId()) {
        case 'h':
            usage(formatter, options, 0);
            break;

        case 'f':
            force = true;
            break;

        case 'p':
            prefix = cmdlineOptions[i].getValue();
            break;

        case 's':
            suffix = cmdlineOptions[i].getValue();
            break;

        default:
            throw new RuntimeException("Unexpected option: " + +cmdlineOptions[i].getId());
        }
    }

    // If no args, print help.
    if (cmdlineArgs.size() != 2) {
        usage(formatter, options, 0);
    }
    (new Warc2Arc()).transform(new File(cmdlineArgs.get(0).toString()), new File(cmdlineArgs.get(1).toString()),
            prefix, suffix, force);
}

From source file:org.cc.smali.main.java

/**
 * Run!//from  w  w w. jav  a2 s  .com
 */
public static void main(String[] args) {
    Locale locale = new Locale("en", "US");
    Locale.setDefault(locale);

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    int jobs = -1;
    boolean allowOdex = false;
    boolean verboseErrors = false;
    boolean printTokens = false;
    boolean experimental = false;

    int apiLevel = 15;

    String outputDexFile = "out.dex";

    String[] remainingArgs = commandLine.getArgs();

    Option[] options = commandLine.getOptions();

    for (int i = 0; i < options.length; i++) {
        Option option = options[i];
        String opt = option.getOpt();

        switch (opt.charAt(0)) {
        case 'v':
            version();
            return;
        case '?':
            while (++i < options.length) {
                if (options[i].getOpt().charAt(0) == '?') {
                    usage(true);
                    return;
                }
            }
            usage(false);
            return;
        case 'o':
            outputDexFile = commandLine.getOptionValue("o");
            break;
        case 'x':
            allowOdex = true;
            break;
        case 'X':
            experimental = true;
            break;
        case 'a':
            apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
            break;
        case 'j':
            jobs = Integer.parseInt(commandLine.getOptionValue("j"));
            break;
        case 'V':
            verboseErrors = true;
            break;
        case 'T':
            printTokens = true;
            break;
        default:
            assert false;
        }
    }

    if (remainingArgs.length == 0) {
        usage();
        return;
    }

    try {
        LinkedHashSet<File> filesToProcess = new LinkedHashSet<File>();

        for (String arg : remainingArgs) {
            File argFile = new File(arg);

            if (!argFile.exists()) {
                throw new RuntimeException("Cannot find file or directory \"" + arg + "\"");
            }

            if (argFile.isDirectory()) {
                getSmaliFilesInDir(argFile, filesToProcess);
            } else if (argFile.isFile()) {
                filesToProcess.add(argFile);
            }
        }

        if (jobs <= 0) {
            jobs = Runtime.getRuntime().availableProcessors();
            if (jobs > 6) {
                jobs = 6;
            }
        }

        boolean errors = false;

        final DexBuilder dexBuilder = DexBuilder.makeDexBuilder(apiLevel);
        ExecutorService executor = Executors.newFixedThreadPool(jobs);
        List<Future<Boolean>> tasks = Lists.newArrayList();

        final boolean finalVerboseErrors = verboseErrors;
        final boolean finalPrintTokens = printTokens;
        final boolean finalAllowOdex = allowOdex;
        final int finalApiLevel = apiLevel;
        final boolean finalExperimental = experimental;
        for (final File file : filesToProcess) {
            tasks.add(executor.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return assembleSmaliFile(file, dexBuilder, finalVerboseErrors, finalPrintTokens,
                            finalAllowOdex, finalApiLevel, finalExperimental);
                }
            }));
        }

        for (Future<Boolean> task : tasks) {
            while (true) {
                try {
                    if (!task.get()) {
                        errors = true;
                    }
                } catch (InterruptedException ex) {
                    continue;
                }
                break;
            }
        }

        executor.shutdown();

        if (errors) {
            System.exit(1);
        }

        dexBuilder.writeTo(new FileDataStore(new File(outputDexFile)));
    } catch (RuntimeException ex) {
        System.err.println("\nUNEXPECTED TOP-LEVEL EXCEPTION:");
        ex.printStackTrace();
        System.exit(2);
    } catch (Throwable ex) {
        System.err.println("\nUNEXPECTED TOP-LEVEL ERROR:");
        ex.printStackTrace();
        System.exit(3);
    }
}

From source file:org.Cherry.Main.Application.java

void process() {
    final Option httpPortOption = OptionBuilder.withArgName(CmdLineArg.httpPort.name()).hasArg()
            .withDescription("port to listen on [8080]").create(CmdLineArg.httpPort.name()),
            configFileOption = OptionBuilder.withArgName(CmdLineArg.configFile.name()).hasArg()
                    .withDescription("configuration file to use").create(CmdLineArg.configFile.name()),
            controllerNamespaces = OptionBuilder.withArgName(CmdLineArg.controllerNamespaces.name()).hasArg()
                    .withDescription("Controller namespace declarations")
                    .create(CmdLineArg.controllerNamespaces.name());

    final Options options = new Options();

    options.addOption(configFileOption);
    options.addOption(httpPortOption);//www  . ja  v  a  2  s  .co  m
    options.addOption(controllerNamespaces);

    final CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, INSTANCE_ARGUMENTS);
    } catch (final ParseException e) {
        error(e, "");

        throw new IllegalArgumentException(e);
    }

    final Option[] processedOptions = commandLine.getOptions();

    if (null != processedOptions && 0 < processedOptions.length) {

        final Map<CmdLineArg, Object> optionMap = new HashMap<CmdLineArg, Object>(processedOptions.length);

        CmdLineArg cmdLineArg;
        Boolean configFileDeclared = false;

        for (final Option option : processedOptions) {
            cmdLineArg = CmdLineArg.valueOf(option.getArgName());

            switch (cmdLineArg) {
            case configFile:
                if (configFileDeclared)
                    throw new IllegalArgumentException(
                            "Duplicated declaration for argument [" + cmdLineArg + "]");
                optionMap.put(cmdLineArg, option.getValue());
                configFileDeclared = true;
                break;

            case httpPort:
                if (configFileDeclared) {
                    warn("{}", "Configuration file foumd, all other options - including [" + cmdLineArg
                            + "] will be ignored!");
                    continue;
                }
                if (optionMap.containsKey(cmdLineArg))
                    throw new IllegalArgumentException(
                            "Duplicated declaration for argument [" + cmdLineArg + "]");
                optionMap.put(cmdLineArg, option.getValue());
                break;

            case controllerNamespaces:
                if (configFileDeclared) {
                    warn("{}", "Configuration file foumd, all other options - including [" + cmdLineArg
                            + "] will be ignored!");
                    continue;
                }
                if (optionMap.containsKey(cmdLineArg))
                    throw new IllegalArgumentException(
                            "Duplicated declaration for argument [" + cmdLineArg + "]");
                optionMap.put(cmdLineArg, option.getValue());
                break;

            default:
                warn("Will ignore [{}]=[{}]", cmdLineArg, option.getValue());
            }
        }

        final File cfgFile = new File((String) optionMap.get(CmdLineArg.configFile));

        if (!cfgFile.exists() || cfgFile.isDirectory())
            throw new IllegalArgumentException(
                    "Missing configuration file [" + cfgFile.getPath() + "] or it is a directory!");

        FileInputStream fis = null;
        Configuration configuration;

        try {
            fis = new FileInputStream(cfgFile);
            configuration = getObjectMapperService().readValue(fis, Configuration.class);
        } catch (final IOException e) {
            error(e, "");
            throw new IllegalArgumentException(e);
        } finally {
            try {
                fis.close();
            } catch (final IOException e) {
                error(e, "");
            }
        }

        debug("{}", configuration);

        getApplicationRepositoryService().put(ApplicationKey.Configuration,
                new ApplicationEntry<Configuration>(configuration));
    }
}

From source file:org.commonvox.hbase_column_manager.UtilityRunner.java

private void logParmInfo(CommandLine commandLine) {
    StringBuilder parmInfo = new StringBuilder(this.getClass().getSimpleName()
            + " has been invoked with the following <option=argument> combinations:");
    for (Option option : commandLine.getOptions()) {
        parmInfo.append(" <").append(option.getLongOpt())
                .append(option.getValue() == null ? "" : ("=" + option.getValue())).append(">");
    }// www .  ja  v  a2  s  .  c  o  m
    LOG.info(parmInfo);
}

From source file:org.cytoscape.cmdline.gui.internal.Parser.java

private void parseCommandLine(String[] args) {

    // try to parse the cmd line
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;

    // first load the simple exit options
    try {//from  w  w  w. j  av a2 s  .c om
        line = parser.parse(options, args);
    } catch (ParseException e) {
        logger.error("Parsing command line failed: " + e.getMessage());
        printHelp();
        props.setProperty("tempHideWelcomeScreen", "true");
        shutdown.exit(1);
        return;
    }

    if (line.hasOption("h")) {
        printHelp();
        shutdown.exit(0);
        props.setProperty("tempHideWelcomeScreen", "true");
        return;
    }

    if (line.hasOption("v")) {
        logger.info("Cytoscape version: " + version.getVersion());
        System.out.println("Cytoscape version: " + version.getVersion());
        props.setProperty("tempHideWelcomeScreen", "true");
        shutdown.exit(0);
        return;
    }

    // always load any properties specified
    if (line.hasOption("P"))
        startupConfig.setProperties(line.getOptionValues("P"));

    // it the only argument is a session file, load it
    if (line.getOptions().length == 0 && line.getArgs().length == 1 && line.getArgs()[0].endsWith(".cys")) {
        startupConfig.setSession(line.getArgs()[0]);
        return;
    }

    // Either load the session ...      
    if (line.hasOption("s")) {
        startupConfig.setSession(line.getOptionValue("s"));

        // ... or all the rest.
    } else {
        if (line.hasOption("N"))
            startupConfig.setNetworks(line.getOptionValues("N"));

        if (line.hasOption("V"))
            startupConfig.setVizMapProps(line.getOptionValues("V"));
    }

    // Do we have any command scripts requested?
    if (line.hasOption("S"))
        startupConfig.setCommandScript(line.getOptionValue("S"));

    // Do we want a rest server?
    if (line.hasOption("R"))
        startupConfig.setRestPort(line.getOptionValue("R"));
}

From source file:org.dkpro.similarity.experiments.rte.Pipeline.java

public static void main(String[] args) throws Exception {
    DATASET_DIR = DkproContext.getContext().getWorkspace("RTE").getAbsolutePath();

    Options options = new Options();
    options.addOption("d", "devset", true, "run the given dev-set");
    options.addOption("t", "testset", true, "run the given test-set (also needs a dev-set");

    CommandLineParser parser = new PosixParser();
    try {//from   w  ww.  j  a v  a  2 s.  c  om
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("d") && !cmd.hasOption("t")) {
            Dataset devset = Dataset.valueOf(cmd.getOptionValue("d"));

            System.out.println("*** " + devset.toString() + " ***");

            runDev(devset);
        }
        if (cmd.hasOption("t") && cmd.hasOption("d")) {
            Dataset devset = Dataset.valueOf(cmd.getOptionValue("d"));
            Dataset testset = Dataset.valueOf(cmd.getOptionValue("t"));

            System.out.println("*** DEV " + devset.toString() + ", TEST " + testset.toString() + " ***");

            runTest(devset, testset);
        }

        if (cmd.getOptions().length == 0) {
            new HelpFormatter().printHelp(Pipeline.class.getSimpleName(), options, true);
        }
    } catch (ParseException e) {
        new HelpFormatter().printHelp(Pipeline.class.getSimpleName(), options);
    }
}

From source file:org.dkpro.similarity.experiments.sts2013baseline.Pipeline.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("D", "train", false, "run train mode");
    options.addOption("T", "test", false, "run test mode incl. evaluation (post-submission scenario)");
    options.addOption("S", "submission", false, "run test mode without evaluation (submission scenario)");

    CommandLineParser parser = new PosixParser();
    try {//  w w  w .  j a v a  2  s.c  o  m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("D")) {
            System.out.println("*** TRAIN MODE ***");
            runTrain();
        }
        if (cmd.hasOption("T")) {
            System.out.println("*** TEST MODE (incl. evaluation) ***");
            runTest(true);
        }
        if (cmd.hasOption("S")) {
            System.out.println("*** TEST MODE (without evaluation) ***");
            runTest(false);
        }

        if (cmd.getOptions().length == 0) {
            new HelpFormatter().printHelp(Pipeline.class.getSimpleName(), options, true);
        }
    } catch (ParseException e) {
        new HelpFormatter().printHelp(Pipeline.class.getSimpleName(), options);
    }
}

From source file:org.dspace.checker.DailyReportEmailer.java

/**
 * Allows users to have email sent to them. The default is to send all
 * reports in one email/*w  ww. ja  va2 s .  c om*/
 * 
 * @param args
 *            <dl>
 *            <dt>-h</dt>
 *            <dd>help</dd>
 *            <dt>-d</dt>
 *            <dd>Select deleted bitstreams</dd>
 *            <dt>-m</dt>
 *            <dd>Bitstreams missing from assetstore</dd>
 *            <dt>-c</dt>
 *            <dd>Bitstreams whose checksums were changed</dd>
 *            <dt>-n</dt>
 *            <dd>Bitstreams whose checksums were changed</dd>
 *            <dt>-a</dt>
 *            <dd>Send all reports in one email</dd>
 *            </dl>
 * 
 */
public static void main(String[] args) {
    // set up command line parser
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;

    // create an options object and populate it
    Options options = new Options();

    options.addOption("h", "help", false, "Help");
    options.addOption("d", "Deleted", false, "Send E-mail report for all bitstreams set as deleted for today");
    options.addOption("m", "Missing", false,
            "Send E-mail report for all bitstreams not found in assetstore for today");
    options.addOption("c", "Changed", false,
            "Send E-mail report for all bitstreams where checksum has been changed for today");
    options.addOption("a", "All", false, "Send all E-mail reports");

    options.addOption("u", "Unchecked", false, "Send the Unchecked bitstream report");

    options.addOption("n", "Not Processed", false,
            "Send E-mail report for all bitstreams set to longer be processed for today");

    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        log.fatal(e);
        System.exit(1);
    }

    // user asks for help
    if (line.hasOption('h')) {
        HelpFormatter myhelp = new HelpFormatter();

        myhelp.printHelp("Checksum Reporter\n", options);
        System.out.println("\nSend Deleted bitstream email report: DailyReportEmailer -d");
        System.out.println("\nSend Missing bitstreams email report: DailyReportEmailer -m");
        System.out.println("\nSend Checksum Changed email report: DailyReportEmailer -c");

        System.out.println("\nSend bitstream not to be processed email report: DailyReportEmailer -n");

        System.out.println("\nSend Un-checked bitstream report: DailyReportEmailer -u");

        System.out.println("\nSend All email reports: DailyReportEmailer");
        System.exit(0);
    }

    // create a new simple reporter
    SimpleReporter reporter = new SimpleReporterImpl();

    DailyReportEmailer emailer = new DailyReportEmailer();

    // get dates for yesterday and tomorrow
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.add(GregorianCalendar.DAY_OF_YEAR, -1);

    Date yesterday = calendar.getTime();
    calendar.add(GregorianCalendar.DAY_OF_YEAR, 2);

    Date tomorrow = calendar.getTime();

    File report = null;
    FileWriter writer = null;

    try {
        // the number of bitstreams in report
        int numBitstreams = 0;

        // create a temporary file in the log directory
        String dirLocation = ConfigurationManager.getProperty("log.dir");
        File directory = new File(dirLocation);

        if (directory.exists() && directory.isDirectory()) {
            report = File.createTempFile("checker_report", ".txt", directory);
        } else {
            throw new IllegalStateException("directory :" + dirLocation + " does not exist");
        }

        writer = new FileWriter(report);

        if ((line.hasOption("a")) || (line.getOptions().length == 0)) {
            writer.write("\n--------------------------------- Begin Reporting ------------------------\n\n");
            numBitstreams += reporter.getDeletedBitstreamReport(yesterday, tomorrow, writer);
            writer.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
            numBitstreams += reporter.getChangedChecksumReport(yesterday, tomorrow, writer);
            writer.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
            numBitstreams += reporter.getBitstreamNotFoundReport(yesterday, tomorrow, writer);
            writer.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
            numBitstreams += reporter.getNotToBeProcessedReport(yesterday, tomorrow, writer);
            writer.write("\n--------------------------------- Report Spacer ---------------------------\n\n");
            numBitstreams += reporter.getUncheckedBitstreamsReport(writer);
            writer.write("\n--------------------------------- End Report ---------------------------\n\n");
            writer.flush();
            writer.close();
            emailer.sendReport(report, numBitstreams);
        } else {
            if (line.hasOption("d")) {
                writer.write(
                        "\n--------------------------------- Begin Reporting ------------------------\n\n");
                numBitstreams += reporter.getDeletedBitstreamReport(yesterday, tomorrow, writer);
                writer.flush();
                writer.close();
                emailer.sendReport(report, numBitstreams);
            }

            if (line.hasOption("m")) {
                writer.write(
                        "\n--------------------------------- Begin Reporting ------------------------\n\n");
                numBitstreams += reporter.getBitstreamNotFoundReport(yesterday, tomorrow, writer);
                writer.flush();
                writer.close();
                emailer.sendReport(report, numBitstreams);
            }

            if (line.hasOption("c")) {
                writer.write(
                        "\n--------------------------------- Begin Reporting ------------------------\n\n");
                numBitstreams += reporter.getChangedChecksumReport(yesterday, tomorrow, writer);
                writer.flush();
                writer.close();
                emailer.sendReport(report, numBitstreams);
            }

            if (line.hasOption("n")) {
                writer.write(
                        "\n--------------------------------- Begin Reporting ------------------------\n\n");
                numBitstreams += reporter.getNotToBeProcessedReport(yesterday, tomorrow, writer);
                writer.flush();
                writer.close();
                emailer.sendReport(report, numBitstreams);
            }

            if (line.hasOption("u")) {
                writer.write(
                        "\n--------------------------------- Begin Reporting ------------------------\n\n");
                numBitstreams += reporter.getUncheckedBitstreamsReport(writer);
                writer.flush();
                writer.close();
                emailer.sendReport(report, numBitstreams);
            }
        }
    } catch (MessagingException e) {
        log.fatal(e);
    } catch (IOException e) {
        log.fatal(e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception e) {
                log.fatal("Could not close writer", e);
            }
        }

        if (report != null && report.exists()) {
            if (!report.delete()) {
                log.error("Unable to delete report file");
            }
        }
    }
}

From source file:org.dspace.identifier.doi.DOIOrganiser.java

public static void runCLI(Context context, DOIOrganiser organiser, String[] args) {
    // initlize options
    Options options = new Options();

    options.addOption("h", "help", false, "Help");
    options.addOption("l", "list", false, "List all objects to be reserved, registered, deleted of updated ");
    options.addOption("r", "register-all", false,
            "Perform online registration for all identifiers queued for registration.");
    options.addOption("s", "reserve-all", false,
            "Perform online reservation for all identifiers queued for reservation.");
    options.addOption("u", "update-all", false,
            "Perform online metadata update for all identifiers queued for metadata update.");
    options.addOption("d", "delete-all", false,
            "Perform online deletion for all identifiers queued for deletion.");

    options.addOption("q", "quiet", false, "Turn the command line output off.");

    Option registerDoi = OptionBuilder.withArgName("DOI|ItemID|handle").withLongOpt("register-doi").hasArgs(1)
            .withDescription("Register a specified identifier. "
                    + "You can specify the identifier by ItemID, Handle or DOI.")
            .create();//from w w  w  .  jav a 2  s.co m

    options.addOption(registerDoi);

    Option reserveDoi = OptionBuilder.withArgName("DOI|ItemID|handle").withLongOpt("reserve-doi").hasArgs(1)
            .withDescription("Reserve a specified identifier online. "
                    + "You can specify the identifier by ItemID, Handle or DOI.")
            .create();

    options.addOption(reserveDoi);

    Option update = OptionBuilder.withArgName("DOI|ItemID|handle").hasArgs(1)
            .withDescription("Update online an object for a given DOI identifier"
                    + " or ItemID or Handle. A DOI identifier or an ItemID or a Handle is needed.\n")
            .withLongOpt("update-doi").create();

    options.addOption(update);

    Option delete = OptionBuilder.withArgName("DOI identifier").withLongOpt("delete-doi").hasArgs(1)
            .withDescription("Delete a specified identifier.").create();

    options.addOption(delete);

    // initialize parser
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    HelpFormatter helpformater = new HelpFormatter();

    try {
        line = parser.parse(options, args);
    } catch (ParseException ex) {
        LOG.fatal(ex);
        System.exit(1);
    }

    // process options
    // user asks for help
    if (line.hasOption('h') || 0 == line.getOptions().length) {
        helpformater.printHelp("\nDOI organiser\n", options);
    }

    if (line.hasOption('q')) {
        organiser.setQuiet();
    }

    if (line.hasOption('l')) {
        organiser.list("reservation", null, null, DOIIdentifierProvider.TO_BE_RESERVED);
        organiser.list("registration", null, null, DOIIdentifierProvider.TO_BE_REGISTERED);
        organiser.list("update", null, null, DOIIdentifierProvider.UPDATE_BEFORE_REGISTRATION,
                DOIIdentifierProvider.UPDATE_REGISTERED, DOIIdentifierProvider.UPDATE_RESERVED);
        organiser.list("deletion", null, null, DOIIdentifierProvider.TO_BE_DELETED);
    }

    DOIService doiService = IdentifierServiceFactory.getInstance().getDOIService();

    if (line.hasOption('s')) {

        try {
            List<DOI> dois = doiService.getDOIsByStatus(context,
                    Arrays.asList(DOIIdentifierProvider.TO_BE_RESERVED));
            if (0 == dois.size()) {
                System.err.println("There are no objects in the database " + "that could be reserved.");
            }

            for (DOI doi : dois) {
                organiser.reserve(doi);
                context.uncacheEntity(doi);
            }
        } catch (SQLException ex) {
            System.err.println("Error in database connection:" + ex.getMessage());
            ex.printStackTrace(System.err);
        }
    }

    if (line.hasOption('r')) {

        try {
            List<DOI> dois = doiService.getDOIsByStatus(context,
                    Arrays.asList(DOIIdentifierProvider.TO_BE_REGISTERED));
            if (0 == dois.size()) {
                System.err.println("There are no objects in the database " + "that could be registered.");
            }
            for (DOI doi : dois) {
                organiser.register(doi);
                context.uncacheEntity(doi);
            }
        } catch (SQLException ex) {
            System.err.println("Error in database connection:" + ex.getMessage());
            ex.printStackTrace(System.err);
        }
    }

    if (line.hasOption('u')) {

        try {
            List<DOI> dois = doiService.getDOIsByStatus(context,
                    Arrays.asList(DOIIdentifierProvider.UPDATE_BEFORE_REGISTRATION,
                            DOIIdentifierProvider.UPDATE_RESERVED, DOIIdentifierProvider.UPDATE_REGISTERED));
            if (0 == dois.size()) {
                System.err.println("There are no objects in the database " + "whose metadata needs an update.");
            }

            for (DOI doi : dois) {
                organiser.update(doi);
                context.uncacheEntity(doi);
            }
        } catch (SQLException ex) {
            System.err.println("Error in database connection:" + ex.getMessage());
            ex.printStackTrace(System.err);
        }
    }

    if (line.hasOption('d')) {

        try {
            List<DOI> dois = doiService.getDOIsByStatus(context,
                    Arrays.asList(DOIIdentifierProvider.TO_BE_DELETED));
            if (0 == dois.size()) {
                System.err.println("There are no objects in the database " + "that could be deleted.");
            }

            Iterator<DOI> iterator = dois.iterator();
            while (iterator.hasNext()) {
                DOI doi = iterator.next();
                iterator.remove();
                organiser.delete(doi.getDoi());
                context.uncacheEntity(doi);
            }
        } catch (SQLException ex) {
            System.err.println("Error in database connection:" + ex.getMessage());
            ex.printStackTrace(System.err);
        }
    }

    if (line.hasOption("reserve-doi")) {
        String identifier = line.getOptionValue("reserve-doi");

        if (null == identifier) {
            helpformater.printHelp("\nDOI organiser\n", options);
        } else {
            try {
                DOI doiRow = organiser.resolveToDOI(identifier);
                organiser.reserve(doiRow);
            } catch (SQLException ex) {
                LOG.error(ex);
            } catch (IllegalArgumentException ex) {
                LOG.error(ex);
            } catch (IllegalStateException ex) {
                LOG.error(ex);
            } catch (IdentifierException ex) {
                LOG.error(ex);
            }
        }
    }

    if (line.hasOption("register-doi")) {
        String identifier = line.getOptionValue("register-doi");

        if (null == identifier) {
            helpformater.printHelp("\nDOI organiser\n", options);
        } else {
            try {
                DOI doiRow = organiser.resolveToDOI(identifier);
                organiser.register(doiRow);
            } catch (SQLException ex) {
                LOG.error(ex);
            } catch (IllegalArgumentException ex) {
                LOG.error(ex);
            } catch (IllegalStateException ex) {
                LOG.error(ex);
            } catch (IdentifierException ex) {
                LOG.error(ex);
            }
        }
    }

    if (line.hasOption("update-doi")) {
        String identifier = line.getOptionValue("update-doi");

        if (null == identifier) {
            helpformater.printHelp("\nDOI organiser\n", options);
        } else {
            try {
                DOI doiRow = organiser.resolveToDOI(identifier);
                organiser.update(doiRow);
            } catch (SQLException ex) {
                LOG.error(ex);
            } catch (IllegalArgumentException ex) {
                LOG.error(ex);
            } catch (IllegalStateException ex) {
                LOG.error(ex);
            } catch (IdentifierException ex) {
                LOG.error(ex);
            }
        }
    }

    if (line.hasOption("delete-doi")) {
        String identifier = line.getOptionValue("delete-doi");

        if (null == identifier) {
            helpformater.printHelp("\nDOI organiser\n", options);
        } else {
            try {
                organiser.delete(identifier);
            } catch (SQLException ex) {
                LOG.error(ex);
            } catch (IllegalArgumentException ex) {
                LOG.error(ex);
            }
        }
    }

}