Example usage for java.lang String substring

List of usage examples for java.lang String substring

Introduction

In this page you can find the example usage for java.lang String substring.

Prototype

public String substring(int beginIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:hu.bme.mit.sette.run.Run.java

public static void main(String[] args) {
    LOG.debug("main() called");

    // parse properties
    Properties prop = new Properties();
    InputStream is = null;/*from  www  . ja  v a 2s. com*/

    try {
        is = new FileInputStream(SETTE_PROPERTIES);
        prop.load(is);
    } catch (IOException e) {
        System.err.println("Parsing  " + SETTE_PROPERTIES + " has failed");
        e.printStackTrace();
        System.exit(1);
    } finally {
        IOUtils.closeQuietly(is);
    }

    String[] basedirs = StringUtils.split(prop.getProperty("basedir"), '|');
    String snippetDir = prop.getProperty("snippet-dir");
    String snippetProject = prop.getProperty("snippet-project");
    String catgPath = prop.getProperty("catg");
    String catgVersionFile = prop.getProperty("catg-version-file");
    String jPETPath = prop.getProperty("jpet");
    String jPETDefaultBuildXml = prop.getProperty("jpet-default-build.xml");
    String jPETVersionFile = prop.getProperty("jpet-version-file");
    String spfPath = prop.getProperty("spf");
    String spfDefaultBuildXml = prop.getProperty("spf-default-build.xml");
    String spfVersionFile = prop.getProperty("spf-version-file");
    String outputDir = prop.getProperty("output-dir");

    Validate.notEmpty(basedirs, "At least one basedir must be specified in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetDir, "The property snippet-dir must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(snippetProject, "The property snippet-project must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(catgPath, "The property catg must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(jPETPath, "The property jpet must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(spfPath, "The property spf must be set in " + SETTE_PROPERTIES);
    Validate.notBlank(outputDir, "The property output-dir must be set in " + SETTE_PROPERTIES);

    String basedir = null;
    for (String bd : basedirs) {
        bd = StringUtils.trimToEmpty(bd);

        if (bd.startsWith("~")) {
            // Linux home
            bd = System.getProperty("user.home") + bd.substring(1);
        }

        FileValidator v = new FileValidator(new File(bd));
        v.type(FileType.DIRECTORY);

        if (v.isValid()) {
            basedir = bd;
            break;
        }
    }

    if (basedir == null) {
        System.err.println("basedir = " + Arrays.toString(basedirs));
        System.err.println("ERROR: No valid basedir was found, please check " + SETTE_PROPERTIES);
        System.exit(2);
    }

    BASEDIR = new File(basedir);
    SNIPPET_DIR = new File(basedir, snippetDir);
    SNIPPET_PROJECT = snippetProject;
    OUTPUT_DIR = new File(basedir, outputDir);

    try {
        String catgVersion = readToolVersion(new File(BASEDIR, catgVersionFile));
        if (catgVersion != null) {
            new CatgTool(new File(BASEDIR, catgPath), catgVersion);
        }

        String jPetVersion = readToolVersion(new File(BASEDIR, jPETVersionFile));
        if (jPetVersion != null) {
            new JPetTool(new File(BASEDIR, jPETPath), new File(BASEDIR, jPETDefaultBuildXml), jPetVersion);
        }

        String spfVersion = readToolVersion(new File(BASEDIR, spfVersionFile));
        if (spfVersion != null) {
            new SpfTool(new File(BASEDIR, spfPath), new File(BASEDIR, spfDefaultBuildXml), spfVersion);
        }

        // TODO stuff
        stuff(args);
    } catch (Exception e) {
        System.err.println(ExceptionUtils.getStackTrace(e));

        ValidatorException vex = (ValidatorException) e;

        for (ValidationException v : vex.getValidator().getAllExceptions()) {
            v.printStackTrace();
        }

        // System.exit(0);

        e.printStackTrace();
        System.err.println("==========");
        e.printStackTrace();

        if (e instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e).getFullMessage());
        } else if (e.getCause() instanceof ValidatorException) {
            System.err.println("Details:");
            System.err.println(((ValidatorException) e.getCause()).getFullMessage());
        }
    }
}

From source file:Counter.java

/** Main program entry point. */
public static void main(String argv[]) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from w w  w  .  j av a  2  s. co m
        System.exit(1);
    }

    // variables
    Counter counter = new Counter();
    PrintWriter out = new PrintWriter(System.out);
    ParserWrapper parser = null;
    int repetition = DEFAULT_REPETITION;
    boolean namespaces = DEFAULT_NAMESPACES;
    boolean validation = DEFAULT_VALIDATION;
    boolean schemaValidation = DEFAULT_SCHEMA_VALIDATION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean dynamicValidation = DEFAULT_DYNAMIC_VALIDATION;
    boolean xincludeProcessing = DEFAULT_XINCLUDE;
    boolean xincludeFixupBaseURIs = DEFAULT_XINCLUDE_FIXUP_BASE_URIS;
    boolean xincludeFixupLanguage = DEFAULT_XINCLUDE_FIXUP_LANGUAGE;

    // process arguments
    for (int i = 0; i < argv.length; i++) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = (ParserWrapper) Class.forName(parserName).newInstance();
                } catch (Exception e) {
                    parser = null;
                    System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                continue;
            }
            if (option.equalsIgnoreCase("n")) {
                namespaces = option.equals("n");
                continue;
            }
            if (option.equalsIgnoreCase("v")) {
                validation = option.equals("v");
                continue;
            }
            if (option.equalsIgnoreCase("s")) {
                schemaValidation = option.equals("s");
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("dv")) {
                dynamicValidation = option.equals("dv");
                continue;
            }
            if (option.equalsIgnoreCase("xi")) {
                xincludeProcessing = option.equals("xi");
                continue;
            }
            if (option.equalsIgnoreCase("xb")) {
                xincludeFixupBaseURIs = option.equals("xb");
                continue;
            }
            if (option.equalsIgnoreCase("xl")) {
                xincludeFixupLanguage = option.equals("xl");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
        }

        // use default parser?
        if (parser == null) {

            // create parser
            try {
                parser = (ParserWrapper) Class.forName(DEFAULT_PARSER_NAME).newInstance();
            } catch (Exception e) {
                System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
                continue;
            }
        }

        // set parser features
        try {
            parser.setFeature(NAMESPACES_FEATURE_ID, namespaces);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + NAMESPACES_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(VALIDATION_FEATURE_ID, validation);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_VALIDATION_FEATURE_ID, schemaValidation);
        } catch (SAXException e) {
            System.err
                    .println("warning: Parser does not support feature (" + SCHEMA_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            parser.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            parser.setFeature(DYNAMIC_VALIDATION_FEATURE_ID, dynamicValidation);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + DYNAMIC_VALIDATION_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FEATURE_ID, xincludeProcessing);
        } catch (SAXException e) {
            System.err.println("warning: Parser does not support feature (" + XINCLUDE_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID, xincludeFixupBaseURIs);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_BASE_URIS_FEATURE_ID + ")");
        }
        try {
            parser.setFeature(XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID, xincludeFixupLanguage);
        } catch (SAXException e) {
            System.err.println(
                    "warning: Parser does not support feature (" + XINCLUDE_FIXUP_LANGUAGE_FEATURE_ID + ")");
        }

        // parse file
        try {
            long beforeParse = System.currentTimeMillis();
            Document document = null;
            for (int j = 0; j < repetition; j++) {
                document = parser.parse(arg);
            }
            long afterParse = System.currentTimeMillis();
            long parse = afterParse - beforeParse;

            ParserWrapper.DocumentInfo documentInfo = parser.getDocumentInfo();
            counter.setDocumentInfo(documentInfo);

            long beforeTraverse1 = System.currentTimeMillis();
            counter.count(document);
            long afterTraverse1 = System.currentTimeMillis();
            long traverse1 = afterTraverse1 - beforeTraverse1;

            long beforeTraverse2 = System.currentTimeMillis();
            counter.count(document);
            long afterTraverse2 = System.currentTimeMillis();
            long traverse2 = afterTraverse2 - beforeTraverse2;
            counter.printResults(out, arg, parse, traverse1, traverse2, repetition);
        } catch (SAXParseException e) {
            // ignore
        } catch (Exception e) {
            System.err.println("error: Parse error occurred - " + e.getMessage());
            Exception se = e;
            if (e instanceof SAXException) {
                se = ((SAXException) e).getException();
            }
            if (se != null)
                se.printStackTrace(System.err);
            else
                e.printStackTrace(System.err);
        }
    }

}

From source file:com.netthreads.mavenize.Mavenize.java

/**
 * Main method.//ww  w .  j ava2  s . com
 * 
 * @param args
 */
public static void main(String[] args) {
    if (args.length > 1) {
        String sourcePath = "";
        String targetPath = "";
        String projectTypeName = ProjectType.Types.DEFAULT.toString();
        String version = PomGenerator.DEFAULT_VERSION;
        String packaging = PomGenerator.PACKAGE_TYPES[0];

        boolean isInput = false;
        boolean isOutput = false;
        for (String arg : args) {
            try {
                if (arg.startsWith(ARG_INPUT)) {
                    sourcePath = arg.substring(ARG_INPUT.length());
                    isInput = true;
                } else if (arg.startsWith(ARG_OUTPUT)) {
                    targetPath = arg.substring(ARG_OUTPUT.length());
                    isOutput = true;
                } else if (arg.startsWith(ARG_TYPE)) {
                    projectTypeName = arg.substring(ARG_TYPE.length());
                } else if (arg.startsWith(ARG_VERSION)) {
                    version = arg.substring(ARG_VERSION.length());
                } else if (arg.startsWith(ARG_PACKAGING)) {
                    packaging = arg.substring(ARG_PACKAGING.length());
                }
            } catch (Exception e) {
                logger.error("Can't process argument, " + arg + ", " + e.getMessage());
            }
        }

        // Project type.
        ProjectType projectType = ProjectTypeFactory.instance().getProjectType(projectTypeName);

        // Execute conversion.
        try {
            if (isInput && isOutput) {
                if (!sourcePath.equals(targetPath)) {
                    Mavenize mvnGather = new Mavenize(null);

                    mvnGather.process(sourcePath, targetPath, projectType, version, packaging);
                } else {
                    throw new MavenizeException("Input and output directories cannot be the same.");
                }
            } else {
                throw new MavenizeException("You must specify input and output directories");
            }
        } catch (MavenizeException e) {
            logger.error("Application error, " + e);
        } catch (IOException ioe) {
            logger.error("Application error, " + ioe);
        }
    } else {
        System.out.println(APP_MESSAGE + ARGS_MESSAGE);
    }
}

From source file:com.mgreau.jboss.as7.cli.CliLauncher.java

public static void main(String[] args) throws Exception {
    int exitCode = 0;
    CommandContext cmdCtx = null;//w w w. j  a  va2s.  c  o  m
    boolean gui = false;
    String appName = "";
    try {
        String argError = null;
        List<String> commands = null;
        File file = null;
        boolean connect = false;
        String defaultControllerProtocol = "http-remoting";
        String defaultControllerHost = null;
        int defaultControllerPort = -1;
        boolean version = false;
        String username = null;
        char[] password = null;
        int connectionTimeout = -1;

        //App deployment
        boolean isAppDeployment = false;
        final Properties props = new Properties();

        for (String arg : args) {
            if (arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                final String fullValue;
                final String value;
                if (arg.startsWith("--")) {
                    fullValue = arg.substring(13);
                } else {
                    fullValue = arg.substring(11);
                }
                final int protocolEnd = fullValue.lastIndexOf("://");
                if (protocolEnd == -1) {
                    value = fullValue;
                } else {
                    value = fullValue.substring(protocolEnd + 3);
                    defaultControllerProtocol = fullValue.substring(0, protocolEnd);
                }

                String portStr = null;
                int colonIndex = value.lastIndexOf(':');
                if (colonIndex < 0) {
                    // default port
                    defaultControllerHost = value;
                } else if (colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    final boolean hasPort;
                    int closeBracket = value.lastIndexOf(']');
                    if (closeBracket != -1) {
                        //possible ip v6
                        if (closeBracket > colonIndex) {
                            hasPort = false;
                        } else {
                            hasPort = true;
                        }
                    } else {
                        //probably ip v4
                        hasPort = true;
                    }
                    if (hasPort) {
                        defaultControllerHost = value.substring(0, colonIndex).trim();
                        portStr = value.substring(colonIndex + 1).trim();
                    } else {
                        defaultControllerHost = value;
                    }
                }

                if (portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if (port < 0) {
                            argError = "The port must be a valid non-negative integer: '" + args + "'";
                        } else {
                            defaultControllerPort = port;
                        }
                    } catch (NumberFormatException e) {
                        argError = "The port must be a valid non-negative integer: '" + arg + "'";
                    }
                }
            } else if ("--connect".equals(arg) || "-c".equals(arg)) {
                connect = true;
            } else if ("--version".equals(arg)) {
                version = true;
            } else if ("--gui".equals(arg)) {
                gui = true;
            } else if (arg.startsWith("--appDeployment=") || arg.startsWith("appDeployment=")) {
                isAppDeployment = true;
                appName = arg.startsWith("--") ? arg.substring(16) : arg.substring(14);
            } else if (arg.startsWith("--file=") || arg.startsWith("file=")) {
                if (file != null) {
                    argError = "Duplicate argument '--file'.";
                    break;
                }
                if (commands != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }

                final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                if (!fileName.isEmpty()) {
                    file = new File(fileName);
                    if (!file.exists()) {
                        argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                        break;
                    }
                } else {
                    argError = "Argument '--file' is missing value.";
                    break;
                }
            } else if (arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                commands = Util.splitCommands(value);
            } else if (arg.startsWith("--command=") || arg.startsWith("command=")) {
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                commands = Collections.singletonList(value);
            } else if (arg.startsWith("--user=")) {
                username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
            } else if (arg.startsWith("--password=")) {
                password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
            } else if (arg.startsWith("--timeout=")) {
                if (connectionTimeout > 0) {
                    argError = "Duplicate argument '--timeout'";
                    break;
                }
                final String value = arg.substring(10);
                try {
                    connectionTimeout = Integer.parseInt(value);
                } catch (final NumberFormatException e) {
                    //
                }
                if (connectionTimeout <= 0) {
                    argError = "The timeout must be a valid positive integer: '" + value + "'";
                }
            } else if (arg.equals("--help") || arg.equals("-h")) {
                commands = Collections.singletonList("help");
            } else if (arg.startsWith("--properties=")) {
                final String value = arg.substring(13);
                final File propertiesFile = new File(value);
                if (!propertiesFile.exists()) {
                    argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                    break;
                }

                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(propertiesFile);
                    props.load(fis);
                } catch (FileNotFoundException e) {
                    argError = e.getLocalizedMessage();
                    break;
                } catch (java.io.IOException e) {
                    argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": "
                            + e.getLocalizedMessage();
                    break;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (java.io.IOException e) {
                        }
                    }
                }
                for (final Object prop : props.keySet()) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            System.setProperty((String) prop, (String) props.get(prop));
                            return null;
                        }
                    });
                }
            } else if (!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                // assume it's commands
                if (file != null) {
                    argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: "
                            + arg;
                    break;
                }
                if (commands != null) {
                    argError = "Duplicate argument '--command'/'--commands'.";
                    break;
                }
                commands = Util.splitCommands(arg);
            }
        }

        if (argError != null) {
            System.err.println(argError);
            exitCode = 1;
            return;
        }

        if (version) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            VersionHandler.INSTANCE.handle(cmdCtx);
            return;
        }

        if (file != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processFile(file, cmdCtx, isAppDeployment, appName, props);
            return;
        }

        if (commands != null) {
            cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                    username, password, false, connect, connectionTimeout);
            processCommands(commands, cmdCtx);
            return;
        }

        // Interactive mode
        cmdCtx = initCommandContext(defaultControllerProtocol, defaultControllerHost, defaultControllerPort,
                username, password, true, connect, connectionTimeout);
        cmdCtx.interact();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 1;
    } finally {
        if (cmdCtx != null && cmdCtx.getExitCode() != 0) {
            exitCode = cmdCtx.getExitCode();
        }
        if (!gui) {
            System.exit(exitCode);
        }
    }
    System.exit(exitCode);
}

From source file:TmlCommandLine.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    long time = System.nanoTime();

    options = new Options();

    // Repository
    options.addOption(OptionBuilder.withDescription(
            "Full path of the repository folder, where TML will retrieve (or insert) documents. (e.g. /home/user/lucene).")
            .hasArg().withArgName("folder").isRequired().create("repo"));

    // Verbosity/*from  w  ww . j av  a  2 s  .  co  m*/
    options.addOption(
            OptionBuilder.withDescription("Verbose output in the console (it goes verbose to the log file).")
                    .hasArg(false).isRequired(false).create("v"));

    // Operation on corpus
    options.addOption(OptionBuilder.hasArg(false).withDescription("Performs an operation on a corpus.")
            .isRequired(false).create("O"));

    // The list of operations
    options.addOption(OptionBuilder.withDescription(
            "The list of operations you want to execute on the corpus. (e.g. PassageDistances,PassageSimilarity .")
            .hasArgs().withValueSeparator(',').withArgName("list").isRequired(false).withLongOpt("operations")
            .create());

    // The file to store the results
    options.addOption(OptionBuilder.withDescription("Folder where to store the results. (e.g. results/run01/).")
            .hasArg().withArgName("folder").isRequired(false).withLongOpt("oresults").create());

    // The corpus on which operate
    options.addOption(OptionBuilder.withDescription(
            "Lucene query that defines the corpus to operate with. (e.g. \"type:sentence AND reference:Document01\").")
            .hasArg().withArgName("query").isRequired(false).withLongOpt("ocorpus").create());

    // The corpus on which operate
    options.addOption(OptionBuilder.withDescription(
            "Use all documents in repository as single document corpora, it can be sentence or paragraph based. (e.g. sentence).")
            .hasArgs().withArgName("type").isRequired(false).withLongOpt("oalldocs").create());

    // The properties file for the corpus
    options.addOption(OptionBuilder.withDescription("Properties file with the corpus parameters (optional).")
            .hasArg().withArgName("parameter file").isRequired(false).withLongOpt("ocpar").create());

    // Background knowledge corpus
    options.addOption(OptionBuilder.withDescription(
            "Lucene query that defines a background knowledge on which the corpus will be projected. (e.g. \"type:sentences AND reference:Document*\").")
            .hasArg().withArgName("query").isRequired(false).withLongOpt("obk").create());

    // Background knowledge parameters
    options.addOption(OptionBuilder.withDescription(
            "Properties file with the background knowledge corpus parameters, if not set it will use the same as the corpus.")
            .hasArg().withArgName("parameter file").isRequired(false).withLongOpt("obkpar").create());

    // Term selection
    String criteria = "";
    for (TermSelection tsel : TermSelection.values()) {
        criteria += "," + tsel.name();
    }
    criteria = criteria.substring(1);
    options.addOption(OptionBuilder.hasArgs().withArgName("name")
            .withDescription("Name of the Term selection criteria (" + criteria + ").").isRequired(false)
            .withValueSeparator(',').withLongOpt("otsel").create());

    //   Term selection threshold
    options.addOption(OptionBuilder.hasArgs().withArgName("number")
            .withDescription("Threshold for the tsel criteria option.").withType(Integer.TYPE).isRequired(false)
            .withValueSeparator(',').withLongOpt("otselth").create());

    //   Dimensionality reduction
    criteria = "";
    for (DimensionalityReduction dim : DimensionalityReduction.values()) {
        criteria += "," + dim.name();
    }
    criteria = criteria.substring(1);
    options.addOption(OptionBuilder.hasArgs().withArgName("list")
            .withDescription("Name of the Dimensionality Reduction criteria. (e.g. " + criteria + ").")
            .isRequired(false).withValueSeparator(',').withLongOpt("odim").create());

    //   Dimensionality reduction threshold
    options.addOption(OptionBuilder.hasArgs().withArgName("list")
            .withDescription("Threshold for the dim options. (e.g. 0,1,2).").isRequired(false)
            .withValueSeparator(',').withLongOpt("odimth").create());

    //   Local weight
    criteria = "";
    for (LocalWeight weight : LocalWeight.values()) {
        criteria += "," + weight.name();
    }
    criteria = criteria.substring(1);
    options.addOption(OptionBuilder.hasArgs().withArgName("list")
            .withDescription("Name of the Local Weight to apply. (e.g." + criteria + ").").isRequired(false)
            .withValueSeparator(',').withLongOpt("otwl").create());

    //   Global weight
    criteria = "";
    for (GlobalWeight weight : GlobalWeight.values()) {
        criteria += "," + weight.name();
    }
    criteria = criteria.substring(1);
    options.addOption(OptionBuilder.hasArgs().withArgName("list")
            .withDescription("Name of the Global Weight to apply. (e.g. " + criteria + ").").isRequired(false)
            .withValueSeparator(',').withLongOpt("otwg").create());

    //   Use Lanczos
    options.addOption(OptionBuilder.hasArg(false).withDescription("Use Lanczos for SVD decomposition.")
            .isRequired(false).withLongOpt("olanczos").create());

    // Inserting documents in repository
    options.addOption(OptionBuilder.hasArg(false).withDescription("Insert documents into repository.")
            .isRequired(false).create("I"));

    // Max documents to insert
    options.addOption(OptionBuilder.hasArg().withArgName("number")
            .withDescription("Maximum number of documents to index or use in an operation.")
            .withType(Integer.TYPE).isRequired(false).withLongOpt("imaxdocs").create());

    // Clean repository
    options.addOption(
            OptionBuilder.hasArg(false).withDescription("Empties the repository before inserting new ones.")
                    .isRequired(false).withLongOpt("iclean").create());

    // Use annotator
    options.addOption(OptionBuilder.hasArgs()
            .withDescription(
                    "List of annotators to use when inserting the documents. (e.g. PennTreeAnnotator).")
            .isRequired(false).withValueSeparator(',').withLongOpt("iannotators").create());

    // Documents folder
    options.addOption(OptionBuilder.hasArg().withArgName("folder")
            .withDescription("The folder that contains the documens to insert.").isRequired(false)
            .withLongOpt("idocs").create());

    // Initializing the line parser
    CommandLineParser parser = new PosixParser();
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        printHelp(options);
        return;
    }

    // Validate that either inserting or an operation are given
    if (!line.hasOption("I") && !line.hasOption("O")) {
        System.out.println("One of the options -I or -O must be present.");
        printHelp(options);
        return;
    }

    repositoryFolder = line.getOptionValue("repo");

    try {
        if (line.hasOption("I")) {
            indexing();
        } else if (line.hasOption("O")) {
            operation();
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printHelp(options);
        return;
    }

    System.out.println("TML finished successfully in " + (System.nanoTime() - time) * 10E-9 + " seconds.");
    return;
}

From source file:edu.ku.brc.util.GeoRefConverter.java

/**
 * @param args//from  w  w  w. j ava2s. c om
 * @throws Exception 
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    String destFormat = GeoRefFormat.DMS_PLUS_MINUS.name();

    String[] inputStrings = new String[] {

            // +/- Deg Min Sec
            "//+/- Deg Min Sec", "0 0 0", "0 0 0.", "-32 45 16.8232", "-32d 45' 16.8232\"", "-32d45'16.8232\"",
            "-3245'16.8232\"", "-32 45' 16.82\"", "-32 45 16.82", "-32 45 6.8232", "-32 45 6.82",
            "-32 45 0.82", "-132 45 16.82151", "-132 45 6.82", "32 45 16.8232", "32 45 16.82", "32 45 6.8232",
            "32 45 6.82", "32 45 0.82", "132 45 16.82151", "132 45 6.82",

            // Deg Min Sec N/S/E/W
            "//Deg Min Sec N/S/E/W", "32 45 16.8232 N", "32 45 16.82 N", "32d45'16.82\" N", "32d45'16.82\"N",
            "32d 45' 16.82\" N", "32 45' 16.82\" N", "32 45 16.82 N", "32 45 6.8232 N", "32 45 6.82 N",
            "32 45 0.82 N", "132 45 16.82151 N", "132 45 6.82 N",

            "32 45 16.8232 S", "32 45 16.82 S", "32 45 6.8232 S", "32 45 6.82 S", "32 45 0.82 S",
            "132 45 16.82151 S", "132 45 6.82 S",

            "32 45 16.8232 E", "32 45 16.82 E", "32 45 6.8232 E", "32 45 6.82 E", "32 45 0.82 E",
            "132 45 16.82151 E", "132 45 6.82 E",

            "32 45 16.8232 W", "32 45 16.82 W", "32 45 6.8232 W", "32 45 6.82 W", "32 45 0.82 W",
            "132 45 16.82151 W", "132 45 6.82 W",

            // +/- Deg Min
            "//+/- Deg Min", "0 0", "0 0.", "-32 16.8232", "-32 16.82", "-32 16.82'", "-3216.82", "-32d 16",
            "-32 16.82", "-32 6.8232", "-32 6.82", "-32 0.82", "-132 16.82151", "-132 6.82", "32 16.8232",
            "32 16.82", "32 6.8232", "32 6.82", "32 0.82", "132 16.82151", "132 6.82",

            // Deg Min N/S/E/W
            "//Deg Min N/S/E/W", "32 16.8232 N", "32 16.82 N", "32 6.8232 N", "32 6.82 N", "32 0.82 N",
            "132 16.82151 N", "132 6.82 N",

            "32 16.8232 S", "32 16.82 S", "32 6.8232 S", "32 6.82 S", "32 0.82 S", "132 16.82151 S",
            "132 6.82 S",

            "32 16.8232 E", "32 16.82 E", "32 6.8232 E", "32 6.82 E", "32 0.82 E", "132 16.82151 E",
            "132 6.82 E",

            "32 16.8232 W", "32 16.82 W", "32 6.8232 W", "32 6.82 W", "32 0.82 W", "132 16.82151 W",
            "132 6.82 W",

            // +/- Decimal Degrees
            "//+/- Decimal Degrees", "0", "0.", "-16.8232", "-16.8232", "-16.82", "-6.8232", "-6.82", "-0.82",
            "-116.82151", "-116.82", "-1.82", "16.8232", "16.82", "6.8232", "6.82", "0.82", "116.82151",
            "116.82", "1.82",

            // Decimal Degrees N/S/E/W
            "//Decimal Degrees N/S/E/W", "16.8232 N", "16.82 N", "16.8232 N", "16.82 N", "16.8232N",
            "16.82N", "6.8232 N", "6.82 N", "0.82 N", "116.82151 N", "116.82 N", "1.82 N",

            "16.8232 S", "16.82 S", "6.8232 S", "6.82 S", "0.82 S", "116.82151 S", "116.82 S", "1.82 S",

            "16.8232 E", "16.82 E", "6.8232 E", "6.82 E", "0.82 E", "116.82151 E", "116.82 E", "1.82 E",

            "16.8232 W", "16.82 W", "6.8232 W", "6.82 W", "0.82 W", "116.82151 W", "116.82 W", "1.82 W",
            "41 43." };

    for (String input : inputStrings) {
        if (input.length() == 0) {
            continue;
        }

        if (input.startsWith("//")) {
            System.out.println();
            System.out.println("----------------------------------");
            System.out.println("----------------------------------");
            System.out.println(input.substring(2));
            System.out.println("----------------------------------");
            System.out.println("----------------------------------");
            continue;
        }

        System.out.println("Input:             " + input);
        BigDecimal degreesPlusMinus = null;
        for (GeoRefFormat format : GeoRefFormat.values()) {
            if (input.matches(format.regex)) {
                System.out.println("Format match:      " + format.name());
                degreesPlusMinus = format.convertToDecimalDegrees(input);
                break;
            }
        }

        // if we weren't able to find a matching format, throw an exception
        if (degreesPlusMinus == null) {
            System.out.println("No matching format found");
            System.out.println("----------------------------------");
            continue;
        }

        int decimalFmtLen = 0;
        int decIndex = input.lastIndexOf('.');
        if (decIndex > -1 && input.length() > decIndex) {
            decimalFmtLen = input.length() - decIndex;
        }

        String convertedVal = null;
        if (destFormat == GeoRefFormat.DMS_PLUS_MINUS.name()) {
            convertedVal = LatLonConverter.convertToSignedDDMMSS(degreesPlusMinus,
                    Math.min(LatLonConverter.DDMMSS_LEN, decimalFmtLen));
        } else if (destFormat == GeoRefFormat.DM_PLUS_MINUS.name()) {
            convertedVal = LatLonConverter.convertToSignedDDMMMM(degreesPlusMinus,
                    Math.min(LatLonConverter.DDMMMM_LEN, decimalFmtLen));
        } else if (destFormat == GeoRefFormat.D_PLUS_MINUS.name()) {
            convertedVal = LatLonConverter.convertToSignedDDDDDD(degreesPlusMinus,
                    Math.min(LatLonConverter.DDDDDD_LEN, decimalFmtLen));
        }

        System.out.println("Converted value:   " + convertedVal);
        System.out.println("----------------------------------");
    }

    GeoRefConverter converter = new GeoRefConverter();
    for (String input : inputStrings) {
        if (input.length() == 0) {
            continue;
        }

        if (input.startsWith("//")) {
            System.out.println();
            System.out.println("----------------------------------");
            System.out.println("----------------------------------");
            System.out.println(input.substring(2));
            System.out.println("----------------------------------");
            System.out.println("----------------------------------");
            continue;
        }

        System.out.println("Input:             " + input);
        String decimalDegrees = converter.convert(input, GeoRefConverter.GeoRefFormat.D_PLUS_MINUS.name());
        System.out.println("Decimal degrees:   " + decimalDegrees);
    }
    System.out.println("----------------------------------");
    System.out.println("----------------------------------");
    System.out.println("----------------------------------");
    System.out.println("----------------------------------");
    System.out.println("----------------------------------");
    System.out.println("----------------------------------");
    System.out.println("----------------------------------");
    System.out.println("----------------------------------");

    String problemString = "41 43 18.";
    System.out.println("input: " + problemString);
    String d = converter.convert(problemString, GeoRefFormat.D_PLUS_MINUS.name());
    String dm = converter.convert(problemString, GeoRefFormat.DM_PLUS_MINUS.name());
    String dms = converter.convert(problemString, GeoRefFormat.DMS_PLUS_MINUS.name());
    System.out.println(d + "   :   " + dm + "   :   " + dms);

    problemString = d;
    System.out.println("input: " + problemString);
    String d2 = converter.convert(problemString, GeoRefFormat.D_PLUS_MINUS.name());
    String dm2 = converter.convert(problemString, GeoRefFormat.DM_PLUS_MINUS.name());
    String dms2 = converter.convert(problemString, GeoRefFormat.DMS_PLUS_MINUS.name());
    System.out.println(d2 + "   :   " + dm2 + "   :   " + dms2);

    problemString = dm;
    System.out.println("input: " + problemString);
    String d3 = converter.convert(problemString, GeoRefFormat.D_PLUS_MINUS.name());
    String dm3 = converter.convert(problemString, GeoRefFormat.DM_PLUS_MINUS.name());
    String dms3 = converter.convert(problemString, GeoRefFormat.DMS_PLUS_MINUS.name());
    System.out.println(d3 + "   :   " + dm3 + "   :   " + dms3);
}

From source file:TypeInfoWriter.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from   w w  w. ja v  a2  s.  c o m
        System.exit(1);
    }

    // variables
    XMLReader parser = null;
    Vector schemas = null;
    Vector instances = null;
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;

    // process arguments
    for (int i = 0; i < argv.length; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("p")) {
                // get parser name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -p option.");
                    continue;
                }
                String parserName = argv[i];

                // create parser
                try {
                    parser = XMLReaderFactory.createXMLReader(parserName);
                } catch (Exception e) {
                    try {
                        Parser sax1Parser = ParserFactory.makeParser(parserName);
                        parser = new ParserAdapter(sax1Parser);
                        System.err.println("warning: Features and properties not supported on SAX1 parsers.");
                    } catch (Exception ex) {
                        parser = null;
                        System.err.println("error: Unable to instantiate parser (" + parserName + ")");
                        e.printStackTrace(System.err);
                        System.exit(1);
                    }
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: schema documents
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    // use default parser?
    if (parser == null) {
        // create parser
        try {
            parser = XMLReaderFactory.createXMLReader(DEFAULT_PARSER_NAME);
        } catch (Exception e) {
            System.err.println("error: Unable to instantiate parser (" + DEFAULT_PARSER_NAME + ")");
            e.printStackTrace(System.err);
            System.exit(1);
        }
    }

    try {
        // Create writer
        TypeInfoWriter writer = new TypeInfoWriter();
        writer.setOutput(System.out, "UTF8");

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(writer);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        if (schemas != null && schemas.size() > 0) {
            final int length = schemas.size();
            StreamSource[] sources = new StreamSource[length];
            for (int j = 0; j < length; ++j) {
                sources[j] = new StreamSource((String) schemas.elementAt(j));
            }
            schema = factory.newSchema(sources);
        } else {
            schema = factory.newSchema();
        }

        // Setup validator and parser
        ValidatorHandler validator = schema.newValidatorHandler();
        parser.setContentHandler(validator);
        if (validator instanceof DTDHandler) {
            parser.setDTDHandler((DTDHandler) validator);
        }
        parser.setErrorHandler(writer);
        validator.setContentHandler(writer);
        validator.setErrorHandler(writer);
        writer.setTypeInfoProvider(validator.getTypeInfoProvider());

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents and print type information
        if (instances != null && instances.size() > 0) {
            final int length = instances.size();
            for (int j = 0; j < length; ++j) {
                parser.parse((String) instances.elementAt(j));
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}

From source file:InstallJars.java

/**
 * Main command line entry point.//w w  w .j a  v  a  2  s . co  m
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    String propName = null;
    boolean expand = true;
    boolean verbose = true;
    boolean run = true;
    String params = "cmd /c java";
    // process arguments
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.charAt(0) == '-') { // switch
            arg = arg.substring(1);
            if (arg.equalsIgnoreCase("quiet")) {
                verbose = false;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
            } else if (arg.equalsIgnoreCase("expand")) {
                expand = true;
            } else if (arg.equalsIgnoreCase("noexpand")) {
                expand = false;
            } else if (arg.equalsIgnoreCase("run")) {
                run = true;
            } else if (arg.equalsIgnoreCase("norun")) {
                run = false;
            } else if (arg.equalsIgnoreCase("java")) {
                run = false;
                if (i < args.length - 1) {
                    params = args[++i];
                }
            } else {
                System.err.println("Invalid switch - " + arg);
                System.exit(1);
            }
        } else {
            if (propName == null) {
                propName = arg;
            } else {
                System.err.println("Too many parameters - " + arg);
                System.exit(1);
            }
        }
    }
    if (propName == null) {
        propName = "InstallJars.properties";
    }
    // do the install
    try {
        InstallJars ij = new InstallJars(expand, verbose, run, propName, params);
        ij.printUsage();
        String cp = ij.install();
        System.out.println("\nRecomended additions to your classpath - " + cp);
    } catch (Exception e) {
        System.err.println("\n" + e.getClass().getName() + ": " + e.getMessage());
        if (verbose) {
            e.printStackTrace(); // *** debug ***
        }
        System.exit(2);
    }
}

From source file:com.mgmtp.jfunk.core.JFunk.java

/**
 * Starts jFunk.//from w w w  .jav a  2 s .  c o m
 * 
 * <pre>
 * -threadcount=&lt;count&gt;    Optional    Number of threads to be used. Allows for parallel
 *                                     execution of test scripts.
 * -parallel               Optional    Allows a single script to be executed in parallel
 *                                     depending on the number of threads specified. The
 *                                     argument is ignored if multiple scripts are specified.
 * &lt;script parameters&gt     Optional    Similar to Java system properties they can be provided
 *                                     as key-value-pairs preceded by -S, e.g. -Skey=value.
 *                                     These parameters are then available in the script as
 *                                     Groovy variables.
 * &lt;script(s)&gt;             Required    At least one test script must be specified.
 *
 * Example:
 * java -cp &lt;jFunkClasspath&gt; com.mgmtp.jfunk.core.JFunk -Skey=value -threadcount=4 -parallel mytest.script
 * </pre>
 * 
 * @param args
 *            The program arguments.
 */
public static void main(final String[] args) {
    SLF4JBridgeHandler.install();

    boolean exitWithError = true;
    StopWatch stopWatch = new StopWatch();

    try {
        RESULT_LOG.info("jFunk started");
        stopWatch.start();

        int threadCount = 1;
        boolean parallel = false;
        Properties scriptProperties = new Properties();
        List<File> scripts = Lists.newArrayList();

        for (String arg : args) {
            if (arg.startsWith("-threadcount")) {
                String[] split = arg.split("=");
                Preconditions.checkArgument(split.length == 2,
                        "The number of threads must be specified as follows: -threadcount=<value>");
                threadCount = Integer.parseInt(split[1]);
                RESULT_LOG.info("Using " + threadCount + (threadCount == 1 ? " thread" : " threads"));
            } else if (arg.startsWith("-S")) {
                arg = arg.substring(2);
                String[] split = arg.split("=");
                Preconditions.checkArgument(split.length == 2,
                        "Script parameters must be given in the form -S<name>=<value>");
                scriptProperties.setProperty(split[0], normalizeScriptParameterValue(split[1]));
                RESULT_LOG.info("Using script parameter " + split[0] + " with value " + split[1]);
            } else if (arg.equals("-parallel")) {
                parallel = true;
                RESULT_LOG.info("Using parallel mode");
            } else {
                scripts.add(new File(arg));
            }
        }

        if (scripts.isEmpty()) {
            scripts.addAll(requestScriptsViaGui());

            if (scripts.isEmpty()) {
                RESULT_LOG.info("Execution finished (took " + stopWatch + " H:mm:ss.SSS)");
                System.exit(0);
            }
        }

        String propsFileName = System.getProperty("jfunk.props.file", "jfunk.properties");
        Module module = ModulesLoader.loadModulesFromProperties(new JFunkDefaultModule(), propsFileName);
        Injector injector = Guice.createInjector(module);

        JFunkFactory factory = injector.getInstance(JFunkFactory.class);
        JFunkBase jFunk = factory.create(threadCount, parallel, scripts, scriptProperties);
        jFunk.execute();

        exitWithError = false;
    } catch (JFunkExecutionException ex) {
        // no logging necessary
    } catch (Exception ex) {
        Logger.getLogger(JFunk.class).error("jFunk terminated unexpectedly.", ex);
    } finally {
        stopWatch.stop();
        RESULT_LOG.info("Execution finished (took " + stopWatch + " H:mm:ss.SSS)");
    }

    System.exit(exitWithError ? -1 : 0);
}

From source file:InlineSchemaValidator.java

/** Main program entry point. */
public static void main(String[] argv) {

    // is there anything to do?
    if (argv.length == 0) {
        printUsage();//from  w w  w  . j  av a  2  s  .c o  m
        System.exit(1);
    }

    // variables
    Vector schemas = null;
    Vector instances = null;
    HashMap prefixMappings = null;
    HashMap uriMappings = null;
    String docURI = argv[argv.length - 1];
    String schemaLanguage = DEFAULT_SCHEMA_LANGUAGE;
    int repetition = DEFAULT_REPETITION;
    boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING;
    boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS;
    boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS;
    boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS;
    boolean memoryUsage = DEFAULT_MEMORY_USAGE;

    // process arguments
    for (int i = 0; i < argv.length - 1; ++i) {
        String arg = argv[i];
        if (arg.startsWith("-")) {
            String option = arg.substring(1);
            if (option.equals("l")) {
                // get schema language name
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -l option.");
                } else {
                    schemaLanguage = argv[i];
                }
                continue;
            }
            if (option.equals("x")) {
                if (++i == argv.length) {
                    System.err.println("error: Missing argument to -x option.");
                    continue;
                }
                String number = argv[i];
                try {
                    int value = Integer.parseInt(number);
                    if (value < 1) {
                        System.err.println("error: Repetition must be at least 1.");
                        continue;
                    }
                    repetition = value;
                } catch (NumberFormatException e) {
                    System.err.println("error: invalid number (" + number + ").");
                }
                continue;
            }
            if (arg.equals("-a")) {
                // process -a: xpath expressions for schemas
                if (schemas == null) {
                    schemas = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    schemas.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-i")) {
                // process -i: xpath expressions for instance documents
                if (instances == null) {
                    instances = new Vector();
                }
                while (i + 1 < argv.length - 1 && !(arg = argv[i + 1]).startsWith("-")) {
                    instances.add(arg);
                    ++i;
                }
                continue;
            }
            if (arg.equals("-nm")) {
                String prefix;
                String uri;
                while (i + 2 < argv.length - 1 && !(prefix = argv[i + 1]).startsWith("-")
                        && !(uri = argv[i + 2]).startsWith("-")) {
                    if (prefixMappings == null) {
                        prefixMappings = new HashMap();
                        uriMappings = new HashMap();
                    }
                    prefixMappings.put(prefix, uri);
                    HashSet prefixes = (HashSet) uriMappings.get(uri);
                    if (prefixes == null) {
                        prefixes = new HashSet();
                        uriMappings.put(uri, prefixes);
                    }
                    prefixes.add(prefix);
                    i += 2;
                }
                continue;
            }
            if (option.equalsIgnoreCase("f")) {
                schemaFullChecking = option.equals("f");
                continue;
            }
            if (option.equalsIgnoreCase("hs")) {
                honourAllSchemaLocations = option.equals("hs");
                continue;
            }
            if (option.equalsIgnoreCase("va")) {
                validateAnnotations = option.equals("va");
                continue;
            }
            if (option.equalsIgnoreCase("ga")) {
                generateSyntheticAnnotations = option.equals("ga");
                continue;
            }
            if (option.equalsIgnoreCase("m")) {
                memoryUsage = option.equals("m");
                continue;
            }
            if (option.equals("h")) {
                printUsage();
                continue;
            }
            System.err.println("error: unknown option (" + option + ").");
            continue;
        }
    }

    try {
        // Create new instance of inline schema validator.
        InlineSchemaValidator inlineSchemaValidator = new InlineSchemaValidator(prefixMappings, uriMappings);

        // Parse document containing schemas and validation roots
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(inlineSchemaValidator);
        Document doc = db.parse(docURI);

        // Create XPath factory for selecting schema and validation roots
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        xpath.setNamespaceContext(inlineSchemaValidator);

        // Select schema roots from the DOM
        NodeList[] schemaNodes = new NodeList[schemas != null ? schemas.size() : 0];
        for (int i = 0; i < schemaNodes.length; ++i) {
            XPathExpression xpathSchema = xpath.compile((String) schemas.elementAt(i));
            schemaNodes[i] = (NodeList) xpathSchema.evaluate(doc, XPathConstants.NODESET);
        }

        // Select validation roots from the DOM
        NodeList[] instanceNodes = new NodeList[instances != null ? instances.size() : 0];
        for (int i = 0; i < instanceNodes.length; ++i) {
            XPathExpression xpathInstance = xpath.compile((String) instances.elementAt(i));
            instanceNodes[i] = (NodeList) xpathInstance.evaluate(doc, XPathConstants.NODESET);
        }

        // Create SchemaFactory and configure
        SchemaFactory factory = SchemaFactory.newInstance(schemaLanguage);
        factory.setErrorHandler(inlineSchemaValidator);

        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: SchemaFactory does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: SchemaFactory does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: SchemaFactory does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: SchemaFactory does not support feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Build Schema from sources
        Schema schema;
        {
            DOMSource[] sources;
            int size = 0;
            for (int i = 0; i < schemaNodes.length; ++i) {
                size += schemaNodes[i].getLength();
            }
            sources = new DOMSource[size];
            if (size == 0) {
                schema = factory.newSchema();
            } else {
                int count = 0;
                for (int i = 0; i < schemaNodes.length; ++i) {
                    NodeList nodeList = schemaNodes[i];
                    int nodeListLength = nodeList.getLength();
                    for (int j = 0; j < nodeListLength; ++j) {
                        sources[count++] = new DOMSource(nodeList.item(j));
                    }
                }
                schema = factory.newSchema(sources);
            }
        }

        // Setup validator and input source.
        Validator validator = schema.newValidator();
        validator.setErrorHandler(inlineSchemaValidator);

        try {
            validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + SCHEMA_FULL_CHECKING_FEATURE_ID + ")");
        }
        try {
            validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations);
        } catch (SAXNotRecognizedException e) {
            System.err.println(
                    "warning: Validator does not recognize feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + HONOUR_ALL_SCHEMA_LOCATIONS_ID + ")");
        }
        try {
            validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err
                    .println("warning: Validator does not recognize feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println("warning: Validator does not support feature (" + VALIDATE_ANNOTATIONS_ID + ")");
        }
        try {
            validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations);
        } catch (SAXNotRecognizedException e) {
            System.err.println("warning: Validator does not recognize feature ("
                    + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        } catch (SAXNotSupportedException e) {
            System.err.println(
                    "warning: Validator does not support feature (" + GENERATE_SYNTHETIC_ANNOTATIONS_ID + ")");
        }

        // Validate instance documents
        for (int i = 0; i < instanceNodes.length; ++i) {
            NodeList nodeList = instanceNodes[i];
            int nodeListLength = nodeList.getLength();
            for (int j = 0; j < nodeListLength; ++j) {
                DOMSource source = new DOMSource(nodeList.item(j));
                source.setSystemId(docURI);
                inlineSchemaValidator.validate(validator, source, docURI, repetition, memoryUsage);
            }
        }
    } catch (SAXParseException e) {
        // ignore
    } catch (Exception e) {
        System.err.println("error: Parse error occurred - " + e.getMessage());
        if (e instanceof SAXException) {
            Exception nested = ((SAXException) e).getException();
            if (nested != null) {
                e = nested;
            }
        }
        e.printStackTrace(System.err);
    }
}