Example usage for org.apache.commons.lang StringUtils removeEnd

List of usage examples for org.apache.commons.lang StringUtils removeEnd

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils removeEnd.

Prototype

public static String removeEnd(String str, String remove) 

Source Link

Document

Removes a substring only if it is at the end of a source string, otherwise returns the source string.

Usage

From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java

private DavResource getResourceFromGroup(DavServletRequest request, List<String> repositories,
        ArchivaDavResourceLocator locator, RepositoryGroupConfiguration repositoryGroupConfiguration)
        throws DavException, RepositoryAdminException {
    if (repositoryGroupConfiguration.getRepositories() == null
            || repositoryGroupConfiguration.getRepositories().isEmpty()) {
        File file = new File(System.getProperty("appserver.base"),
                "groups/" + repositoryGroupConfiguration.getId());

        return new ArchivaDavResource(file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
                request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler, fileLockManager);
    }/*from w ww.j a va 2s .  c  o  m*/
    List<File> mergedRepositoryContents = new ArrayList<>();
    // multiple repo types so we guess they are all the same type
    // so use the first one
    // FIXME add a method with group in the repository storage
    String firstRepoId = repositoryGroupConfiguration.getRepositories().get(0);

    String path = getLogicalResource(locator, managedRepositoryAdmin.getManagedRepository(firstRepoId), false);
    if (path.startsWith("/")) {
        path = path.substring(1);
    }
    LogicalResource logicalResource = new LogicalResource(path);

    // flow:
    // if the current user logged in has permission to any of the repositories, allow user to
    // browse the repo group but displaying only the repositories which the user has permission to access.
    // otherwise, prompt for authentication.

    String activePrincipal = getActivePrincipal(request);

    boolean allow = isAllowedToContinue(request, repositories, activePrincipal);

    // remove last /
    String pathInfo = StringUtils.removeEnd(request.getPathInfo(), "/");

    if (allow) {

        if (StringUtils.endsWith(pathInfo, repositoryGroupConfiguration.getMergedIndexPath())) {
            File mergedRepoDir = buildMergedIndexDirectory(repositories, activePrincipal, request,
                    repositoryGroupConfiguration);
            mergedRepositoryContents.add(mergedRepoDir);
        } else {
            if (StringUtils.equalsIgnoreCase(pathInfo, "/" + repositoryGroupConfiguration.getId())) {
                File tmpDirectory = new File(SystemUtils.getJavaIoTmpDir(), repositoryGroupConfiguration.getId()
                        + "/" + repositoryGroupConfiguration.getMergedIndexPath());
                if (!tmpDirectory.exists()) {
                    synchronized (tmpDirectory.getAbsolutePath()) {
                        if (!tmpDirectory.exists()) {
                            tmpDirectory.mkdirs();
                        }
                    }
                }
                mergedRepositoryContents.add(tmpDirectory.getParentFile());
            }
            for (String repository : repositories) {
                ManagedRepositoryContent managedRepository = null;

                try {
                    managedRepository = repositoryFactory.getManagedRepositoryContent(repository);
                } catch (RepositoryNotFoundException e) {
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Invalid managed repository <" + repository + ">: " + e.getMessage());
                } catch (RepositoryException e) {
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Invalid managed repository <" + repository + ">: " + e.getMessage());
                }

                File resourceFile = new File(managedRepository.getRepoRoot(), logicalResource.getPath());
                if (resourceFile.exists()) {
                    // in case of group displaying index directory doesn't have sense !!
                    String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
                    if (StringUtils.isNotEmpty(repoIndexDirectory)) {
                        if (!new File(repoIndexDirectory).isAbsolute()) {
                            repoIndexDirectory = new File(managedRepository.getRepository().getLocation(),
                                    StringUtils.isEmpty(repoIndexDirectory) ? ".indexer" : repoIndexDirectory)
                                            .getAbsolutePath();
                        }
                    }
                    if (StringUtils.isEmpty(repoIndexDirectory)) {
                        repoIndexDirectory = new File(managedRepository.getRepository().getLocation(),
                                ".indexer").getAbsolutePath();
                    }

                    if (!StringUtils.equals(FilenameUtils.normalize(repoIndexDirectory),
                            FilenameUtils.normalize(resourceFile.getAbsolutePath()))) {
                        // for prompted authentication
                        if (httpAuth.getSecuritySession(request.getSession(true)) != null) {
                            try {
                                if (isAuthorized(request, repository)) {
                                    mergedRepositoryContents.add(resourceFile);
                                    log.debug("Repository '{}' accessed by '{}'", repository, activePrincipal);
                                }
                            } catch (DavException e) {
                                // TODO: review exception handling

                                log.debug("Skipping repository '{}' for user '{}': {}", managedRepository,
                                        activePrincipal, e.getMessage());

                            }

                        } else {
                            // for the current user logged in
                            try {
                                if (servletAuth.isAuthorized(activePrincipal, repository,
                                        WebdavMethodUtil.getMethodPermission(request.getMethod()))) {
                                    mergedRepositoryContents.add(resourceFile);
                                    log.debug("Repository '{}' accessed by '{}'", repository, activePrincipal);
                                }
                            } catch (UnauthorizedException e) {
                                // TODO: review exception handling

                                log.debug("Skipping repository '{}' for user '{}': {}", managedRepository,
                                        activePrincipal, e.getMessage());

                            }
                        }
                    }
                }
            }
        }
    } else {
        throw new UnauthorizedDavException(locator.getRepositoryId(), "User not authorized.");
    }

    ArchivaVirtualDavResource resource = new ArchivaVirtualDavResource(mergedRepositoryContents,
            logicalResource.getPath(), mimeTypes, locator, this);

    // compatibility with MRM-440 to ensure browsing the repository group works ok
    if (resource.isCollection() && !request.getRequestURI().endsWith("/")) {
        throw new BrowserRedirectException(resource.getHref());
    }

    return resource;
}

From source file:org.apache.beam.examples.oozie.OozieAuditLogParser.java

private void applyValueTo(OozieAuditLogObject oozieAuditLogObject, Matcher matcher) throws ParseException {
    oozieAuditLogObject.timestamp = humanDateToMilliseconds(matcher.group(1));
    oozieAuditLogObject.level = matcher.group(2);
    oozieAuditLogObject.ip = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(6), "["), "]");
    oozieAuditLogObject.user = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(9), "["), "]");
    oozieAuditLogObject.group = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(12), "["), "]");
    oozieAuditLogObject.app = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(15), "["), "]");
    oozieAuditLogObject.jobId = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(18), "["), "]");
    oozieAuditLogObject.operation = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(21), "["), "]");
    oozieAuditLogObject.parameter = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(24), "["), "]");
    oozieAuditLogObject.status = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(27), "["), "]");
    oozieAuditLogObject.httpcode = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(30), "["), "]");
    oozieAuditLogObject.errorcode = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(33), "["), "]");
    oozieAuditLogObject.errormessage = StringUtils.removeEnd(StringUtils.removeStart(matcher.group(36), "["),
            "]");
}

From source file:org.apache.ctakes.jdl.data.loader.CsvLoader.java

/**
 * @param loader/*from w  w w . j  a v a2 s  .  c o m*/
 *            the loader to manage
 * @return the sql string
 */
public final String getSqlInsert(final CsvLoadType loader) {
    String query = "insert into " + loader.getTable() + " (";
    String values = ") values (";
    for (Column column : loader.getColumn()) {
        if (BooleanUtils.isNotTrue(column.isSkip())) {
            query += column.getName() + ",";
            values += "?,";
        }
    }
    return StringUtils.removeEnd(query, ",") + StringUtils.removeEnd(values, ",") + ")";
}

From source file:org.apache.ctakes.jdl.data.loader.XmlLoader.java

/**
 * @param loader/*from  ww  w. ja  va2  s.  c o  m*/
 *            the xml to manage
 * @return the sql string
 */
public final String getSqlInsert(final XmlLoadType loader) {
    String query = "insert into " + loader.getTable() + " (";
    String values = ") values (";
    for (Column column : loader.getColumn()) {
        query += column.getName() + ",";
        values += "?,";
    }
    return StringUtils.removeEnd(query, ",") + StringUtils.removeEnd(values, ",") + ")";
}

From source file:org.apache.geode.management.internal.cli.GfshParser.java

private int completeParameters(CommandTarget commandTarget, int cursorStart, String remainingBuffer, int cursor,
        List<Completion> completionCandidates) {
    int desiredCursorPosition = cursorStart;
    // Factor for remainingBuffer
    boolean sizeReduced = false;
    // We need to work modify the flow according to the CliException
    // generated. For that we will need a reference to the Exception
    // CliException reference
    CliCommandOptionException coe = null;
    OptionSet userOptionSet = null;/*w w w . j  a  va  2s  . c o m*/
    try {
        // We need to remove the space which separates command from the
        // parameters
        if (remainingBuffer.length() > 0) {
            remainingBuffer = remainingBuffer.substring(1);
            sizeReduced = true;
        }

        userOptionSet = commandTarget.getOptionParser().parse(remainingBuffer);
    } catch (CliException ce) {
        if (ce instanceof CliCommandOptionException) {
            coe = (CliCommandOptionException) ce;
            coe.setCommandTarget(commandTarget);
            userOptionSet = coe.getOptionSet();
        }
    }

    // Contains mandatory options which have not been specified
    List<Option> mandatoryOptions = new ArrayList<Option>();
    // Contains non-mandatory options which have not been specified
    List<Option> unspecifiedOptions = new ArrayList<Option>();
    // First we need a list to create a list of all the options specified
    Map<String, Option> optionsPresentMap = new LinkedHashMap<String, Option>();
    if (userOptionSet != null) {

        // Start with the arguments
        String argumentSeparator = " ";
        for (Argument argument : commandTarget.getOptionParser().getArguments()) {
            if (completionCandidates.size() == 0) {
                boolean warning = false;
                if (userOptionSet.hasArgument(argument)) {
                    boolean incrementCursor = true;
                    // Here we need to get all the possible values for this
                    // argument
                    if (getAllPossibleValuesForParameter(completionCandidates, argument,
                            userOptionSet.getValue(argument), commandTarget.getGfshMethodTarget())) {
                        // Check whether the list of completionCandidates is
                        // not empty
                        if (completionCandidates.size() > 0) {
                            // First check whether the argument value
                            // matches with any
                            // of the completionCandidates
                            if (perfectMatch(completionCandidates, userOptionSet.getValue(argument))) {
                                // Remove all the completionCandidates
                                completionCandidates.clear();
                            } else {
                                modifyCompletionCandidates(completionCandidates, argumentSeparator,
                                        userOptionSet.getValue(argument));
                                // For this case also we should not
                                // increment the
                                // cursorPosition
                                if (completionCandidates.size() > 0) {
                                    incrementCursor = false;
                                }
                            }
                        }
                    } else {
                        // The completion candidates should be cleared if the Converter has
                        // populated it with some values
                        completionCandidates.clear();
                    }
                    if (incrementCursor) {
                        desiredCursorPosition += userOptionSet.getValue(argument).length()
                                + argumentSeparator.length();
                    }
                } else {
                    if (argument.isRequired()) {
                        // Here the converter will come in handy
                        // to get suggestion for arguments
                        if (getAllPossibleValuesForParameter(completionCandidates, argument, null,
                                commandTarget.getGfshMethodTarget())) {
                            if (completionCandidates.size() == 0) {
                                // Enable warning if nothing is returned
                                warning = true;
                            }
                        } else {
                            // The completion candidates should be cleared if the Converter has
                            // populated it with some values
                            completionCandidates.clear();
                            warning = true;
                        }
                    } else {
                        boolean checkForPossibleValues = true;
                        // This means that the argument is not mandatory
                        // Now here we need to check whether user wants to
                        // enter an option.
                        if (endsWithOptionSpecifiers(userOptionSet.getUserInput())
                                || hasOptionSpecified(userOptionSet.getUserInput())) {
                            // This means options have started, and we
                            // cannot have arguments after options
                            // So, we just skip checking for possible
                            // values
                            checkForPossibleValues = false;
                        }
                        // Just try getting the PossibleValues without
                        // aiming
                        if (checkForPossibleValues) {
                            getAllPossibleValuesForParameter(completionCandidates, argument, null,
                                    commandTarget.getGfshMethodTarget());
                        }
                    }
                    if (completionCandidates.size() > 0) {
                        modifyCompletionCandidates(completionCandidates, argumentSeparator, (String[]) null);
                    }
                }
                if (warning) {
                    String argMessage = argument.getArgumentName()
                            + ((argument.getHelp() != null && !argument.getHelp().equals(""))
                                    ? ": " + argument.getHelp()
                                    : "");
                    logWarning(CliStrings.format(CliStrings.GFSHPARSER__MSG__REQUIRED_ARGUMENT_0, argMessage));
                    return desiredCursorPosition + userOptionSet.getNoOfSpacesRemoved();
                }
            }
            argumentSeparator = SyntaxConstants.ARGUMENT_SEPARATOR;
        }
        if (completionCandidates.size() > 0) {
            return desiredCursorPosition + userOptionSet.getNoOfSpacesRemoved();
        }

        // Now process options

        boolean warningValueRequired = false;
        Option warningOption = null;

        for (Option option : commandTarget.getOptionParser().getOptions()) {
            if (userOptionSet.hasOption(option)) {
                // We are supporting option synonyms,
                // so we need to check that here
                for (String string : userOptionSet.getSplit()) {
                    if (string.startsWith(SyntaxConstants.LONG_OPTION_SPECIFIER)) {
                        // Remove option prefix
                        string = StringUtils.removeStart(string, SyntaxConstants.LONG_OPTION_SPECIFIER);
                        // Remove value specifier
                        string = StringUtils.removeEnd(string, SyntaxConstants.OPTION_VALUE_SPECIFIER);
                        if (!string.equals("")) {
                            if (option.getLongOption().equals(string)) {
                                // This means that user has entered the whole option and
                                // Increment desiredCursorPostion by the length of the
                                // option and the option specifier, including space
                                desiredCursorPosition += /* space */1
                                        + SyntaxConstants.LONG_OPTION_SPECIFIER.length()
                                        + option.getLongOption().length();
                                break;

                            } else {
                                // This is only possible if the user has
                                // entered one of the synonyms of the options
                                // which wasn't displayed initially
                                for (String optionSynonym : option.getSynonyms()) {
                                    if (optionSynonym.equals(string)) {
                                        // This means that what the user has
                                        // entered is actually a
                                        // synonym for the option
                                        desiredCursorPosition += /* space */1
                                                + SyntaxConstants.LONG_OPTION_SPECIFIER.length()
                                                + optionSynonym.length();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                optionsPresentMap.put(option.getLongOption(), option);

                // For option value

                if (userOptionSet.hasValue(option)) {
                    String value = userOptionSet.getValue(option);
                    boolean valueActuallySpecified = false;

                    String valueSeparator = SyntaxConstants.VALUE_SEPARATOR;
                    if (option.getValueSeparator() != null) {
                        valueSeparator = option.getValueSeparator();
                    }

                    // JOpt doesn't maintain trailing comma (separator), hence reading it from buffer.
                    boolean bufferEndsWithValueSeparator = remainingBuffer.endsWith(valueSeparator);
                    // Check whether the value assigned to the option is
                    // actually part of the split array or has been
                    // assigned using the specifiedDefaultValue attribute

                    // userOptionElement can be option name or value of that option.
                    // E.g. "--opt=val" has elements "opt" & "val"
                    for (String userOptionElement : userOptionSet.getSplit()) {
                        if (userOptionElement.equals(value)
                                || (userOptionElement).equals(value + valueSeparator)) {
                            valueActuallySpecified = true;
                        }
                    }
                    if (!valueActuallySpecified) {
                        continue;
                    }
                    boolean incrementCursor = true;
                    boolean considerLastValue = false;
                    int lengthToBeAdded = 0;
                    int lastIndexOf = 0;

                    // This should only be invoked if we don't have any
                    // completionCandidates beforeHand
                    if (completionCandidates.size() == 0) {
                        // Here also we might need to invoke converter to
                        // get values apt for the option
                        if (!endsWithOptionSpecifiers(userOptionSet.getUserInput())
                                && getAllPossibleValuesForParameter(completionCandidates, option, value,
                                        commandTarget.getGfshMethodTarget())) {

                            // If the value returned by getAllPossibleValues
                            // is the same as that entered by the
                            // user we need to remove it from the
                            // completionCandidates and move forward

                            String prefix = "";
                            String[] split = ParserUtils.splitValues(value, valueSeparator);

                            if (completionCandidates.size() > 0) {
                                if (PreprocessorUtils.isSyntaxValid(value) && bufferEndsWithValueSeparator) {
                                    // This means that the user wants to
                                    // enter more values,
                                    prefix = valueSeparator;
                                } else if (perfectMatch(completionCandidates, split)) {
                                    // If the user does not want to enter
                                    // more values, and it matches one
                                    // of the values then we do not
                                    // need to suggest anything for
                                    // this option
                                    completionCandidates.clear();
                                    considerLastValue = true;
                                } else if (ParserUtils.contains(value, valueSeparator)) {
                                    prefix = valueSeparator;
                                } else {
                                    incrementCursor = false;
                                    if (value.startsWith(" ")) {
                                        prefix = "  ";
                                    } else if (value.startsWith("\n")) {
                                        prefix = "\n";
                                    } else {
                                        prefix = SyntaxConstants.OPTION_VALUE_SPECIFIER;
                                    }
                                }
                            }
                            modifyCompletionCandidates(completionCandidates, prefix,
                                    bufferEndsWithValueSeparator, split);
                            if (completionCandidates.size() == 0) {
                                incrementCursor = true;
                                considerLastValue = true;
                            }
                        } else {
                            // The completion candidates should be cleared if the Converter has
                            // populated it with some values
                            completionCandidates.clear();
                            considerLastValue = true;
                        }
                    } else {
                        // Make everything true
                        considerLastValue = true;
                    }
                    // FIX for: 46265
                    // if bufferEndsWithValueSeparator, append a valueSeparator to get the real lastIndexOd
                    // e.g. Let's say remainingBuffer is: cmd --opt1=val1,val2,
                    // value would be: cmd --opt1=val1,val2 ---> not there's no comma in the end.
                    // This doesn't give us the real last index of valueSeparator, hence add extra
                    // valueSeparator.
                    lastIndexOf = ParserUtils.lastIndexOf(
                            bufferEndsWithValueSeparator ? value + valueSeparator : value, valueSeparator);
                    lengthToBeAdded = value.substring(0, (lastIndexOf > 0 ? lastIndexOf : value.length()))
                            .length();
                    // Increment desiredCursorPosition
                    if (incrementCursor) {
                        desiredCursorPosition += /* value specifier length */SyntaxConstants.OPTION_VALUE_SPECIFIER
                                .length() + lengthToBeAdded
                                + ((considerLastValue) ? value.length() - lengthToBeAdded : 0);
                        if (value.endsWith(" ") && considerLastValue) {
                            desiredCursorPosition--;
                        }
                    }
                    if (completionCandidates.size() == 0) {
                        if (!PreprocessorUtils.isSyntaxValid(value)) {
                            return desiredCursorPosition + userOptionSet.getNoOfSpacesRemoved();
                        } else {
                            // Check whether the value ends with
                            // VALUE_SEPARATOR,
                            // if yes then we need to return
                            if (value.endsWith(valueSeparator)) {
                                return desiredCursorPosition + userOptionSet.getNoOfSpacesRemoved();
                            }
                        }
                    }
                } else {
                    // Here the converter is useful to invoke
                    // auto-suggestion, get Values from Converter
                    if (completionCandidates.size() == 0) {
                        if (getAllPossibleValuesForParameter(completionCandidates, option, null,
                                commandTarget.getGfshMethodTarget())) {
                            if (completionCandidates.size() == 0) {
                                warningValueRequired = true;
                            } else {
                                modifyCompletionCandidates(completionCandidates,
                                        SyntaxConstants.OPTION_VALUE_SPECIFIER, new String[] { null });
                            }
                        } else {
                            // The completion candidates should be cleared if the Converter
                            // has populated it with some values
                            completionCandidates.clear();
                            warningValueRequired = true;
                        }
                    }
                }
            } else {

                // As we have reached here, the OptionParser was not able to
                // detect anything which proves that the option is present
                // So, we check with what the user provided and add only
                // that to the list of options to prompt for

                for (String userOptString : userOptionSet.getSplit()) {
                    // Now to determine whether what the user specified was
                    // an option, we need to check whether it starts
                    // with an option specifier
                    if (userOptString.startsWith(SyntaxConstants.LONG_OPTION_SPECIFIER)) {
                        // Now remove the option specifier part
                        userOptString = StringUtils.removeStart(userOptString,
                                SyntaxConstants.LONG_OPTION_SPECIFIER);
                        if (option.getLongOption().startsWith(userOptString) && !userOptString.equals("")
                                && !option.getLongOption().equals(userOptString)
                                && !optionsPresentMap.containsKey(userOptString)) {

                            completionCandidates.add(new Completion(
                                    " " + SyntaxConstants.LONG_OPTION_SPECIFIER + option.getLongOption(),
                                    option.getLongOption(), "", 0));
                        } else {
                            for (String optionSynonym : option.getSynonyms()) {
                                if (optionSynonym.startsWith(userOptString) && !userOptString.equals("")
                                        && !optionSynonym.equals(userOptString)) {
                                    completionCandidates.add(new Completion(
                                            " " + SyntaxConstants.LONG_OPTION_SPECIFIER + optionSynonym,
                                            optionSynonym, "", 0));
                                    break;
                                }
                            }
                        }
                    }
                }

                if (completionCandidates.size() == 0) {
                    if (option.isRequired()) {
                        mandatoryOptions.add(option);
                    } else {
                        unspecifiedOptions.add(option);
                    }
                }
            }
            if (warningValueRequired/* || warningMultipleValuesNotSupported */) {
                warningOption = option;
                warningValueRequired = false;
            }
        }

        // Display warning if something not specified
        if (warningOption != null) {
            String optionMsg = warningOption.getLongOption()
                    + ((warningOption.getHelp() != null && !warningOption.getHelp().equals(""))
                            ? ": " + warningOption.getHelp()
                            : "");
            logWarning(CliStrings.format(CliStrings.GFSHPARSER__MSG__VALUE_REQUIRED_FOR_OPTION_0, optionMsg));

            desiredCursorPosition += userOptionSet.getNoOfSpacesRemoved();
            completionCandidates.add(new Completion(SyntaxConstants.OPTION_VALUE_SPECIFIER, "", null, 0));
            return desiredCursorPosition;
        }

    }

    // Calculate the cursor position
    int newCursor = desiredCursorPosition
            + ((userOptionSet != null) ? userOptionSet.getNoOfSpacesRemoved() : 0);

    String subString = remainingBuffer;
    if (newCursor != cursorStart) {
        int sizedReducedAdj = sizeReduced ? -1 : 0;
        int begin = newCursor + sizedReducedAdj - cursorStart;
        subString = remainingBuffer.substring(begin).trim();
    }

    // Exception handling
    if (coe != null // hasException
            && newCursor < cursor // newCursorIsEarlierThanCursor
            && completionCandidates.size() == 0 // zeroCompletionCandidates
            && !(PreprocessorUtils.containsOnlyWhiteSpaces(subString) // onlyHasWhiteSpaces
                    || ((subString.endsWith(SyntaxConstants.LONG_OPTION_SPECIFIER)
                            && subString.startsWith(SyntaxConstants.LONG_OPTION_SPECIFIER)) // isHypenHyphen
                            || (subString.startsWith(SyntaxConstants.SHORT_OPTION_SPECIFIER)
                                    && subString.endsWith(SyntaxConstants.SHORT_OPTION_SPECIFIER))))) { // isHyphen

        ExceptionHandler.handleException(coe);
        return cursor;
    }

    // If nothing has been specified for auto-completion then we need to suggest options
    if (completionCandidates.size() == 0) {
        if (mandatoryOptions.size() > 0) {

            for (Option option : mandatoryOptions) {
                completionCandidates.add(
                        new Completion(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + option.getLongOption(),
                                option.getLongOption(), "", 0));
            }
        } else {
            // As all the mandatory options have been specified we can prompt the
            // user for optional options.
            unspecifiedOptions = getUnspecifiedOptionsWithMode(unspecifiedOptions, commandTarget,
                    optionsPresentMap);
            for (Option option : unspecifiedOptions) {
                completionCandidates.add(
                        new Completion(" " + SyntaxConstants.LONG_OPTION_SPECIFIER + option.getLongOption(),
                                option.getLongOption(), "", 0));
            }
        }
    }
    return newCursor;
}

From source file:org.apache.geode.management.internal.cli.GfshParser.java

/**
 *
 *///from   ww w  . j a v a2s  .  co  m
public ParseResult parse(String userInput) {
    GfshParseResult parseResult = null;
    // First remove the trailing white spaces
    userInput = StringUtils.stripEnd(userInput, null);
    if ((ParserUtils.contains(userInput, SyntaxConstants.COMMAND_DELIMITER)
            && StringUtils.endsWithIgnoreCase(userInput, SyntaxConstants.COMMAND_DELIMITER))) {
        userInput = StringUtils.removeEnd(userInput, SyntaxConstants.COMMAND_DELIMITER);
    }

    try {
        boolean error = false;
        CliCommandOptionException coe = null;
        List<CommandTarget> targets = locateTargets(ParserUtils.trimBeginning(userInput), false);
        if (targets.size() > 1) {
            if (userInput.length() > 0) {
                handleCondition(CliStrings.format(
                        CliStrings.GFSHPARSER__MSG__AMBIGIOUS_COMMAND_0_FOR_ASSISTANCE_USE_1_OR_HINT_HELP,
                        new Object[] { userInput, AbstractShell.completionKeys }),
                        CommandProcessingException.COMMAND_NAME_AMBIGUOUS, userInput);
            }
        } else {
            if (targets.size() == 1) {
                OptionSet parse = null;
                List<MethodParameter> parameters = new ArrayList<MethodParameter>();
                Map<String, String> paramValMap = new HashMap<String, String>();
                CommandTarget commandTarget = targets.get(0);
                GfshMethodTarget gfshMethodTarget = commandTarget.getGfshMethodTarget();
                preConfigureConverters(commandTarget);

                try {
                    parse = commandTarget.getOptionParser().parse(gfshMethodTarget.getRemainingBuffer());
                } catch (CliException ce) {
                    if (ce instanceof CliCommandOptionException) {
                        coe = (CliCommandOptionException) ce;
                        coe.setCommandTarget(commandTarget);
                        parse = coe.getOptionSet();
                        error = true;
                    }
                }

                try {
                    checkOptionSetForValidCommandModes(parse, commandTarget);
                } catch (CliCommandMultiModeOptionException ce) {
                    error = true;
                    coe = ce;
                }

                error = processArguments(parse, commandTarget, paramValMap, parameters, error);
                // TODO: next call throws when space before closing "
                error = processOptions(parse, commandTarget, paramValMap, parameters, error);

                if (!error) {
                    Object[] methodParameters = new Object[parameters.size()];
                    for (MethodParameter parameter : parameters) {
                        methodParameters[parameter.getParameterNo()] = parameter.getParameter();
                    }
                    parseResult = new GfshParseResult(gfshMethodTarget.getMethod(),
                            gfshMethodTarget.getTarget(), methodParameters, userInput,
                            commandTarget.getCommandName(), paramValMap);
                } else {
                    if (coe != null) {
                        logWrapper.fine("Handling exception: " + coe.getMessage());
                        ExceptionHandler.handleException(coe); // TODO: this eats exception that would make it
                                                               // easier to debug GemfireDataCommandsDUnitTest
                                                               // ExceptionHandler.handleException() only logs it on console.
                                                               // When on member, we need to handle this.
                        if (!CliUtil.isGfshVM()) {
                            handleCondition(
                                    CliStrings.format(CliStrings.GFSHPARSER__MSG__INVALID_COMMAND_STRING_0,
                                            userInput),
                                    coe, CommandProcessingException.COMMAND_INVALID, userInput);
                        }
                    }
                }

            } else {
                String message = CliStrings.format(CliStrings.GFSHPARSER__MSG__COMMAND_0_IS_NOT_VALID,
                        userInput);
                CommandTarget commandTarget = locateExactMatchingTarget(userInput);
                if (commandTarget != null) {
                    String commandName = commandTarget.getCommandName();
                    AvailabilityTarget availabilityIndicator = commandTarget.getAvailabilityIndicator();
                    message = CliStrings.format(CliStrings.GFSHPARSER__MSG__0_IS_NOT_AVAILABLE_REASON_1,
                            new Object[] { commandName, availabilityIndicator.getAvailabilityDescription() });
                }
                handleCondition(message, CommandProcessingException.COMMAND_INVALID_OR_UNAVAILABLE, userInput);
            }
        }
    } catch (IllegalArgumentException e1) {
        logWrapper.warning(CliUtil.stackTraceAsString(e1));
    } catch (IllegalAccessException e1) {
        logWrapper.warning(CliUtil.stackTraceAsString(e1));
    } catch (InvocationTargetException e1) {
        logWrapper.warning(CliUtil.stackTraceAsString(e1));
    }
    return parseResult;
}

From source file:org.apache.geode.management.internal.cli.parser.jopt.JoptOptionParser.java

public OptionSet parse(String userInput) throws CliCommandOptionException {
    OptionSet optionSet = new OptionSet();
    optionSet.setUserInput(userInput != null ? userInput.trim() : "");
    if (userInput != null) {
        TrimmedInput input = PreprocessorUtils.trim(userInput);
        String[] preProcessedInput = preProcess(new HyphenFormatter().formatCommand(input.getString()));
        joptsimple.OptionSet joptOptionSet = null;
        CliCommandOptionException ce = null;
        // int factor = 0;
        try {//from  www. ja v  a 2s .  c om
            joptOptionSet = parser.parse(preProcessedInput);
        } catch (OptionException e) {
            ce = processException(e);
            // TODO: joptOptionSet = e.getDetected(); // removed when geode-joptsimple was removed
        }
        if (joptOptionSet != null) {

            // Make sure there are no miscellaneous, unknown strings that cannot be identified as
            // either options or arguments.
            if (joptOptionSet.nonOptionArguments().size() > arguments.size()) {
                String unknownString = (String) joptOptionSet.nonOptionArguments().get(arguments.size()); // added
                                                                                                          // cast
                                                                                                          // when
                                                                                                          // geode-joptsimple
                                                                                                          // was
                                                                                                          // removed
                                                                                                          // If the first option is un-parseable then it will be returned as "<option>=<value>"
                                                                                                          // since it's
                                                                                                          // been interpreted as an argument. However, all subsequent options will be returned as
                                                                                                          // "<option>".
                                                                                                          // This hack splits off the string before the "=" sign if it's the first case.
                if (unknownString.matches("^-*\\w+=.*$")) {
                    unknownString = unknownString.substring(0, unknownString.indexOf('='));
                }
                // TODO: ce =
                // processException(OptionException.createUnrecognizedOptionException(unknownString,
                // joptOptionSet)); // removed when geode-joptsimple was removed
            }

            // First process the arguments
            StringBuffer argument = new StringBuffer();
            int j = 0;
            for (int i = 0; i < joptOptionSet.nonOptionArguments().size() && j < arguments.size(); i++) {
                argument = argument.append(joptOptionSet.nonOptionArguments().get(i));
                // Check for syntax of arguments before adding them to the
                // option set as we want to support quoted arguments and those
                // in brackets
                if (PreprocessorUtils.isSyntaxValid(argument.toString())) {
                    optionSet.put(arguments.get(j), argument.toString());
                    j++;
                    argument.delete(0, argument.length());
                }
            }
            if (argument.length() > 0) {
                // Here we do not need to check for the syntax of the argument
                // because the argument list is now over and this is the last
                // argument which was not added due to improper syntax
                optionSet.put(arguments.get(j), argument.toString());
            }

            // Now process the options
            for (Option option : options) {
                List<String> synonyms = option.getAggregate();
                for (String string : synonyms) {
                    if (joptOptionSet.has(string)) {
                        // Check whether the user has actually entered the
                        // full option or just the start
                        boolean present = false;
                        outer: for (String inputSplit : preProcessedInput) {
                            if (inputSplit.startsWith(SyntaxConstants.LONG_OPTION_SPECIFIER)) {
                                // Remove option prefix
                                inputSplit = StringUtils.removeStart(inputSplit,
                                        SyntaxConstants.LONG_OPTION_SPECIFIER);
                                // Remove value specifier
                                inputSplit = StringUtils.removeEnd(inputSplit,
                                        SyntaxConstants.OPTION_VALUE_SPECIFIER);
                                if (!inputSplit.equals("")) {
                                    if (option.getLongOption().equals(inputSplit)) {
                                        present = true;
                                        break outer;
                                    } else {
                                        for (String optionSynonym : option.getSynonyms()) {
                                            if (optionSynonym.equals(inputSplit)) {
                                                present = true;
                                                break outer;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (present) {
                            if (joptOptionSet.hasArgument(string)) {
                                List<?> arguments = joptOptionSet.valuesOf(string);
                                if (arguments.size() > 1
                                        && !(option.getConverter() instanceof MultipleValueConverter)
                                        && option.getValueSeparator() == null) {
                                    List<String> optionList = new ArrayList<String>(1);
                                    optionList.add(string);
                                    // TODO: ce = processException(new
                                    // MultipleArgumentsForOptionException(optionList, joptOptionSet)); // removed
                                    // when geode-joptsimple was removed
                                } else if ((arguments.size() == 1
                                        && !(option.getConverter() instanceof MultipleValueConverter))
                                        || option.getValueSeparator() == null) {
                                    optionSet.put(option, arguments.get(0).toString().trim());
                                } else {
                                    StringBuffer value = new StringBuffer();
                                    String valueSeparator = option.getValueSeparator();
                                    for (Object object : joptOptionSet.valuesOf(string)) {
                                        if (value.length() == 0) {
                                            value.append((String) object);
                                        } else {
                                            if (valueSeparator != null) {
                                                value.append(valueSeparator + ((String) object).trim());
                                            } else {
                                                value.append(((String) object).trim());
                                            }
                                        }
                                    }
                                    optionSet.put(option, value.toString());
                                }
                            } else {
                                optionSet.put(option, option.getSpecifiedDefaultValue());
                            }
                            break;
                        }
                    }
                }
            }
        }

        // Convert the preProcessedInput into List<String>
        List<String> split = new ArrayList<String>();
        for (int i = 0; i < preProcessedInput.length; i++) {
            split.add(preProcessedInput[i]);
        }
        optionSet.setNoOfSpacesRemoved(input.getNoOfSpacesRemoved() /* + factor */);
        optionSet.setSplit(split);
        if (ce != null) {
            ce.setOptionSet(optionSet);
            throw ce;
        }
    }
    return optionSet;
}

From source file:org.apache.gobblin.cluster.GobblinClusterManager.java

/**
 * Create the service based application launcher and other associated services
 * @throws Exception//from  ww w  .j av a2s  .c  o  m
 */
private void initializeAppLauncherAndServices() throws Exception {
    // Done to preserve backwards compatibility with the previously hard-coded timeout of 5 minutes
    Properties properties = ConfigUtils.configToProperties(this.config);
    if (!properties.contains(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS)) {
        properties.setProperty(ServiceBasedAppLauncher.APP_STOP_TIME_SECONDS, Long.toString(300));
    }
    this.applicationLauncher = new ServiceBasedAppLauncher(properties, this.clusterName);

    // create a job catalog for keeping track of received jobs if a job config path is specified
    if (this.config.hasPath(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX
            + ConfigurationKeys.JOB_CONFIG_FILE_GENERAL_PATH_KEY)) {
        String jobCatalogClassName = ConfigUtils.getString(config,
                GobblinClusterConfigurationKeys.JOB_CATALOG_KEY,
                GobblinClusterConfigurationKeys.DEFAULT_JOB_CATALOG);

        this.jobCatalog = (MutableJobCatalog) GobblinConstructorUtils
                .invokeFirstConstructor(Class.forName(jobCatalogClassName),
                        ImmutableList.of(config
                                .getConfig(StringUtils
                                        .removeEnd(GobblinClusterConfigurationKeys.GOBBLIN_CLUSTER_PREFIX, "."))
                                .withFallback(this.config)));
    } else {
        this.jobCatalog = null;
    }

    SchedulerService schedulerService = new SchedulerService(properties);
    this.applicationLauncher.addService(schedulerService);
    this.jobScheduler = buildGobblinHelixJobScheduler(config, this.appWorkDir,
            getMetadataTags(clusterName, applicationId), schedulerService);
    this.applicationLauncher.addService(this.jobScheduler);
    this.jobConfigurationManager = buildJobConfigurationManager(config);
    this.applicationLauncher.addService(this.jobConfigurationManager);
}

From source file:org.apache.gobblin.compaction.parser.CompactionPathParser.java

private void parseTimeAndDatasetName(FileSystemDataset dataset, CompactionParserResult rst) {
    String commonBase = rst.getSrcBaseDir();
    String fullPath = dataset.datasetURN();
    int startPos = fullPath.indexOf(commonBase) + commonBase.length();
    String relative = StringUtils.removeStart(fullPath.substring(startPos), "/");

    int delimiterStart = StringUtils.indexOf(relative, rst.getSrcSubDir());
    if (delimiterStart == -1) {
        throw new StringIndexOutOfBoundsException();
    }//  ww w . jav a  2 s .  c  om
    int delimiterEnd = relative.indexOf("/", delimiterStart);
    String datasetName = StringUtils.removeEnd(relative.substring(0, delimiterStart), "/");
    String timeString = StringUtils.removeEnd(relative.substring(delimiterEnd + 1), "/");
    rst.datasetName = datasetName;
    rst.timeString = timeString;
    rst.time = getTime(timeString);
}

From source file:org.apache.gobblin.config.store.zip.ZipFileConfigStore.java

/**
 * Retrieves all the children of the given {@link ConfigKeyPath} using {@link Files#walk} to list files
 *//*w ww . j  a va2 s. c o m*/
@Override
public Collection<ConfigKeyPath> getChildren(ConfigKeyPath configKey, String version)
        throws VersionDoesNotExistException {
    Preconditions.checkNotNull(configKey, "configKey cannot be null!");
    Preconditions.checkArgument(version.equals(getCurrentVersion()));

    List<ConfigKeyPath> children = new ArrayList<>();
    Path datasetDir = getDatasetDirForKey(configKey);

    try {

        if (!Files.exists(this.fs.getPath(datasetDir.toString()))) {
            return children;
        }

        Stream<Path> files = Files.walk(datasetDir, 1);

        for (Iterator<Path> it = files.iterator(); it.hasNext();) {
            Path path = it.next();

            if (Files.isDirectory(path) && !path.equals(datasetDir)) {
                children.add(configKey
                        .createChild(StringUtils.removeEnd(path.getName(path.getNameCount() - 1).toString(),
                                SingleLinkedListConfigKeyPath.PATH_DELIMETER)));
            }

        }
        return children;
    } catch (IOException e) {
        throw new RuntimeException(
                String.format("Error while getting children for configKey: \"%s\"", configKey), e);
    }
}