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

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

Introduction

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

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:com.aliyun.odps.mapred.bridge.streaming.StreamJob.java

void parseArgv() {
    CommandLine cmdLine = null;
    try {/* w w  w. j a  v a  2 s .  c  o m*/
        cmdLine = parser.parse(allOptions, argv_);
    } catch (Exception oe) {
        LOG.error(oe.getMessage());
        exitUsage(argv_.length > 0 && "-info".equals(argv_[0]));
    }

    if (cmdLine == null) {
        exitUsage(argv_.length > 0 && "-info".equals(argv_[0]));
        return;
    }

    @SuppressWarnings("unchecked")
    List<String> args = cmdLine.getArgList();
    if (args != null && args.size() > 0) {
        fail("Found " + args.size() + " unexpected arguments on the " + "command line " + args);
    }

    detailedUsage_ = cmdLine.hasOption("info");
    if (cmdLine.hasOption("help") || detailedUsage_) {
        printUsage = true;
        return;
    }
    verbose_ = cmdLine.hasOption("verbose");
    background_ = cmdLine.hasOption("background");
    debug_ = cmdLine.hasOption("debug") ? debug_ + 1 : debug_;

    output_ = cmdLine.getOptionValue("output");

    comCmd_ = cmdLine.getOptionValue("combiner");
    redCmd_ = cmdLine.getOptionValue("reducer");

    lazyOutput_ = cmdLine.hasOption("lazyOutput");

    String[] values = cmdLine.getOptionValues("file");
    SessionState ss = SessionState.get();
    MetaExplorer metaExplorer = new MetaExplorerImpl(ss.getOdps());
    Map<String, String> aliasToTempResource = new HashMap<String, String>();
    String padding = "_" + UUID.randomUUID().toString();
    if (values != null && values.length > 0) {
        for (int i = 0; i < values.length; i++) {
            String file = values[i];
            packageFiles_.add(file);
            try {
                aliasToTempResource.put(FilenameUtils.getName(file),
                        metaExplorer.addFileResourceWithRetry(file, Resource.Type.FILE, padding, true));
            } catch (OdpsException e) {
                throw new RuntimeException(e);
            }
        }

        config_.set("stream.temp.resource.alias", JSON.toJSONString(aliasToTempResource));

        String[] res = config_.getResources();
        Set<String> resources = aliasToTempResource.keySet();
        if (res != null) {
            config_.setResources(StringUtils.join(res, ",") + "," + StringUtils.join(resources, ","));
        } else {
            config_.setResources(StringUtils.join(resources, ","));
        }
    }

    additionalConfSpec_ = cmdLine.getOptionValue("additionalconfspec");
    numReduceTasksSpec_ = cmdLine.getOptionValue("numReduceTasks");
    partitionerSpec_ = cmdLine.getOptionValue("partitioner");
    mapDebugSpec_ = cmdLine.getOptionValue("mapdebug");
    reduceDebugSpec_ = cmdLine.getOptionValue("reducedebug");
    ioSpec_ = cmdLine.getOptionValue("io");

    String[] car = cmdLine.getOptionValues("cacheArchive");
    if (null != car) {
        fail("no -cacheArchive option any more, please use -resources instead.");
    }

    String[] caf = cmdLine.getOptionValues("cacheFile");
    if (null != caf) {
        fail("no -cacheFile option any more, please use -resources instead.");
    }

    mapCmd_ = cmdLine.getOptionValue("mapper");

    String[] cmd = cmdLine.getOptionValues("cmdenv");
    if (null != cmd && cmd.length > 0) {
        for (String s : cmd) {
            if (addTaskEnvironment_.length() > 0) {
                addTaskEnvironment_ += " ";
            }
            addTaskEnvironment_ += s;
        }
    }

    // per table input config
    Map<String, Map<String, String>> inputConfigs = new HashMap<String, Map<String, String>>();
    String[] columns = null;

    for (Option opt : cmdLine.getOptions()) {
        if ("jobconf".equals(opt.getOpt())) {
            String[] jobconf = opt.getValues();
            if (null != jobconf && jobconf.length > 0) {
                for (String s : jobconf) {
                    String[] parts = s.split("=", 2);
                    config_.set(parts[0], parts[1]);
                }
            }
        } else if ("columns".equals(opt.getOpt())) {
            String columnsValue = opt.getValue();
            if (columnsValue.equals("ALL")) {
                columns = null;
            } else {
                columns = columnsValue.split(",");
            }
        } else if ("input".equals(opt.getOpt())) {
            values = opt.getValues();
            if (values != null && values.length > 0) {
                for (String input : values) {
                    TableInfo ti = parseTableInfo(input);
                    if (columns != null) {
                        ti.setCols(columns);
                    }
                    inputSpecs_.add(ti);

                    String inputKey = (ti.getProjectName() + "." + ti.getTableName()).toLowerCase();
                    // XXX only apply once per table
                    if (inputConfigs.get(inputKey) != null) {
                        continue;
                    }

                    Map<String, String> inputConfig = new HashMap<String, String>();
                    inputConfig.put("stream.map.input.field.separator",
                            config_.get("stream.map.input.field.separator", "\t"));
                    // TODO other per table input config: cols, etc.
                    inputConfigs.put(inputKey, inputConfig);
                }
            }
        }
    }
    try {
        config_.set("stream.map.input.configs", JSON.toJSONString(inputConfigs));
    } catch (Exception e) {
        throw new RuntimeException("fail to set input configs");
    }
}

From source file:com.archivas.clienttools.arcmover.cli.ArcCopy.java

protected void parseArgs() throws ParseException {

    // create the command cmdLine parser
    CommandLineParser parser = new PosixParser();
    CommandLine cmdLine;

    // parse the command cmdLine arguments
    cmdLine = parser.parse(getOptions(), getArgs());

    // Help//from  www .j  a  v  a  2 s  .  c o  m
    printHelp = cmdLine.hasOption("h");
    if (printHelp) {
        return;
    }

    initializeProfiles(cmdLine.hasOption("insecure"));

    // See how we are getting the input list: file or from stdin
    @SuppressWarnings({ "unchecked" })
    List<String> argList = cmdLine.getArgList();

    // Handle the load schedule and export lists
    LoadSchedule schedule = LoadSchedule.getDefaultLoadSchedule();
    getLoadSchedule(cmdLine, schedule);
    setUpExportListThread(cmdLine);

    // See if we are rerunning, set up the job if we are
    boolean rerunning = handleRerunAndResume(cmdLine, schedule);

    if (rerunning) {
        List<String> extraOptions = new ArrayList<String>();
        if (cmdLine.hasOption(DESTINATION_PROFILE_OPTION)) {
            extraOptions.add(DESTINATION_PROFILE_OPTION);
        }
        if (cmdLine.hasOption(SOURCE_PROFILE_OPTION)) {
            extraOptions.add(SOURCE_PROFILE_OPTION);
        }
        if (cmdLine.hasOption(DESTINATION_PATH_OPTION)) {
            extraOptions.add(DESTINATION_PATH_OPTION);
        }
        if (cmdLine.hasOption(SOURCE_PATH_OPTION)) {
            extraOptions.add(SOURCE_PATH_OPTION);
        }
        if (cmdLine.hasOption(JOB_NAME)) {
            extraOptions.add(JOB_NAME);
        }
        if (cmdLine.hasOption(HOLD_OPTION)) {
            extraOptions.add(HOLD_OPTION);
        }
        if (cmdLine.hasOption(INDEX_OPTION)) {
            extraOptions.add(INDEX_OPTION);
        }
        if (cmdLine.hasOption(SHRED_OPTION)) {
            extraOptions.add(SHRED_OPTION);
        }
        if (cmdLine.hasOption(RETENTION_OPTION)) {
            extraOptions.add(RETENTION_OPTION);
        }
        if (cmdLine.hasOption(UID_OPTION)) {
            extraOptions.add(UID_OPTION);
        }
        if (cmdLine.hasOption(GID_OPTION)) {
            extraOptions.add(GID_OPTION);
        }
        if (cmdLine.hasOption(FILE_PERMS_OPTION)) {
            extraOptions.add(FILE_PERMS_OPTION);
        }
        if (cmdLine.hasOption(DIR_PERMS_OPTION)) {
            extraOptions.add(DIR_PERMS_OPTION);
        }
        if (cmdLine.hasOption(CUSTOM_METADATA_OPTION)) {
            extraOptions.add(CUSTOM_METADATA_OPTION);
        }
        if (cmdLine.hasOption(ACL_OPTION)) {
            extraOptions.add(ACL_OPTION);
        }
        if (cmdLine.hasOption(OWNER_OPTION)) {
            extraOptions.add(OWNER_OPTION);
        }
        if (cmdLine.hasOption(DOMAIN_OPTION)) {
            extraOptions.add(DOMAIN_OPTION);
        }
        if (cmdLine.hasOption(IGNORE_CONFLICTS)) {
            extraOptions.add(IGNORE_CONFLICTS);
        }
        if (!extraOptions.isEmpty()) {
            throw new ParseException("The following supplied options are not allowed with --" + RESUME
                    + " or --" + RERUN + ": " + extraOptions);
        }
        // The list_file is not allowed for rerun/resume
        if (argList.size() > numCmdLineArgs - 1) {
            throw new ParseException(
                    "The list_file argument is not allowed with --" + RESUME + " or --" + RERUN);
        }

    } else {
        if (argList.size() != numCmdLineArgs) {
            throw new ParseException("Missing argument list_file.");
        }

        String listFileName = argList.get(numCmdLineArgs - 1);

        // Required fields
        List<String> missingRequiredOptions = new ArrayList<String>();
        if (!cmdLine.hasOption("s")) {
            missingRequiredOptions.add("s");
        }
        if (!cmdLine.hasOption("d")) {
            missingRequiredOptions.add("d");
        }
        if (!cmdLine.hasOption(DESTINATION_PATH_OPTION)) {
            missingRequiredOptions.add(DESTINATION_PATH_OPTION);
        }

        // Print a friendly string if we are missing more than one require options
        if (missingRequiredOptions.size() > 1) {
            throw new ParseException("Missing required options: " + missingRequiredOptions);
        }

        // Parse require options
        String srcProfileName = getProfileNameFromCmdLineAndValidateExistance(cmdLine, "s");
        String tarProfileName = getProfileNameFromCmdLineAndValidateExistance(cmdLine, "d");
        AbstractProfileBase srcProfile = ProfileManager.getProfileByName(srcProfileName);
        AbstractProfileBase dstProfile = ProfileManager.getProfileByName(tarProfileName);
        String targetPath = validateTargetPath(cmdLine);

        // Optional fields
        String sourcePath = null;
        if (cmdLine.hasOption(SOURCE_PATH_OPTION)) {
            sourcePath = cmdLine.getOptionValue(SOURCE_PATH_OPTION);
        }

        String jobName = null;
        if (cmdLine.hasOption(JOB_NAME)) {
            jobName = cmdLine.getOptionValue(JOB_NAME);
        }

        FileMetadata metadata = new FileMetadata();

        // We ignore the metadata on the commandline going hcp to hcp unless the user has
        // cli.override_metadata
        // set to true in their user.properties file. This is a special hook for service.
        boolean goingFromLFSToHCP = srcProfile.getType() == ProfileType.FILESYSTEM
                && dstProfile.getType() != ProfileType.FILESYSTEM;
        boolean isCLIMetadataOverrideEnabled = Boolean.parseBoolean(HCPMoverProperties.CLI_OVERRIDE_MD.get());
        if (goingFromLFSToHCP || isCLIMetadataOverrideEnabled) {
            if (cmdLine.hasOption(INDEX_OPTION)) {
                metadata.setSearchIndex(new Boolean(cmdLine.getOptionValue(INDEX_OPTION)));
            }
            if (cmdLine.hasOption(HOLD_OPTION)) {
                metadata.setRetentionHold(new Boolean(cmdLine.getOptionValue(HOLD_OPTION)));
            }
            if (cmdLine.hasOption(SHRED_OPTION)) {
                metadata.setShred(new Boolean(cmdLine.getOptionValue(SHRED_OPTION)));
            }

            if (cmdLine.hasOption(RETENTION_OPTION)) {
                String cmdLineRetentionValue = cmdLine.getOptionValue(RETENTION_OPTION);
                Retention retention = Retention.fromHcapValue(cmdLineRetentionValue);
                metadata.setRetention(retention);
            }

            if (cmdLine.hasOption(CUSTOM_METADATA_OPTION)) {
                CustomMetadata customMetadata = new CustomMetadata(CustomMetadata.Form.FILE,
                        cmdLine.getOptionValue(CUSTOM_METADATA_OPTION));
                metadata.setCustomMetadata(customMetadata);
            }

            if (cmdLine.hasOption(ACL_OPTION)) {
                if (dstProfile.supportsACLs()) {
                    ACLMetadata acl = new ACLMetadata(CustomMetadata.Form.FILE,
                            cmdLine.getOptionValue(ACL_OPTION));
                    metadata.setACL(acl);
                } else {
                    throw new ParseException("The " + ACL_OPTION
                            + " may only be specified when copying from the local file system to a HCP 5.0 or later namespace.");
                }
            }

            if (dstProfile.supportsPosixSettings()) {
                if (cmdLine.hasOption(UID_OPTION)) {
                    metadata.setUid(cmdLine.getOptionValue(UID_OPTION));
                }
                if (cmdLine.hasOption(GID_OPTION)) {
                    metadata.setGid(cmdLine.getOptionValue(GID_OPTION));
                }
                if (cmdLine.hasOption(FILE_PERMS_OPTION)) {
                    metadata.setFileMode(new Integer(cmdLine.getOptionValue(FILE_PERMS_OPTION)));
                }
                if (cmdLine.hasOption(DIR_PERMS_OPTION)) {
                    metadata.setDirMode(new Integer(cmdLine.getOptionValue(DIR_PERMS_OPTION)));
                }
            } else {
                List<String> extraOptions = new ArrayList<String>();
                if (cmdLine.hasOption(UID_OPTION)) {
                    extraOptions.add(UID_OPTION);
                }
                if (cmdLine.hasOption(GID_OPTION)) {
                    extraOptions.add(GID_OPTION);
                }
                if (cmdLine.hasOption(FILE_PERMS_OPTION)) {
                    extraOptions.add(FILE_PERMS_OPTION);
                }
                if (cmdLine.hasOption(DIR_PERMS_OPTION)) {
                    extraOptions.add(DIR_PERMS_OPTION);
                }
                if (!extraOptions.isEmpty()) {
                    throw new ParseException(
                            "The following supplied options are only allowed when copying from the local file system to either HCAP 2.x or the default namespace on HCP 3.0 or later: "
                                    + extraOptions);
                }
            }

            // throw an exception if anonymous user tries to set owner for objects
            if (dstProfile.isAnonymousAccess()) {
                if (cmdLine.hasOption(OWNER_OPTION)) {
                    throw new ParseException("Cannot use owner option with an anonymous namespace profile.");
                }
            }

            if (dstProfile.supportsOwner()) {
                if (cmdLine.hasOption(OWNER_OPTION)) {
                    Owner owner;
                    if (cmdLine.hasOption(DOMAIN_OPTION)) {
                        owner = new Owner(cmdLine.getOptionValue(OWNER_OPTION),
                                cmdLine.getOptionValue(DOMAIN_OPTION));
                    } else {
                        String ownerName = cmdLine.getOptionValue(OWNER_OPTION);
                        if (ownerName.length() == 0) {
                            owner = new Owner(Owner.OwnerType.PUBLIC);
                        } else {
                            owner = new Owner(ownerName);
                        }
                    }
                    metadata.setOwner(owner);
                }
            } else {
                List<String> extraOptions = new ArrayList<String>();
                if (cmdLine.hasOption(OWNER_OPTION)) {
                    extraOptions.add(OWNER_OPTION);
                }
                if (cmdLine.hasOption(DOMAIN_OPTION)) {
                    extraOptions.add(DOMAIN_OPTION);
                }
                if (!extraOptions.isEmpty()) {
                    throw new ParseException(
                            "The following supplied options are only allowed when copying from the local file system to an HCP 5.0 or later namespace: "
                                    + extraOptions);
                }
            }
        } else {
            List<String> extraOptions = new ArrayList<String>();
            if (cmdLine.hasOption(HOLD_OPTION)) {
                extraOptions.add(HOLD_OPTION);
            }
            if (cmdLine.hasOption(INDEX_OPTION)) {
                extraOptions.add(INDEX_OPTION);
            }
            if (cmdLine.hasOption(SHRED_OPTION)) {
                extraOptions.add(SHRED_OPTION);
            }
            if (cmdLine.hasOption(RETENTION_OPTION)) {
                extraOptions.add(RETENTION_OPTION);
            }
            if (cmdLine.hasOption(UID_OPTION)) {
                extraOptions.add(UID_OPTION);
            }
            if (cmdLine.hasOption(GID_OPTION)) {
                extraOptions.add(GID_OPTION);
            }
            if (cmdLine.hasOption(FILE_PERMS_OPTION)) {
                extraOptions.add(FILE_PERMS_OPTION);
            }
            if (cmdLine.hasOption(DIR_PERMS_OPTION)) {
                extraOptions.add(DIR_PERMS_OPTION);
            }
            if (cmdLine.hasOption(CUSTOM_METADATA_OPTION)) {
                extraOptions.add(CUSTOM_METADATA_OPTION);
            }
            if (cmdLine.hasOption(ACL_OPTION)) {
                extraOptions.add(ACL_OPTION);
            }
            if (cmdLine.hasOption(OWNER_OPTION)) {
                extraOptions.add(OWNER_OPTION);
            }
            if (cmdLine.hasOption(DOMAIN_OPTION)) {
                extraOptions.add(DOMAIN_OPTION);
            }
            if (!extraOptions.isEmpty()) {
                throw new ParseException(
                        "The following supplied options are only allowed when copying from the local file system to HCP: "
                                + extraOptions);
            }
        }

        boolean ignoreConflicts = cmdLine.hasOption(IGNORE_CONFLICTS);

        // Validate the input file if one was provided
        try {
            FileListParser.validateFile(new File(listFileName), srcProfile, sourcePath, targetPath);
        } catch (IOException e) {
            throw new ParseException("Error parsing input file.  Msg: " + e.getMessage());
        } catch (FileListParserException e) {
            throw new ParseException("Error parsing input file.  Msg: " + e.getMessage());
        }

        // Setup the job with the arguments
        try {
            setupCopyJob(listFileName, dstProfile, targetPath, srcProfile, sourcePath, jobName, metadata,
                    ignoreConflicts, schedule);
            managedJobImpl = arcMover.createManagedJob(managedJob);
        } catch (IllegalArgumentException e) {
            throw new ParseException(
                    "IllegalArgumentException writing to database during file list parsing.  Msg: "
                            + e.getMessage());
        } catch (DatabaseException e) {
            throw new ParseException(
                    "DatabaseException writing to database during file list parsing.  Msg: " + e.getMessage());
        } catch (JobException e) {
            throw new ParseException(
                    "JobException writing to database during file list parsing.  Msg: " + e.getMessage());
        }
    }
}

From source file:net.jsign.PESignerCLI.java

void execute(String... args) throws SignerException {
    DefaultParser parser = new DefaultParser();
    try {//from   w  w  w. j  a v a 2  s .co m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help") || args.length == 0) {
            printHelp();
            return;
        }

        File keystore = cmd.hasOption("keystore") ? new File(cmd.getOptionValue("keystore")) : null;
        String storepass = cmd.getOptionValue("storepass");
        String storetype = cmd.getOptionValue("storetype");
        String alias = cmd.getOptionValue("alias");
        String keypass = cmd.getOptionValue("keypass");
        File keyfile = cmd.hasOption("keyfile") ? new File(cmd.getOptionValue("keyfile")) : null;
        File certfile = cmd.hasOption("certfile") ? new File(cmd.getOptionValue("certfile")) : null;
        String tsaurl = cmd.getOptionValue("tsaurl");
        String tsmode = cmd.getOptionValue("tsmode");
        String algorithm = cmd.getOptionValue("alg");
        String name = cmd.getOptionValue("name");
        String url = cmd.getOptionValue("url");
        File file = cmd.getArgList().isEmpty() ? null : new File(cmd.getArgList().get(0));

        if (keystore != null && storetype == null) {
            // guess the type of the keystore from the extension of the file
            String filename = keystore.getName().toLowerCase();
            if (filename.endsWith(".p12") || filename.endsWith(".pfx")) {
                storetype = "PKCS12";
            } else {
                storetype = "JKS";
            }
        }

        PrivateKey privateKey;
        Certificate[] chain;

        // some exciting parameter validation...
        if (keystore == null && keyfile == null && certfile == null) {
            throw new SignerException("keystore option, or keyfile and certfile options must be set");
        }
        if (keystore != null && (keyfile != null || certfile != null)) {
            throw new SignerException("keystore option can't be mixed with keyfile or certfile");
        }

        if (keystore != null) {
            // JKS or PKCS12 keystore 
            KeyStore ks;
            try {
                ks = KeyStore.getInstance(storetype);
            } catch (KeyStoreException e) {
                throw new SignerException("keystore type '" + storetype + "' is not supported", e);
            }

            if (!keystore.exists()) {
                throw new SignerException("The keystore " + keystore + " couldn't be found");
            }
            FileInputStream in = null;
            try {
                in = new FileInputStream(keystore);
                ks.load(in, storepass != null ? storepass.toCharArray() : null);
            } catch (Exception e) {
                throw new SignerException("Unable to load the keystore " + keystore, e);
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    // ignore
                }
            }

            if (alias == null) {
                throw new SignerException("alias option must be set");
            }

            try {
                chain = ks.getCertificateChain(alias);
            } catch (KeyStoreException e) {
                throw new SignerException(e.getMessage(), e);
            }
            if (chain == null) {
                throw new SignerException(
                        "No certificate found under the alias '" + alias + "' in the keystore " + keystore);
            }

            char[] password = keypass != null ? keypass.toCharArray() : storepass.toCharArray();

            try {
                privateKey = (PrivateKey) ks.getKey(alias, password);
            } catch (Exception e) {
                throw new SignerException("Failed to retrieve the private key from the keystore", e);
            }

        } else {
            // separate private key and certificate files (PVK/SPC)
            if (keyfile == null) {
                throw new SignerException("keyfile option must be set");
            }
            if (!keyfile.exists()) {
                throw new SignerException("The keyfile " + keyfile + " couldn't be found");
            }
            if (certfile == null) {
                throw new SignerException("certfile option must be set");
            }
            if (!certfile.exists()) {
                throw new SignerException("The certfile " + certfile + " couldn't be found");
            }

            // load the certificate chain
            try {
                chain = loadCertificateChain(certfile);
            } catch (Exception e) {
                throw new SignerException("Failed to load the certificate from " + certfile, e);
            }

            // load the private key
            try {
                privateKey = PVK.parse(keyfile, keypass);
            } catch (Exception e) {
                throw new SignerException("Failed to load the private key from " + keyfile, e);
            }
        }

        if (algorithm != null && DigestAlgorithm.of(algorithm) == null) {
            throw new SignerException("The digest algorithm " + algorithm + " is not supported");
        }

        if (file == null) {
            throw new SignerException("missing file argument");
        }
        if (!file.exists()) {
            throw new SignerException("The file " + file + " couldn't be found");
        }

        PEFile peFile;
        try {
            peFile = new PEFile(file);
        } catch (IOException e) {
            throw new SignerException("Couldn't open the executable file " + file, e);
        }

        // and now the actual work!
        PESigner signer = new PESigner(chain, privateKey).withProgramName(name).withProgramURL(url)
                .withDigestAlgorithm(DigestAlgorithm.of(algorithm))
                .withTimestamping(tsaurl != null || tsmode != null)
                .withTimestampingMode(TimestampingMode.of(tsmode)).withTimestampingAutority(tsaurl);

        try {
            System.out.println("Adding Authenticode signature to " + file);
            signer.sign(peFile);
        } catch (Exception e) {
            throw new SignerException("Couldn't sign " + file, e);
        } finally {
            try {
                peFile.close();
            } catch (IOException e) {
                System.err.println("Couldn't close " + file);
                e.printStackTrace(System.err);
            }
        }

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

From source file:edu.uci.ics.asterix.aoya.AsterixYARNClient.java

/**
 * Initialize the mode of the client from the arguments.
 * //  ww  w .  j  a v a  2  s .co m
 * @param args
 * @param cliParser
 * @throws ParseException
 */
private void initMode(String[] args, CommandLine cliParser) throws ParseException {
    @SuppressWarnings("unchecked")
    List<String> clientVerb = cliParser.getArgList();
    String message = null;
    //Now check if there is a mode
    if (clientVerb == null || clientVerb.size() < 1) {
        message = "You must specify an action.";
    }
    //But there can only be one mode...
    else if (clientVerb.size() > 1) {
        message = "Trailing arguments, or too many arguments. Only one action may be performed at a time.";
    }
    if (message != null) {
        throw new ParseException(message);
    }
    //Now we can initialize the mode and check it against parameters
    mode = Mode.fromAlias(clientVerb.get(0));
    if (mode == null) {
        mode = Mode.NOOP;
    }
}

From source file:com.netcrest.pado.tools.pado.command.temporal.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from   w  w  w  .  j  a  v  a 2 s  . co  m
public void run(CommandLine commandLine, String command) throws Exception {
    boolean isLucene = commandLine.hasOption("lucene");
    boolean isEnable = commandLine.hasOption("enable");
    boolean isDisable = commandLine.hasOption("disable");
    boolean isAll = commandLine.hasOption("all");
    if (isAll && (isLucene == false && isEnable == false && isDisable == false)) {
        PadoShell.printlnError(this,
                "Invalid option. '-all' only applies to '-lucene', '-enable', and '-disable'.");
        return;
    }

    List<String> argList = (List<String>) commandLine.getArgList();

    if (isLucene || isEnable || isDisable) {

        // Build Lucene indexes

        // Parse [-all [-grid <grid ID>[,...]] | [<path>...]]
        String[] gridIds = PadoShellUtil.getGridIds(this, commandLine, true);
        if (gridIds == null) {
            return;
        }
        String fullPaths[] = PadoShellUtil.getFullPaths(padoShell, commandLine);
        if (PadoShellUtil.hasError(this, padoShell, fullPaths, true)) {
            return;
        }

        if (isLucene) {
            runLucene(gridIds, fullPaths);
        } else {
            setTemporalEnabled(isEnable, gridIds, fullPaths);
        }

    } else {

        // Execute temporal command
        String path;
        if (argList.size() == 1) {
            path = padoShell.getCurrentPath();
        } else {
            path = argList.get(1);
        }
        String fullPath = padoShell.getFullPath(path);
        String gridId = SharedCache.getSharedCache().getGridId(fullPath);
        String gridPath = GridUtil.getChildPath(fullPath);

        String fullPaths[] = PadoShellUtil.getFullPaths(padoShell, commandLine);
        if (fullPaths == null) {
            fullPaths = new String[] { fullPath };
        }
        if (PadoShellUtil.hasError(this, padoShell, fullPaths, false)) {
            return;
        }

        ITemporalBiz temporalBiz = SharedCache.getSharedCache().getPado().getCatalog()
                .newInstance(ITemporalBiz.class, gridPath);
        temporalBiz.getBizContext().getGridContextClient().setGridIds(gridId);
        temporalBiz.setGridPath(gridPath);
        rawFormat = false;
        if (commandLine.hasOption("put")) {
            runPut(temporalBiz, commandLine.getOptionValues("put"));
        } else if (commandLine.hasOption("putAttachments")) {
            runPutAttachments(temporalBiz, commandLine.getOptionValues("putAttachments"));
        } else if (commandLine.hasOption("get")) {
            runGet(temporalBiz, commandLine.getOptionValues("get"));
        } else if (commandLine.hasOption("getAttachments1")) {
            runGetAttachments1(temporalBiz, commandLine.getOptionValues("getAttachments1"));
        } else if (commandLine.hasOption("getAttachments2")) {
            runGetAttachments2(temporalBiz, commandLine.getOptionValues("getAttachments2"));
        } else if (commandLine.hasOption("getAttachments3")) {
            runGetAttachments3(temporalBiz, commandLine.getOptionValues("getAttachments3"));
        } else if (commandLine.hasOption("remove")) {
            runRemove(temporalBiz, commandLine.getOptionValues("remove"));
        } else if (commandLine.hasOption("history")) {
            if (commandLine.hasOption("rawformat")) {
                rawFormat = true;
            } else {
                rawFormat = false;
            }
            runHistory(temporalBiz, commandLine.getOptionValue("history"));
        } else {
            boolean isRefresh = commandLine.hasOption("-refresh");
            IScrollableResultSet srs = temporalBiz.getEntryResultSet(System.currentTimeMillis(), null, true,
                    padoShell.getFetchSize(), isRefresh);
            srs.setFetchSize(padoShell.getFetchSize());
            ResultSetDisplay.display(srs);
        }
    }
}

From source file:de.uni_rostock.goodod.tools.Configuration.java

private HierarchicalConfiguration getConfigMap(String args[]) {

    CombinedConfiguration cfg = new CombinedConfiguration();
    HierarchicalConfiguration envCfg = new CombinedConfiguration();
    String repoRoot = System.getenv("GOODOD_REPO_ROOT");
    boolean helpMode = false;

    envCfg.addProperty("repositoryRoot", repoRoot);
    if (null == args) {
        return cfg;
    }/* w ww . j a va2s .co  m*/
    GnuParser cmdLineParser = new GnuParser();
    CommandLine cmdLine = null;
    try {
        // parse the command line arguments
        cmdLine = cmdLineParser.parse(options, args);
    } catch (ParseException exception) {
        logger.fatal("Could not validate command-line.", exception);
        System.exit(1);
    }

    if (cmdLine.hasOption('c')) {
        envCfg.addProperty("configFile", cmdLine.getOptionValue('c'));
    }
    if (cmdLine.hasOption('t')) {
        envCfg.addProperty("threadCount", cmdLine.getOptionObject('t'));
    }

    if (cmdLine.hasOption('s')) {
        envCfg.addProperty("similarity", cmdLine.getOptionValue('s'));
    }
    if (cmdLine.hasOption('h')) {
        envCfg.addProperty("helpMode", true);
        helpMode = true;
    }
    if (cmdLine.hasOption('d')) {
        envCfg.addProperty("debug", true);
    }
    if (cmdLine.hasOption('1')) {
        envCfg.addProperty("one-way", true);
    }
    //Fetch the remaining arguments, but alas, commons-cli is not generics aware
    @SuppressWarnings("unchecked")
    List<String> argList = cmdLine.getArgList();
    HierarchicalConfiguration testConfig = null;
    try {
        if (argList.isEmpty() && (false == helpMode)) {
            logger.fatal("No test specification provided.");
            System.exit(1);
        } else if (1 == argList.size()) {
            File testFile = new File(argList.get(0));
            testConfig = readTestConfig(testFile);
            assert (null != testConfig);
            envCfg.addProperty("testFile", testFile.toString());

        } else if (false == helpMode) {
            /*
             *  For > 1 file, we assume that both are ontologies and we
             *  construct ourselves a test case configuration for them.
             */
            testConfig = new HierarchicalConfiguration();
            String ontologyA = argList.get(0);
            String ontologyB = argList.get(1);
            testConfig.addProperty("testName", "Comparison of " + ontologyA + " and " + ontologyB);
            testConfig.addProperty("notInRepository", true);
            Node studentOntologies = new Node("studentOntologies");
            Node groupA = new Node("groupA", Collections.singletonList(ontologyA));
            Node groupB = new Node("groupB", Collections.singletonList(ontologyB));
            studentOntologies.addChild(groupA);
            studentOntologies.addChild(groupB);
            testConfig.getRoot().addChild(studentOntologies);
            if (2 < argList.size()) {
                logger.warn("Ignoring extra arguments to comparison between individual ontologies.");
            }
            envCfg.addProperty("testFile", "unknown.plist");
        }
    } catch (Throwable t) {
        logger.fatal("Could not load test configuration.", t);
        System.exit(1);
    }
    cfg.addConfiguration(envCfg, "environment");
    if (false == helpMode) {
        cfg.addConfiguration(testConfig, "TestSubTree", "testDescription");
    }
    return cfg;
}

From source file:com.trsst.Command.java

public int doBegin(String[] argv, PrintStream out, InputStream in) {

    buildOptions(argv, out, in);/*from ww w . j  av a2s.c  om*/

    int result = 0;
    Server server = null;
    try {

        CommandLineParser argParser = new GnuParser();
        CommandLine commands;
        try {
            commands = argParser.parse(mergedOptions, argv);
        } catch (Throwable t) {
            log.error("Unexpected error parsing arguments: " + Arrays.asList(argv), t);
            return 127;
        }
        LinkedList<String> arguments = new LinkedList<String>();
        for (Object o : commands.getArgList()) {
            arguments.add(o.toString()); // dodge untyped param warning
        }
        if (commands.hasOption("?")) {
            printAllUsage();
            return 0;
        }
        if (arguments.size() < 1) {
            printAllUsage();
            return 127; // "command not found"
        }
        if (!commands.hasOption("strict")) {
            // most trsst nodes run with self-signed certificates,
            // so by default we accept them
            Common.enableAnonymousSSL();
        } else {
            System.err.println("Requiring signed SSL");
        }
        // System.out.println("Commands: " + arguments );
        String mode = arguments.removeFirst().toString();

        // for port requests
        if ("serve".equals(mode)) {
            // start a server and exit
            result = doServe(commands, arguments);
            return 0;
        }

        // attempt to parse next argument as a server url
        Client client = null;
        if (commands.hasOption("h")) {
            String host = commands.getOptionValue("h");
            try {
                URL url = new URL(host);
                // this argument is a server url
                client = new Client(url);
                System.err.println("Using service: " + host);
            } catch (MalformedURLException e) {
                // otherwise: ignore and continue
                System.err.println("Bad hostname: " + host);
            }
        }

        // if a server url wasn't specified
        if (client == null) {
            // start a client with a local server
            server = new Server();
            client = new Client(server.getServiceURL());
            System.err.println("Starting temporary service at: " + server.getServiceURL());
        }

        if ("pull".equals(mode)) {
            // pull feeds from server
            result = doPull(client, commands, arguments, out);
        } else if ("push".equals(mode)) {
            // push feeds to server
            result = doPush(client, commands, arguments, out);
        } else if ("post".equals(mode)) {
            // post (and push) entries
            result = doPost(client, commands, arguments, out, in);
        } else {
            printAllUsage();
            result = 127; // "command not found"
        }
    } catch (Throwable t) {
        log.error("Unexpected error: " + t, t);
        result = 1; // "catchall for general errors"
    }
    if (server != null) {
        server.stop();
    }
    return result;
}

From source file:biomine.bmvis2.Vis.java

private void createGUI(String title) {
    //        try {
    //            System.setProperty("com.apple.macosx.AntiAliasedTextOn", "false");
    //            System.setProperty("com.apple.macosx.AntiAliasedGraphicsOn",
    //                    "false");
    //        } catch (Throwable t) {
    //            // Ignore property exceptions
    //        }/*ww  w.j a  va  2  s. c o m*/
    //        try {
    //            System.setProperty("sun.java2d.opengl", "true");
    //        } catch (Throwable t) {
    //            // Ignore property exceptions
    //        }

    this.setLayout(new GridLayout());
    this.tabs = new TabbedPaneHiddenBar();
    this.getContentPane().add(tabs);
    this.tabs.setVisible(true);

    tabs.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent arg0) {
            GraphTab tab = (GraphTab) tabs.getSelectedComponent();
            if (tab == null) {
                Logging.info("ui", "No graphs open, creating the default menu.");
                Vis.this.setJMenuBar(getDefaultMenu());
            } else {
                Vis.this.setJMenuBar(tab.getMenuBar());
            }
        }
    });

    if (appletContext == null) {
        Options opts = new Options();
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = null;

        opts.addOption("h", "help", false, "Show help.");
        opts.addOption("s", "simple", false, "Show simple UI without side panes");
        opts.addOption("logcategories", true, "Logging categories delimited by spaces, all for all");
        opts.addOption("loglevel", true, "Logging level: 0 for debug, 1 for info, 2 for warning, 3 for error");
        opts.addOption("d", "debug", false, "Shorthand for logcategories all, loglevel -1");

        try {
            cmd = parser.parse(opts, args);
        } catch (ParseException e) {
            System.err.println(e.getLocalizedMessage());
            System.err.println();
            Vis.printCmdLineHelp(opts);
            System.exit(1);
        }

        if (cmd.hasOption("-h") || cmd.getArgList().size() == 0) {
            Vis.printCmdLineHelp(opts);
            System.exit(0);
        }

        if (cmd.hasOption("-s"))
            this.properties.put("simple", "true");

        if (cmd.hasOption("-d")) {
            Logging.init(new ArrayList<String>(Arrays.asList("all")), -1);
        } else {
            ArrayList<String> logCategories = null;
            Integer logLevel = null;
            if (cmd.hasOption("logcategories"))
                logCategories = new ArrayList<String>(
                        Arrays.asList(cmd.getOptionValue("logcategories").split(",")));
            if (cmd.hasOption("loglevel"))
                logLevel = Integer.parseInt(cmd.getOptionValue("loglevel"));

            if (logCategories != null || logLevel != null)
                Logging.init(logCategories, logLevel);
        }

        VisFrame frame = new VisFrame("BMVIS II");
        this.visFrame = frame;
        frame.add(this);

        boolean noneOpened = true;
        for (Object arg : cmd.getArgList()) {
            if (this.openTab((String) arg) != null)
                noneOpened = false;
        }

        if (noneOpened && cmd.getArgList().size() > 0) {
            String message = "No files could be opened! Exiting.";
            Logging.error("graph_reading", message);
            JOptionPane.showMessageDialog(this, message);
            System.exit(1);
        }

        this.visFrame.setVisible(true);

    } else {
        // Applet operation goes here...
        this.setVisible(true);

        try {
            if (getParameter("graph") != null) {
                String graphFile = getParameter("graph");

                URL u = new URL(getCodeBase(), graphFile);
                InputStream graphStream = u.openConnection().getInputStream();
                BMGraph bm = BMGraphUtils.readBMGraph(graphStream);
                graphStream.close();
                this.openTab(new FileGraphSource(bm));
            }
            if (getParameter("json") != null) {
                String jsonFile = getParameter("json");
                URL u = new URL(getCodeBase(), jsonFile);
                InputStream jsonStream = u.openConnection().getInputStream();

                openJSONTab(StreamToString.convertStreamToString(jsonStream), jsonFile);
            }
        } catch (IOException e) {
            Logging.error("graph_reading", e.toString());
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }
}

From source file:com.trsst.Command.java

public int doPost(Client client, CommandLine commands, LinkedList<String> arguments, PrintStream out,
        InputStream in) {// w ww .j  ava 2s  .  c o m

    String id = null;

    if (arguments.size() == 0 && commands.getArgList().size() == 0) {
        printPostUsage();
        return 127; // "command not found"
    }

    if (arguments.size() > 0) {
        id = arguments.removeFirst();
        System.err.println("Obtaining keys for feed id: " + id);
    } else {
        System.err.println("Generating new feed id... ");
    }

    // read input text
    String subject = commands.getOptionValue("s");
    String verb = commands.getOptionValue("v");
    String base = commands.getOptionValue("b");
    String body = commands.getOptionValue("c");
    String name = commands.getOptionValue("n");
    String email = commands.getOptionValue("m");
    String uri = commands.getOptionValue("uri");
    String title = commands.getOptionValue("t");
    String subtitle = commands.getOptionValue("subtitle");
    String icon = commands.getOptionValue("i");
    if (icon == null && commands.hasOption("i")) {
        icon = "-";
    }
    String logo = commands.getOptionValue("l");
    if (logo == null && commands.hasOption("l")) {
        logo = "-";
    }
    String attach = commands.getOptionValue("a");
    if (attach == null && commands.hasOption("a")) {
        attach = "-";
    }
    String[] recipients = commands.getOptionValues("e");
    String[] mentions = commands.getOptionValues("r");
    String[] tags = commands.getOptionValues("g");
    String url = commands.getOptionValue("u");
    String vanity = commands.getOptionValue("vanity");

    // obtain password
    char[] password = null;
    String pass = commands.getOptionValue("p");
    if (pass != null) {
        password = pass.toCharArray();
    } else {
        try {
            Console console = System.console();
            if (console != null) {
                password = console.readPassword("Password: ");
            } else {
                log.info("No console detected for password input.");
            }
        } catch (Throwable t) {
            log.error("Unexpected error while reading password", t);
        }
    }
    if (password == null) {
        log.error("Password is required to post.");
        return 127; // "command not found"
    }
    if (password.length < 6) {
        System.err.println("Password must be at least six characters in length.");
        return 127; // "command not found"
    }

    // obtain keys
    KeyPair signingKeys = null;
    KeyPair encryptionKeys = null;
    String keyPath = commands.getOptionValue("k");

    // if id was not specified from the command line
    if (id == null) {

        // if password was not specified from command line
        if (pass == null) {
            try {
                // verify password
                char[] verify = null;
                Console console = System.console();
                if (console != null) {
                    verify = console.readPassword("Re-type Password: ");
                } else {
                    log.info("No console detected for password verification.");
                }
                if (verify == null || verify.length != password.length) {
                    System.err.println("Passwords do not match.");
                    return 127; // "command not found"
                }
                for (int i = 0; i < verify.length; i++) {
                    if (verify[i] != password[i]) {
                        System.err.println("Passwords do not match.");
                        return 127; // "command not found"
                    }
                    verify[i] = 0;
                }
            } catch (Throwable t) {
                log.error("Unexpected error while verifying password: " + t.getMessage(), t);
            }
        }

        // create new account
        if (base == null) {
            // default to trsst hub
            base = "https://home.trsst.com/feed";
        }

        // generate vanity id if required
        if (vanity != null) {
            System.err.println("Searching for vanity feed id prefix: " + vanity);
            switch (vanity.length()) {
            case 0:
            case 1:
                break;
            case 2:
                System.err.println("This may take several minutes.");
                break;
            case 3:
                System.err.println("This may take several hours.");
                break;
            case 4:
                System.err.println("This may take several days.");
                break;
            case 5:
                System.err.println("This may take several months.");
                break;
            default:
                System.err.println("This may take several years.");
                break;
            }
            System.err.println("Started: " + new Date());
            System.err.println("^C to exit");
        }
        do {
            signingKeys = Common.generateSigningKeyPair();
            id = Common.toFeedId(signingKeys.getPublic());
        } while (vanity != null && !id.startsWith(vanity));
        if (vanity != null) {
            System.err.println("Finished: " + new Date());
        }

        encryptionKeys = Common.generateEncryptionKeyPair();
        System.err.println("New feed id created: " + id);

        File keyFile;
        if (keyPath != null) {
            keyFile = new File(keyPath, id + Common.KEY_EXTENSION);
        } else {
            keyFile = new File(Common.getClientRoot(), id + Common.KEY_EXTENSION);
        }

        // persist to keystore
        writeSigningKeyPair(signingKeys, id, keyFile, password);
        writeEncryptionKeyPair(encryptionKeys, id, keyFile, password);

    } else {

        File keyFile;
        if (keyPath != null) {
            keyFile = new File(Common.getClientRoot(), keyPath);
        } else {
            keyFile = new File(Common.getClientRoot(), id + Common.KEY_EXTENSION);
        }

        if (keyFile.exists()) {
            System.err.println("Using existing account id: " + id);

        } else {
            System.err.println("Cannot locate keys for account id: " + id);
            return 78; // "configuration error"
        }

        signingKeys = readSigningKeyPair(id, keyFile, password);
        if (signingKeys != null) {
            encryptionKeys = readEncryptionKeyPair(id, keyFile, password);
            if (encryptionKeys == null) {
                encryptionKeys = signingKeys;
            }
        }
    }

    // clear password chars
    for (int i = 0; i < password.length; i++) {
        password[i] = 0;
    }
    if (signingKeys == null) {
        System.err.println("Could not obtain keys for signing.");
        return 73; // "can't create output error"
    }

    String[] recipientIds = null;
    if (recipients != null) {
        LinkedList<String> keys = new LinkedList<String>();
        for (int i = 0; i < recipients.length; i++) {
            if ("-".equals(recipients[i])) {
                // "-" is shorthand for encrypt for mentioned ids
                if (mentions != null) {
                    for (String mention : mentions) {
                        if (Common.isFeedId(mention)) {
                            keys.add(mention);
                        }
                    }
                }
            } else if (Common.isFeedId(recipients[i])) {
                keys.add(recipients[i]);
            } else {
                log.warn("Could not parse recipient id: " + recipients[i]);
            }
        }
        recipientIds = keys.toArray(new String[0]);
    }

    // handle binary attachment
    String mimetype = null;
    byte[] attachment = null;
    if (attach != null) {
        InputStream input = null;
        try {
            if ("-".equals(attach)) {
                input = new BufferedInputStream(in);
            } else {
                File file = new File(attach);
                input = new BufferedInputStream(new FileInputStream(file));
                System.err.println("Attaching: " + file.getCanonicalPath());
            }
            attachment = Common.readFully(input);
            mimetype = new Tika().detect(attachment);
            System.err.println("Detected type: " + mimetype);
        } catch (Throwable t) {
            log.error("Could not read attachment: " + attach, t);
            return 73; // "can't create output error"
        } finally {
            try {
                input.close();
            } catch (IOException ioe) {
                // suppress any futher error on closing
            }
        }
    }

    Object result;
    try {
        EntryOptions options = new EntryOptions();
        options.setStatus(subject);
        options.setVerb(verb);
        if (mentions != null) {
            options.setMentions(mentions);
        }
        if (tags != null) {
            options.setTags(tags);
        }
        options.setBody(body);
        if (attachment != null) {
            options.addContentData(attachment, mimetype);
        } else if (url != null) {
            options.setContentUrl(url);
        }
        FeedOptions feedOptions = new FeedOptions();
        feedOptions.setAuthorEmail(email);
        feedOptions.setAuthorName(name);
        feedOptions.setAuthorUri(uri);
        feedOptions.setTitle(title);
        feedOptions.setSubtitle(subtitle);
        feedOptions.setBase(base);
        if (icon != null) {
            if ("-".equals(icon)) {
                feedOptions.setAsIcon(true);
            } else {
                feedOptions.setIconURL(icon);
            }
        }
        if (logo != null) {
            if ("-".equals(logo)) {
                feedOptions.setAsLogo(true);
            } else {
                feedOptions.setLogoURL(logo);
            }
        }
        if (recipientIds != null) {
            EntryOptions publicEntry = new EntryOptions().setStatus("Encrypted content").setVerb("encrypt");
            // TODO: add duplicate mentions to outside of envelope
            options.encryptFor(recipientIds, publicEntry);
        }
        result = client.post(signingKeys, encryptionKeys, options, feedOptions);
    } catch (IllegalArgumentException e) {
        log.error("Invalid request: " + id + " : " + e.getMessage(), e);
        return 76; // "remote error"
    } catch (IOException e) {
        log.error("Error connecting to service for id: " + id, e);
        return 76; // "remote error"
    } catch (org.apache.abdera.security.SecurityException e) {
        log.error("Error generating signatures for id: " + id, e);
        return 73; // "can't create output error"
    } catch (Exception e) {
        log.error("General security error for id: " + id, e);
        return 74; // "general io error"
    }

    if (result != null) {
        if (format) {
            out.println(Common.formatXML(result.toString()));
        } else {
            out.println(result.toString());
        }
    }

    return 0; // "OK"
}

From source file:com.greenpepper.maven.runner.CommandLineRunner.java

@SuppressWarnings("unchecked")
private List<String> parseCommandLine(String[] args)
        throws ArgumentMissingException, IOException, ParseException {
    List<String> parameters = new ArrayList<String>();
    CommandLine commandLine = argumentsParser.parse(args);
    if (commandLine != null) {
        Option[] options = commandLine.getOptions();
        for (Option option : options) {
            if ("v".equals(option.getOpt())) {
                isDebug = true;/*from ww w.  j  ava2 s .c om*/
                parameters.add("--debug");
            } else if ("p".equals(option.getOpt())) {
                projectDependencyDescriptor = option.getValue();
            } else if ("m".equals(option.getOpt())) {
                usingScopes(option.getValue());
            } else if ("o".equals(option.getOpt())) {
                parameters.add("-" + option.getOpt());
                parameters.add(option.getValue());
            } else if ("r".equals(option.getOpt())) {
                parameters.add("-" + option.getOpt());
                parameters.add(option.getValue());
            } else {
                parameters.add("--" + option.getLongOpt());
                if (option.hasArg()) {
                    parameters.add(option.getValue());
                }
            }
        }
        parameters.addAll(commandLine.getArgList());
    }
    return parameters;
}