Example usage for org.apache.commons.cli ParseException printStackTrace

List of usage examples for org.apache.commons.cli ParseException printStackTrace

Introduction

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

Prototype

public void printStackTrace(PrintStream s) 

Source Link

Document

Prints this throwable and its backtrace to the specified print stream.

Usage

From source file:com.github.dakusui.symfonion.CLI.java

public static int invoke(PrintStream stdout, PrintStream stderr, String... args) {
    int ret = 255;
    try {/* w  ww .  j av  a  2s. com*/
        CLI cli = new CLI(args);
        cli.mode.invoke(cli, stdout);
        ret = 0;
    } catch (ParseException e) {
        printError(stderr, e);
        ret = 1;
    } catch (CLIException e) {
        printError(stderr, e);
        ret = 2;
    } catch (SymfonionException e) {
        printError(stderr, e);
        ret = 3;
    } catch (IOException e) {
        e.printStackTrace(stderr);
        ret = 4;
    }
    return ret;
}

From source file:com.norconex.collector.core.AbstractCollectorLauncher.java

protected CommandLine parseCommandLineArguments(String[] args) {
    Options options = new Options();
    options.addOption("c", ARG_CONFIG, true, "Required: Collector configuration file.");
    options.addOption("v", ARG_VARIABLES, true, "Optional: variable file.");
    options.addOption("a", ARG_ACTION, true, "Required: one of start|resume|stop");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;/*from   w  w w  .j  av a  2s.  c  o m*/
    try {
        cmd = parser.parse(options, args);
        if (!cmd.hasOption(ARG_CONFIG) || !cmd.hasOption(ARG_ACTION) || EqualsUtil.equalsNone(
                cmd.getOptionValue(ARG_ACTION), ARG_ACTION_START, ARG_ACTION_RESUME, ARG_ACTION_STOP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("collector-http[.bat|.sh]", options);
            System.exit(-1);
        }
    } catch (ParseException e) {
        PrintStream err = System.err;
        err.println("Could not parse arguments.");
        e.printStackTrace(System.err);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("collector-http[.bat|.sh]", options);
        System.exit(-1);
    }
    return cmd;
}

From source file:com.redhat.consulting.eapquickstarts.mutualauth.remoting.ejb.client.RemoteEJBClient.java

private void parseInputs(String[] args) {
    CommandLineParser parser = new GnuParser();
    CommandLine cmdLine;/*from   ww w. j  a v  a 2 s .  com*/

    try {
        cmdLine = parser.parse(options, args);
        CommandLineArgumentsParserUtils.printRawArguments(args,
                "List of original arguments right after they have been parsed \n");
        if (cmdLine.getArgs().length != 0) {
            System.out.print("unexpected Exception occurred while processing pased in arguments: ");
            CommandLineArgumentsParserUtils.printHelp(cmdLine, options);
        }
        processOptions(cmdLine);

    } catch (ParseException e) {
        e.printStackTrace(System.out);
    }
}

From source file:eu.project.ttc.tools.cli.TermSuiteAlignerCLI.java

public void run(String[] args, PrintStream out) {
    File logDir = new File("logs");
    if (!logDir.exists())
        logDir.mkdir();// ww  w .j av  a 2s.  c  o m
    String logPath = Paths
            .get("logs",
                    "termsuite-aligner-" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".log")
            .toAbsolutePath().toString();
    TermSuiteCLIUtils.logToFile(logPath);
    Stopwatch sw = Stopwatch.createStarted();
    LOGGER.info("Logging to {}", logPath);
    try {

        // usage
        // java -DconfigFile=myPropertiesFileName -Xms1g  -Xmx2g -cp ttc-term-suite-1.3.jar eu.project.ttc.tools.cli.TermSuiteSpotterCLI
        // if the option -DconfigFile is missing preferencesFileName is set to TermSuiteCLIUtils.USER_HOME+PREFERENCES_FILE_NAME
        // create the command line parser
        PosixParser parser = new PosixParser();

        // create the Options
        Options options = declareOptions();

        try {
            // Parse and set CL options
            CommandLine line = parser.parse(options, args, false);
            readArguments(line, out);
            TermSuiteCLIUtils.setGlobalLogLevel("info");
            TermSuiteCLIUtils.logCommandLineOptions(line);

            BilingualAligner aligner = TermSuiteAlignerBuilder.start().setSourceTerminology(sourceTermino.get())
                    .setTargetTerminology(targetTermino.get()).setDicoPath(dicoPath).setDistance(distance)
                    .create();

            for (String term : terms) {
                Term sourceTerm = readSourceTerm(term);
                if (sourceTerm == null) {
                    LOGGER.error("Cannot find term \"{}\" in {}", term, line.getOptionValue(SOURCE_TERMINO));
                } else {
                    if (terms.size() > 1) {
                        out.println("---");
                        out.println(sourceTerm);
                        out.println("-");
                    }
                    for (TranslationCandidate candidate : aligner.align(sourceTerm, n, 1)) {
                        if (showExplanation)
                            out.format("%s\t%.3f\t%s\t%s\n", candidate.getTerm(), candidate.getScore(),
                                    candidate.getMethod(), candidate.getExplanation().getText());
                        else
                            out.format("%s\t%.3f\t%s\n", candidate.getTerm(), candidate.getScore(),
                                    candidate.getMethod());
                    }
                }
            }

            LOGGER.info("Script executed in " + sw.toString());

        } catch (ParseException e) {
            TermSuiteCLIUtils.printUsage(e, USAGE, options);
        }

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

From source file:com.planet57.gshell.MainSupport.java

public void boot(final String... args) throws Exception {
    checkNotNull(args);//  ww  w.  j av  a 2 s. c om

    if (log.isDebugEnabled()) {
        log.debug("Booting w/args: {}", Arrays.toString(args));
    }

    // Register default handler for uncaught exceptions
    Thread.setDefaultUncaughtExceptionHandler(
            (thread, cause) -> log.warn("Unhandled exception occurred on thread: {}", thread, cause));

    // Prepare branding
    Branding branding = createBranding();

    // Process preferences
    PreferenceProcessor pp = new PreferenceProcessor();
    pp.setBasePath(branding.getPreferencesBasePath());
    pp.addBean(this);
    pp.process();

    // Process command line options & arguments
    CliProcessor clp = new CliProcessor();
    clp.addBean(this);
    clp.setStopAtNonOption(true);

    // cope with cli exceptions; which are expected
    try {
        clp.process(args);
    } catch (ParseException e) {
        e.printStackTrace(System.err);
        exit(2);
    }

    // once options are processed setup logging environment
    setupLogging(loggingLevel);

    // setup styling
    Styler.setSource(new MemoryStyleSource());

    // prepare terminal and I/O
    Terminal terminal = createTerminal(branding);
    IO io = StyledIO.create("shell", createStreamSet(terminal), terminal);

    if (help) {
        HelpPrinter printer = new HelpPrinter(clp, terminal.getWidth());
        printer.printUsage(io.out, branding.getProgramName());
        io.flush();
        exit(0);
    }

    if (version) {
        io.format("%s %s%n", branding.getDisplayName(), branding.getVersion());
        io.flush();
        exit(0);
    }

    // install thread-IO handler and attach streams
    threadIO.start();
    threadIO.setStreams(io.streams.in, io.streams.out, io.streams.err);

    Object result = null;
    try {
        variables.set(VariableNames.SHELL_ERRORS, showErrorTraces);

        Shell shell = createShell(io, variables, branding);
        shell.start();
        try {
            if (command != null) {
                result = shell.execute(command);
            } else if (appArgs != null) {
                result = shell.execute(String.join(" ", appArgs));
            } else {
                shell.run();
            }
        } finally {
            shell.stop();
        }
    } finally {
        io.flush();
        threadIO.stop();
        terminal.close();
    }

    if (result == null) {
        result = variables.get(VariableNames.LAST_RESULT);
    }

    exit(ExitCodeDecoder.decode(result));
}

From source file:com.facebook.stetho.dumpapp.Dumper.java

/**
 * Execute the dump method as if it were a fragile external command.  Swallows exceptions
 * and translates them to dumped output text.
 *
 * @param input Input that came from the CLI's stdin.
 * @param out Output that will eventually make its way to the CLI's stdout.
 * @param err Output that will eventually make its way to the CLI's stderr.
 * @param args Argument list as passed from the CLI.
 *
 * @return Exit code as if this were a command-line invocation.
 *//*  w ww .  j  a  v  a  2 s.  c  om*/
public int dump(InputStream input, PrintStream out, PrintStream err, String[] args) {
    try {
        return doDump(input, out, err, args);
    } catch (ParseException e) {
        err.println(e.getMessage());
        dumpUsage(err);
        return 1;
    } catch (DumpException e) {
        err.println(e.getMessage());
        return 1;
    } catch (DumpappOutputBrokenException e) {
        // The peer is already gone, no sense in sending the exception stack to them.
        throw e;
    } catch (RuntimeException e) {
        e.printStackTrace(err);
        return 1;
    }
}

From source file:com.oneops.boo.BooCli.java

/**
 * Parse user's input./*from www .java  2 s  .com*/
 *
 * @param arg the arg
 * @throws ParseException the parse exception
 * @throws BooException the Boo exception
 * @throws OneOpsClientAPIException the one ops client API exception
 */
public int parse(String[] arg) throws ParseException, BooException, OneOpsClientAPIException {
    CommandLineParser parser = new DefaultParser();
    int exit = 0;
    // CommandLineParser parser = new GnuParser();
    try {

        String assembly = null;
        CommandLine cmd = parser.parse(options, arg);
        /**
         * Handle command without configuration file dependency first.
         */
        if (cmd.hasOption("h")) {
            this.help(null, "");
            return exit;
        }

        if (cmd.hasOption("quiet")) {
            BooCli.setQuiet(Boolean.TRUE);
        }

        if (cmd.hasOption("force")) {
            BooCli.setForced(Boolean.TRUE);
        }
        if (cmd.hasOption("no-deploy")) {
            BooCli.setNoDeploy(Boolean.TRUE);
        }

        if (cmd.hasOption("a")) {
            assembly = cmd.getOptionValue("a");
        }
        /**
         * Get configuration dir or file.
         */
        if (cmd.hasOption("f")) {
            this.configFile = new File(booUtils.getAbsolutePath(cmd.getOptionValue("f")));
            System.out.printf(Constants.CONFIG_FILE, this.configFile);
            System.out.println();
        }

        if (this.configFile == null || !this.configFile.exists()) {
            this.help(null, "No YAML file found.");
            return Constants.EXIT_YAML_NOT_FOUND;
        }

        String yaml = "";

        if (ClientConfig.ONEOPS_CONFIG.exists()) {
            if (cmd.hasOption("profile")) {
                this.profile = cmd.getOptionValue("profile");
            }
            ClientConfigIniReader iniReader = new ClientConfigIniReader();
            if (iniReader.read(ClientConfig.ONEOPS_CONFIG, profile) == null) {
                System.out.format("%n%s is not a valid profile in %s.%n%n", profile,
                        ClientConfig.ONEOPS_CONFIG);
                return Constants.EXIT_INVALID_PROFILE;
            }

            ClientConfigInterpolator interpolator = new ClientConfigInterpolator();
            yaml = interpolator.interpolate(this.configFile, ClientConfig.ONEOPS_CONFIG, this.profile);
        }

        if (cmd.hasOption('v')) {
            System.out.println(yaml);
            if (!ClientConfig.ONEOPS_CONFIG.exists()) {
                System.out.format("%nYou do not have a %s file. No interpolation can be performed.%n%n",
                        ClientConfig.ONEOPS_CONFIG);
            }
            return exit;
        }

        if (cmd.hasOption("m")) {
            this.comment = cmd.getOptionValue("m");
        }

        this.init(this.configFile, assembly, null, comment);
        if (cmd.hasOption("l")) {
            String prefix = cmd.getOptionValue("l");
            if (prefix == null) {
                this.listFiles(config.getYaml().getAssembly().getName());
            } else {
                this.listFiles(prefix.trim());
            }
            return Constants.EXIT_NORMAL;
        }
        /**
         * Handle other commands.
         */
        if (cmd.hasOption("s")) {
            if (!flow.isAssemblyExist()) {
                System.err.printf(Constants.NOTFOUND_ERROR, config.getYaml().getAssembly().getName());
                return Constants.EXIT_ASSEMBLY_NOT_FOUND;
            } else {
                System.out.println(this.getStatus());
            }
        } else if (cmd.hasOption("c")) {
            if (config.getYaml().getAssembly().getAutoGen()) {
                this.initOo(this.config, this.autoGenAssemblyName(config.getYaml().getAssembly().getAutoGen(),
                        config.getYaml().getAssembly().getName()), comment);
                LogUtils.info(Constants.CREATING_ASSEMBLY, config.getYaml().getAssembly().getName());
            }
            this.createPacks(Boolean.FALSE, isNoDeploy);
        } else if (cmd.hasOption("u")) {
            if (!config.getYaml().getAssembly().getAutoGen()) {
                if (flow.isAssemblyExist()) {
                    this.createPacks(Boolean.TRUE, isNoDeploy);
                } else {
                    System.err.printf(Constants.NOTFOUND_ERROR, config.getYaml().getAssembly().getName());
                }
            } else {
                List<String> assemblies = this.listFiles(this.config.getYaml().getAssembly().getName());
                for (String asm : assemblies) {
                    this.initOo(config, asm, comment);
                    this.createPacks(Boolean.TRUE, isNoDeploy);
                }
            }
        } else if (cmd.hasOption("r")) {
            List<String> assemblies;
            if (config.getYaml().getAssembly().getAutoGen()) {
                assemblies = this.listFiles(this.config.getYaml().getAssembly().getName());
            } else {
                assemblies = new ArrayList<String>();
                String asb = this.config.getYaml().getAssembly().getName();
                if (this.flow.isAssemblyExist(asb)) {
                    assemblies.add(asb);
                }
            }
            this.cleanup(assemblies);
        } else if (cmd.hasOption("get-ips")) {
            if (!flow.isAssemblyExist()) {
                System.err.printf(Constants.NOTFOUND_ERROR, config.getYaml().getAssembly().getName());
            } else if (cmd.getOptionValues("get-ips") == null) {
                // if there is no args for get-ips
                getIps0();
            } else if (cmd.getOptionValues("get-ips").length == 1) {
                // if there is one arg for get-ips
                getIps1(cmd.getOptionValues("get-ips")[0]);
            } else if (cmd.getOptionValues("get-ips").length == 2) {
                // if there are two args for get-ips
                getIps2(cmd.getOptionValues("get-ips")[0], cmd.getOptionValues("get-ips")[1]);
            }
        } else if (cmd.hasOption("retry")) {
            this.retryDeployment();
        } else if (cmd.hasOption("procedure")) {
            if (cmd.getOptionValues("procedure").length != 3) {
                System.err.println("Wrong parameters! --prodedure <platformName> <componentName> <actionName>");
                return Constants.EXIT_WRONG_PRAMETER;
            } else {
                String[] args = cmd.getOptionValues("procedure");
                String arglist = "";
                int rollAt = 100;
                if (cmd.hasOption("procedure-arguments")) {
                    arglist = cmd.getOptionValue("procedure-arguments");
                }
                if (cmd.hasOption("procedure-step-size")) {
                    rollAt = Integer.parseInt(cmd.getOptionValue("procedure-step-size"));
                }
                List<String> instances = null;
                if (cmd.hasOption("procedure-instances")) {
                    String ins = cmd.getOptionValue("procedure-instances");
                    if (ins != null && ins.trim().length() > 0) {
                        if (ins.equalsIgnoreCase("list")) {
                            List<String> list = flow.listInstances(args[0], args[1]);
                            if (list != null) {
                                for (String instance : list) {
                                    System.out.println(instance);
                                }
                            }
                            return Constants.EXIT_NORMAL;
                        }
                        instances = Arrays.asList(ins.split(","));
                    }
                }
                if ("list".equalsIgnoreCase(args[2])) {
                    List<String> list = flow.listActions(args[0], args[1]);
                    if (list != null) {
                        for (String instance : list) {
                            System.out.println(instance);
                        }
                    }
                } else {
                    exit = this.executeAction(args[0], args[1], args[2], arglist, instances, rollAt);
                }

            }
        } else {
            System.err.println("Wrong parameters!");
            return Constants.EXIT_WRONG_PRAMETER;
        }
    } catch (ParseException e) {
        exit = Constants.EXIT_PARSE_ERROR;
    } catch (Exception e) {
        exit = Constants.EXIT_UNKOWN;
        e.printStackTrace(new PrintStream(System.err));
    }
    return exit;
}

From source file:nz.ac.waikato.its.irr.scripts.FixSquishedMetadata.java

public static void main(String[] args) {
    CommandLine line = null;/*from  w  w w  .  ja v a  2s.c om*/
    try {
        line = new BasicParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println("Could not parse command line options: " + e.getMessage());
        ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
    }

    if (line == null || line.hasOption("h")) {
        ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 0, OPTIONS);
    }

    Context context = null;
    try {
        context = new Context();
        context.turnOffAuthorisationSystem();

        DSpaceObject dso = null;
        if (line.hasOption("i")) {
            String handle = line.getOptionValue("i");
            dso = HandleManager.resolveToObject(context, handle);
            if (dso == null) {
                System.err.println("Could not resolve identifier " + handle + " to a DSpace object");
                ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
            }
        }

        String delimiter = line.getOptionValue("d");
        int minMatches = 1;
        if (line.hasOption("m")) {
            try {
                minMatches = Integer.valueOf(line.getOptionValue("m"));
            } catch (NumberFormatException e) {
                System.err.println("Could not parse min matches value (" + line.getOptionValue("m")
                        + ") as a number :" + e.getMessage());
                ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
            }
        }
        boolean dryRun = line.hasOption("n");

        String schema, element, qualifier;
        String[] fieldComponents = line.getOptionValue("f", "").split("\\.");
        if (fieldComponents.length < 2) {
            System.err.println("Unsupported metadata field name: " + line.getOptionValue("f"));
            ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
        }
        schema = fieldComponents[0];
        element = fieldComponents[1];
        qualifier = fieldComponents.length > 2 ? fieldComponents[2] : null;

        boolean changes = false;
        if (dso == null || dso.getType() == Constants.SITE) {
            changes = process(Item.findByMetadataField(context, schema, element, qualifier, Item.ANY), schema,
                    element, qualifier, delimiter, minMatches, dryRun);
        } else if (dso.getType() == Constants.COMMUNITY) {
            Collection[] collections = ((Community) dso).getAllCollections();
            for (Collection collection : collections) {
                changes |= process(collection.getAllItems(), schema, element, qualifier, delimiter, minMatches,
                        dryRun);
            }
        } else if (dso.getType() == Constants.COLLECTION) {
            changes = process(((Collection) dso).getAllItems(), schema, element, qualifier, delimiter,
                    minMatches, dryRun);
        } else if (dso.getType() == Constants.ITEM) {
            changes = process((Item) dso, schema, element, qualifier, delimiter, minMatches, dryRun);
        } else {
            System.err.println("Unsupported type of DSpace object: " + dso.getTypeText()
                    + ", need site, community, collection or item handle");
            ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
        }
        if (changes) {
            context.complete();
        }
    } catch (SQLException | AuthorizeException | IOException e) {
        e.printStackTrace(System.err);
    } finally {
        if (context != null && context.isValid()) {
            context.abort();
        }
    }
}

From source file:nz.ac.waikato.its.irr.scripts.MoveMetadataValues.java

public static void main(String[] args) {
    CommandLine line = null;/* w w  w. j  a va 2 s .c o  m*/
    try {
        line = new BasicParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println("Could not parse command line options: " + e.getMessage());
        ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
    }

    if (line == null || line.hasOption("h")) {
        ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 0, OPTIONS);
        return;
    }

    boolean dryRun = line.hasOption("n");

    String sourceSchema, sourceElement, sourceQualifier;
    String[] sourceFieldComponents = line.getOptionValue("s", "").split("\\.");
    if (sourceFieldComponents.length < 2) {
        System.err.println("Unsupported source metadata field name: " + line.getOptionValue("s"));
        ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
    }
    sourceSchema = sourceFieldComponents[0];
    sourceElement = sourceFieldComponents[1];
    sourceQualifier = sourceFieldComponents.length > 2 ? sourceFieldComponents[2] : null;

    String targetSchema, targetElement, targetQualifier;
    String[] targetFieldComponents = line.getOptionValue("t", "").split("\\.");
    if (targetFieldComponents.length < 2) {
        System.err.println("Unsupported target metadata field name: " + line.getOptionValue("t"));
        ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
    }
    targetSchema = targetFieldComponents[0];
    targetElement = targetFieldComponents[1];
    targetQualifier = targetFieldComponents.length > 2 ? targetFieldComponents[2] : null;

    String language = line.getOptionValue("l");

    boolean matchCase = line.hasOption("c");
    boolean usePreferredCase = line.hasOption("p");

    Map<String, String> valuesFilter = new HashMap<>();
    if (line.hasOption("r")) {
        File valuesFile = new File(line.getOptionValue("r"));
        if (valuesFile.exists() && valuesFile.canRead()) {
            try (Scanner scanner = new Scanner(valuesFile)) {
                while (scanner.hasNextLine()) {
                    String value = scanner.nextLine().trim();
                    String key = matchCase ? value : value.toLowerCase();
                    valuesFilter.put(key, value);
                }
            } catch (FileNotFoundException e) {
                System.err.println(
                        "Problem reading values file " + line.getOptionValue("r") + ": " + e.getMessage());
                ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
            }
        } else {
            System.err.println(
                    "Values file " + line.getOptionValue("r") + " doesn't exist or is not readable, aborting");
            ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
        }
    }

    Context context = null;
    try {
        context = new Context();
        context.turnOffAuthorisationSystem();

        DSpaceObject dso = null;
        if (line.hasOption("i")) {
            String handle = line.getOptionValue("i");
            dso = HandleManager.resolveToObject(context, handle);
            if (dso == null) {
                System.err.println("Could not resolve identifier " + handle + " to a DSpace object");
                ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
            }
        }

        boolean changes = false;
        if (dso == null || dso.getType() == Constants.SITE) {
            changes = process(
                    Item.findByMetadataField(context, sourceSchema, sourceElement, sourceQualifier, Item.ANY),
                    sourceSchema, sourceElement, sourceQualifier, targetSchema, targetElement, targetQualifier,
                    language, valuesFilter, matchCase, usePreferredCase, dryRun);
        } else if (dso.getType() == Constants.COMMUNITY) {
            Collection[] collections = ((Community) dso).getAllCollections();
            for (Collection collection : collections) {
                changes |= process(collection.getAllItems(), sourceSchema, sourceElement, sourceQualifier,
                        targetSchema, targetElement, targetQualifier, language, valuesFilter, matchCase,
                        usePreferredCase, dryRun);
            }
        } else if (dso.getType() == Constants.COLLECTION) {
            changes = process(((Collection) dso).getAllItems(), sourceSchema, sourceElement, sourceQualifier,
                    targetSchema, targetElement, targetQualifier, language, valuesFilter, matchCase,
                    usePreferredCase, dryRun);
        } else if (dso.getType() == Constants.ITEM) {
            changes = process((Item) dso, sourceSchema, sourceElement, sourceQualifier, targetSchema,
                    targetElement, targetQualifier, language, valuesFilter, matchCase, usePreferredCase,
                    dryRun);
        } else {
            System.err.println("Unsupported type of DSpace object: " + dso.getTypeText()
                    + ", need site, community, collection or item handle");
            ScriptUtils.printHelpAndExit(FixSquishedMetadata.class.getSimpleName(), 1, OPTIONS);
        }
        if (changes) {
            context.complete();
        }
    } catch (SQLException | AuthorizeException | IOException e) {
        e.printStackTrace(System.err);
    } finally {
        if (context != null && context.isValid()) {
            context.abort();
        }
    }
}

From source file:nz.ac.waikato.its.irr.scripts.RetrospectiveElementsLinkup.java

public static void main(String[] args) {
    CommandLine line = null;/*from   ww  w  .  ja v  a 2 s  .c  o  m*/
    try {
        line = new BasicParser().parse(OPTIONS, args);
    } catch (ParseException e) {
        System.err.println("Could not parse command line options: " + e.getMessage());
        ScriptUtils.printHelpAndExit(RetrospectiveElementsLinkup.class.getSimpleName(), 1, OPTIONS);
    }

    if (line == null || line.hasOption("h")) {
        ScriptUtils.printHelpAndExit(RetrospectiveElementsLinkup.class.getSimpleName(), 0, OPTIONS);
    }

    if (line.hasOption("f") && (line.hasOption("d") || line.hasOption("p"))) {
        System.err.println(
                "Cannot give both -f and -d/-p; use -f for bulk operation, -d/-p to link a single item.");
        ScriptUtils.printHelpAndExit(RetrospectiveElementsLinkup.class.getSimpleName(), 1, OPTIONS);
    }

    if (!line.hasOption("f") && !line.hasOption("d") && !line.hasOption("p")) {
        System.err.println("Need either -f (for bulk operation) or -d and -p (to link a single item).");
        ScriptUtils.printHelpAndExit(RetrospectiveElementsLinkup.class.getSimpleName(), 1, OPTIONS);
    }

    boolean verbose = line.hasOption("v");

    int itemsProcessed = 0;
    Context context = null;
    try {
        context = new Context();
        context.turnOffAuthorisationSystem();

        if (line.hasOption("f")) {
            String fileName = line.getOptionValue("f");
            File inputFile = new File(fileName);
            if (!inputFile.exists() || !inputFile.canRead()) {
                System.err.println(
                        "Input file " + fileName + " doesn't exist or is not readable for current user.");
                ScriptUtils.printHelpAndExit(RetrospectiveElementsLinkup.class.getSimpleName(), 1, OPTIONS);
            }
            try (Scanner scanner = new Scanner(inputFile)) {
                while (scanner.hasNextLine()) {
                    String nextLine = scanner.nextLine();
                    if (nextLine.startsWith("#")) {
                        continue;
                    }
                    String[] toProcess = nextLine.trim().split(",\\s*");
                    if (toProcess.length != 2) {
                        System.err.println(
                                "Skipping line, was expecting comma-separated pair of DSpace id, Elements pubs id");
                        continue;
                    }
                    try {
                        processLinkup(context, toProcess[0], toProcess[1], verbose);
                        if (verbose) {
                            System.out.println(
                                    String.format("Linked up DSpace id/handle %s with Elements pubs id %s",
                                            toProcess[0], toProcess[1]));
                        }
                        context.commit();
                        itemsProcessed++;
                    } catch (Exception e) {
                        System.err.println(String.format(
                                "Caught exception while attempting to link up DSpace id %s and publications id %s, skipping line",
                                toProcess[0], toProcess[1]));
                        e.printStackTrace(System.err);
                    }
                }
            } catch (FileNotFoundException e) {
                System.err.println("Error processing file " + fileName);
            }
        } else if (!line.hasOption("d") || !line.hasOption("p")) {
            System.err.println("In single item mode, -d and -p are both required.");
            ScriptUtils.printHelpAndExit(RetrospectiveElementsLinkup.class.getSimpleName(), 1, OPTIONS);
        } else {
            String dspaceString = line.getOptionValue("d", "");
            String pubsString = line.getOptionValue("p", "");

            processLinkup(context, dspaceString, pubsString, verbose);
            if (verbose) {
                System.out.println(String.format("Linked up DSpace id/handle %s with Elements pubs id %s",
                        dspaceString, pubsString));
            }
            context.commit();
            itemsProcessed++;
        }
    } catch (SQLException | AuthorizeException e) {
        e.printStackTrace(System.err);
    } finally {
        if (context != null && context.isValid()) {
            context.abort();
        }
    }

    if (itemsProcessed > 0) {
        System.out.println(String.format("Processed %d item(s); remember to run the ListHoldings task next.",
                itemsProcessed));
    }
}