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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:nor.core.Nor.java

/**
 * ??/*from w  w  w  .j a va2s .c o m*/
 * @param args ?????
 * @throws MalformedURLException
 */
@SuppressWarnings("static-access")
public static void main(final String[] args) {
    LOGGER.info("main", "Start up...");

    final Options ops = new Options();
    ops.addOption(OptionBuilder.withArgName("dir").hasArg()
            .withDescription("set directory which has config files").create("config"));

    ops.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("use given configu file for logging system").create("log"));

    final Option pluginsPath = OptionBuilder.withArgName("dir").hasArg()
            .withDescription("use given directory for a serch path of plugins").create("plugin_dir");
    ops.addOption(pluginsPath);

    final Option plugins = OptionBuilder.withArgName("file").hasArg().withDescription("use given plugin file")
            .create("plugin");
    ops.addOption(plugins);

    ops.addOption("help", false, "show this help");

    try {

        final Parser parser = new BasicParser();
        final CommandLine cmd = parser.parse(ops, args);

        if (cmd.hasOption("help")) {

            final HelpFormatter help = new HelpFormatter();
            help.printHelp("nor", ops, true);
            System.exit(0);

        }

        // Configure about logging system.
        InputStream logStream;
        if (cmd.hasOption("log")) {

            logStream = new FileInputStream(cmd.getOptionValue("log"));

        } else {

            final String file = System.getProperty("nor.log", LoggindConfigFile);
            logStream = Nor.class.getResourceAsStream(file);

        }
        Logger.loadConfig(logStream);
        logStream.close();

        // Create the application instance by given config directory
        if (cmd.hasOption("config")) {

            Nor.nor = new Nor(cmd.getOptionValue("config"));

        } else {

            Nor.nor = new Nor(System.getProperty("nor.config", "config"));

        }

        // Load plugins
        final List<URL> pluginJar = new ArrayList<URL>();
        if (cmd.hasOption("plugin")) {

            for (final String filename : cmd.getOptionValues("plugin")) {

                final File f = new File(filename);
                pluginJar.add(f.toURI().toURL());

            }

        }
        if (cmd.hasOption("plugin_dir")) {

            for (final String dirname : cmd.getOptionValues("plugin_dir")) {

                final File dir = new File(dirname);
                if (dir.isDirectory()) {

                    for (final String filename : dir.list()) {

                        final File f = new File(dir, filename);
                        pluginJar.add(f.toURI().toURL());

                    }

                }

            }

        }
        nor.init(pluginJar);

        nor.start();

        // Waiting for end
        System.in.read();

        // Closing
        nor.close();

    } catch (final UnrecognizedOptionException e) {

        final HelpFormatter help = new HelpFormatter();
        help.printHelp("nor", ops, true);

    } catch (final Exception e) {

        LOGGER.catched(Level.SEVERE, "main", e);

    }

    LOGGER.info("main", "End.");

}

From source file:norbert.mynemo.ui.ImportCommandParser.java

/**
 * Parses and checks the given arguments, then calls
 * {@link FileImporter#convert(String, java.util.Collection, Optional, Optional, Optional, Optional)
 * FileImporter.convert()}./*from   w w w.  j a va2 s .  c om*/
 */
public static void parse(String[] args) throws ParseException, IOException {
    CommandLineParser parser = new BasicParser();

    Options options = getOptions();

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

    String outputFilepath = commandLine.getOptionValue(OUT_LONG_OPTION);
    String[] ratingsFilepaths = commandLine.getOptionValues(RATINGS_LONG_OPTION);
    String[] moviesFilepath = Optional.fromNullable(commandLine.getOptionValues(MOVIES_LONG_OPTION))
            .or(new String[0]);
    Optional<String> user = Optional.fromNullable(commandLine.getOptionValue(USER_LONG_OPTION));
    Optional<Integer> maxUsers = parseMaxUser(commandLine.getOptionValue(MAX_USERS_LONG_OPTION));
    Optional<Integer> minRatingsByMovie = parseMinRatingsByMovie(
            commandLine.getOptionValue(MIN_RATINGS_BY_MOVIE_LONG_OPTION));
    Optional<Integer> minCommonRatings = parseMinCommonRatings(
            commandLine.getOptionValue(MIN_COMMON_RATINGS_LONG_OPTION));
    Optional<UserSimilarityType> similarityType = parseSimilarityType(
            commandLine.getOptionValue(SIMILARITY_LONG_OPTION));

    check(outputFilepath, ratingsFilepaths, moviesFilepath, maxUsers, minCommonRatings, user, similarityType);

    FileImporter.convert(outputFilepath, Arrays.asList(ratingsFilepaths), Arrays.asList(moviesFilepath), user,
            maxUsers, minRatingsByMovie, minCommonRatings, similarityType);
}

From source file:norbert.mynemo.ui.RecommendCommandParser.java

/**
 * Parses and checks the given arguments, then runs the recommendation algorithm.
 *///ww w  .j a  v a 2s.  c om
public static void parse(String[] args)
        throws ParseException, IOException, TasteException, InterruptedException {

    CommandLine commandLine = new BasicParser().parse(getOptions(), args);

    // parse the options and create the data types
    RecommenderType algorithm = parseAlgorithm(commandLine.getOptionValue(ALGORITHM_CHAR_OPTION));
    long user = parseUser(commandLine.getOptionValue(USER_CHAR_OPTION));
    Integer recommendations = parseRecommendations(
            Optional.fromNullable(commandLine.getOptionValue(RECOMMENDATIONS_CHAR_OPTION)));
    Optional<Integer> features = parseFeatures(commandLine.getOptionValue(FEATURES_CHAR_OPTION));
    Optional<Integer> iterations = parseIterations(commandLine.getOptionValue(ITERATIONS_CHAR_OPTION));
    Optional<Integer> neighbors = parseNeighbors(commandLine.getOptionValue(NEIGHBORS_CHAR_OPTION));
    // loading the data model can be long, thus it is the last parsed option
    DataModel dataModel = parseDataModel(commandLine.getOptionValue(DATAMODEL_CHAR_OPTION));

    check(algorithm, dataModel, user, features, iterations, neighbors);

    execute(algorithm, dataModel, user, recommendations, features, iterations, neighbors);
}

From source file:norbert.mynemo.ui.ScrapeCommandParser.java

/**
 * Parses and checks the given arguments, then runs the scraper.
 *//*from  w ww .j  ava  2 s. c  o  m*/
public static void parse(String[] args)
        throws ParseException, IOException, TasteException, InterruptedException {

    CommandLine commandLine = new BasicParser().parse(getOptions(), args);

    // parse the options
    String outMoviesFilepath = commandLine.getOptionValue(OUT_MOVIES_LONG_OPTION);
    String outRatingsFilepath = commandLine.getOptionValue(OUT_RATINGS_LONG_OPTION);
    String[] inputFilepaths = commandLine.getOptionValues(IN_LONG_OPTION);
    List<String> userAgents = parseUserAgents(commandLine.getOptionValue(USERAGENTS_LONG_OPTION));
    String movieBlacklistFilepath = commandLine.getOptionValue(MOVIE_BLACKLIST_LONG_OPTION);
    String userBlacklistFilepath = commandLine.getOptionValue(USER_BLACKLIST_LONG_OPTION);

    // check
    check(outMoviesFilepath, outRatingsFilepath, inputFilepaths, movieBlacklistFilepath);

    // run
    execute(outMoviesFilepath, outRatingsFilepath, inputFilepaths, userAgents, movieBlacklistFilepath,
            userBlacklistFilepath);
}

From source file:norbert.mynemo.ui.SelectCommandParser.java

/**
 * Parses and checks the given arguments, runs the selection process and print the result.
 *///from w w  w  .  j  av a 2s .  c o  m
public static void parse(String[] args) throws ParseException, IOException, TasteException {

    CommandLine commandLine = new BasicParser().parse(getOptions(), args);

    // retrieve some option values
    String dataModelValue = commandLine.getOptionValue(DATAMODEL_LONG_OPTION);
    String userValue = commandLine.getOptionValue(USER_LONG_OPTION);

    // parse the option values
    Long user = parseUser(userValue);
    List<RecommenderType> algorithms = parseAlgorithms(commandLine.getOptionValues(ALGORITHMS_LONG_OPTION));
    MetricType metric = parseMetric(commandLine.getOptionValue(METRIC_LONG_OPTION));
    SpeedOption speed = parseSpeed(commandLine.getOptionValue(SPEED_LONG_OPTION));
    double coverage = parseCoverage(commandLine.getOptionValue(COVERAGE_LONG_OPTION));
    // loading the data model can be long, thus it is the last parsed option
    DataModel dataModel = parseDataModel(dataModelValue);

    // the parsing is finished, execute
    check(dataModel, user);
    Optional<RecommenderEvaluation> selection = select(dataModel, user, algorithms, metric, speed, coverage);
    printSelection(selection, dataModelValue, userValue);
}

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

public static void main(String[] args) {
    CommandLine line = null;//from www.j a va  2 s .co 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);
    }

    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;//from w  w w . j a  va  2 s .com
    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;/*w  ww .  java2s  . 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));
    }
}

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

public static void main(String[] args) {
    CommandLine line = null;//w w w . ja v  a2  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(RetrospectivelyAssignWorkflowTasks.class.getSimpleName(), 1, OPTIONS);
    }

    if (line == null || line.hasOption("h")) {
        ScriptUtils.printHelpAndExit(RetrospectivelyAssignWorkflowTasks.class.getSimpleName(), 0, OPTIONS);
    }
    if (!line.hasOption('e')) {
        System.err.println("Missing required parameter (e-mail address)");
        ScriptUtils.printHelpAndExit(RetrospectivelyAssignWorkflowTasks.class.getSimpleName(), 1, OPTIONS);
    }
    String email = line.getOptionValue('e');

    Context context = null;
    try {
        context = new Context();
        EPerson ePerson = EPerson.findByEmail(context, email);
        if (ePerson == null) {
            System.err.println("Couldn't find an account for e-mail address " + email);
            context.abort();
            return;
        }

        List<WorkflowItem> alreadyAccessibleTasks = new ArrayList<>();
        alreadyAccessibleTasks.addAll(WorkflowManager.getOwnedTasks(context, ePerson));
        alreadyAccessibleTasks.addAll(WorkflowManager.getPooledTasks(context, ePerson));

        WorkflowItem[] allTasks = WorkflowItem.findAll(context);
        for (WorkflowItem task : allTasks) {
            System.out.println("Processing task " + task.getID());
            if (alreadyAccessibleTasks.contains(task)) {
                System.out.println("EPerson already has access to this task");
                continue;
            }

            Collection collection = task.getCollection();
            boolean ePersonShouldSeeTask = checkIsMember(context, collection.getWorkflowGroup(1), ePerson)
                    || checkIsMember(context, collection.getWorkflowGroup(2), ePerson)
                    || checkIsMember(context, collection.getWorkflowGroup(3), ePerson);

            if (!ePersonShouldSeeTask) {
                System.out.println("EPerson isn't in any of the workflow groups for this task");
                continue;
            }

            System.out.println("Giving EPerson " + email + " access to workflow task " + task.getID());

            TableRow tr = DatabaseManager.row("tasklistitem");
            tr.setColumn("eperson_id", ePerson.getID());
            tr.setColumn("workflow_id", task.getID());
            DatabaseManager.insert(context, tr);
        }

        context.commit();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    } finally {
        if (context != null && context.isValid()) {
            context.abort();
        }
    }
}

From source file:oeg.licensius.core.Licensius.java

/**
 * Parses the command line parameters, invoking the proper methods
 *///from  w  w w  .j  a v  a  2s  . c o m
private static String parseCommandLineParams(String[] args) {
    StringBuilder res = new StringBuilder();
    CommandLineParser parser = null;
    CommandLine cli = null;
    try {
        Options options = new Options();
        options.addOption("help", false, "shows help (Help)");
        options.addOption("version", false, "shows the version info");
        options.addOption("nologs", false, "disables the logging funcionality");
        options.addOption("listlicenses", false,
                "shows the list of RDFLicenses available at http://rdflicense.linkeddata.es/. Takes no input. Output is json");
        options.addOption("legalcode", true,
                "shows the legal text of a license in English if available.  Input is RDFLicense URI. Output is json.");
        options.addOption("getinfolicense", true,
                "shows basic information of a license in json. Input is RDFLicense URI. Output is json.");
        options.addOption("findlicenseinrdf", true,
                "finds possible licenses in a RDF document. Input is URI pointing to an online RDF document. Output is json.");
        options.addOption("findlicenseintxt", true,
                "finds possible licenses in a TEXT document. Input is URI pointing to an online TXT document. Output is json.");
        options.addOption("isopen", true,
                "determines if a license is 'open' according to the http://www.opendefinition.com. Output is 'true' or 'false'");

        parser = new BasicParser();
        cli = parser.parse(options, args);

        ///HELP
        if (cli.hasOption("help") || (args.length == 0)) {
            new HelpFormatter().printHelp(Licensius.class.getCanonicalName(), options);
            return "";
        }

        ///NOLOGS
        if (cli.hasOption("nologs")) {
            initLoggerDisabled();
        } else {
            initLogger(true, true);
        }

        //VERSION
        // java -jar licensius-core.jar -version -nologs
        if (cli.hasOption("version")) {
            res.append(name + " version ").append(version).append("\n");
            res.append("Last compiled: ").append(SystemInformation.getCompileTimeStamp(Licensius.class))
                    .append(" en ").append(System.getenv("COMPUTERNAME")).append("\n");
            res.append("(C) 2016 Ontology Engineering Group (Universidad Politcnica de Madrid)").append("\n");
            res.append(SystemInformation.getSystemInfo());
        }

        //LEGALCODE
        // java -jar licensius-core.jar -legalcode http://purl.org/NET/rdflicense/ukogl-nc2.0
        if (cli.hasOption("legalcode")) {
            String uri = cli.getOptionValue("legalcode");
            RDFLicense lic = new RDFLicense(uri);
            res.append(lic.getLegalCode("en"));
        }

        //LISTLICENSES
        // java -jar licensius-core.jar -listlicences
        if (cli.hasOption("listlicenses")) {
            JSONArray array = new JSONArray();
            RDFLicenseDataset dataset = new RDFLicenseDataset();
            List<RDFLicense> list = dataset.listRDFLicenses();
            for (RDFLicense rdf : list) {
                String uri = rdf.getURI();
                if (uri != null) {
                    array.add(rdf.getURI());
                }
            }
            res.append(array.toJSONString());
        }

        //GETINFOLICENSE
        //java -jar licensius-core.jar -getinfolicense http://purl.org/NET/rdflicense/ukogl-nc2.0
        if (cli.hasOption("getinfolicense")) {
            String uri = cli.getOptionValue("getinfolicense");
            RDFLicense rdf = RDFLicenseDataset.getRDFLicense(uri);
            if (rdf == null) {
                res.append("License not found");
            } else {
                res.append(rdf.toLongJSON());
            }
        }

        //FINDLICENSEINRDF
        //java -jar licensius-core.jar -findlicenseinrdf http://purl.org/NET/p-plan
        if (cli.hasOption("findlicenseinrdf")) {
            String uri = cli.getOptionValue("findlicenseinrdf");
            LicenseFinder lf = new LicenseFinder();
            LicensiusResponse le = lf.findLicenseInRDF(uri);
            res.append(le.getJSON());
        }

        //FINDLICENSEINTXT
        //java -jar licensius-core.jar -findlicenseintxt https://github.com/pyvandenbussche/lov
        if (cli.hasOption("findlicenseintxt")) {
            String uri = cli.getOptionValue("findlicenseintxt");
            LicenseGuess lg = new LicenseGuess();
            String s = lg.licenseguessfromuri(uri);
            res.append(s);
        }

        //ISOPEN
        //java -jar licensius-core.jar -isopen http://purl.org/NET/rdflicense/ukogl-nc2.0
        if (cli.hasOption("isopen")) {
            String uri = cli.getOptionValue("isopen");
            RDFLicense lic = RDFLicenseDataset.getRDFLicense(uri);
            if (lic == null)
                res.append("License not found");
            else {
                RDFLicenseCheck check = new RDFLicenseCheck(lic);
                if (check.isOpen())
                    res.append("true");
                else
                    res.append("false");
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage());
    }

    return res.toString();
}