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

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

Introduction

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

Prototype

public static String removeStart(String str, String remove) 

Source Link

Document

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

Usage

From source file:org.apache.eagle.topology.resolver.impl.ClusterNodeAPITopologyRackResolver.java

@Override
public String resolve(String hostname) {
    String nodeid = hostname + ":" + hostPort;
    String requestUrl = activeApiUrl + "/" + nodeid;
    String rack = DEFAULT_RACK_NAME;
    InputStream is = null;/*from   w ww .j  a va2s.c  o  m*/
    try {
        is = InputStreamUtils.getInputStream(requestUrl, null, AppConstants.CompressionType.NONE);
        LOG.info("resolve rack by api url {}", requestUrl);
        Node node = OBJ_MAPPER.readValue(is, Node.class);
        rack = StringUtils.removeStart(node.getNode().getRack(), "/");
    } catch (Exception e) {
        LOG.warn("resolve rack by api url {} failed, {}", requestUrl, e);
        return rack;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                LOG.warn("{}", e);
            }
        }
    }
    return rack;
}

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;//from www .j  ava2 s .co 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

private CommandTarget locateExactMatchingTarget(final String userInput)// exact matching
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    CommandTarget commandTarget = null;//from w w w  .  j a v a  2  s  . c o  m

    Map<String, CommandTarget> commandTargetsMap = commandManager.getCommands();
    // Reverse sort the command names because we should start from longer names
    // E.g. Consider commands "A", "A B" & user input as "A B --opt1=val1"
    // In this case, "A B" is the most probable match & should be matched first
    // which can be achieved by reversing natural order of sorting.
    Set<String> commandNamesReverseSorted = new TreeSet<String>(Collections.reverseOrder());
    commandNamesReverseSorted.addAll(commandTargetsMap.keySet());

    // Now we need to locate the CommandTargets from the entries in the map
    for (final String commandName : commandNamesReverseSorted) {
        if (userInput.startsWith(commandName) && commandWordsMatch(userInput, commandName)) {
            // This means that the user has entered the command & name matches exactly
            commandTarget = commandTargetsMap.get(commandName);
            if (commandTarget != null) {
                String remainingBuffer = StringUtils.removeStart(userInput, commandName);
                commandTarget = commandTarget.duplicate(commandName, remainingBuffer);
                break;
            }
        }
    }
    return commandTarget;
}

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 w  ww  .  j ava 2 s.  c  o  m
            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.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();
    }/*  w  w w .j av  a2  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.hadoop.fs.azure.AzureNativeFileSystemStore.java

/**
 * Trims a suffix/prefix from the given string. For example if
 * s is given as "/xy" and toTrim is "/", this method returns "xy"
 *///from w  w  w .  java2  s .co m
private static String trim(String s, String toTrim) {
    return StringUtils.removeEnd(StringUtils.removeStart(s, toTrim), toTrim);
}

From source file:org.apache.jetspeed.portlets.spaces.PageNavigator.java

@Override
public void processAction(ActionRequest actionRequest, ActionResponse actionResponse)
        throws PortletException, IOException {
    String name = actionRequest.getParameter("name");
    String type = actionRequest.getParameter("type");
    String templatePage = StringUtils.defaultString(actionRequest.getParameter("templatePage"), null);

    SpaceBean space = (SpaceBean) actionRequest.getPortletSession().getAttribute(SpaceNavigator.ATTRIBUTE_SPACE,
            PortletSession.APPLICATION_SCOPE);

    if (space == null) {
        log.warn("Space not found in session.");
        return;//from   w w  w.j av  a 2s.c  om
    }

    if (StringUtils.isBlank(name)) {
        log.warn("Blank name to create a node of type " + type);
        return;
    }

    if (StringUtils.isBlank(type)) {
        throw new PortletException("Blank node type: " + type);
    }

    if ((Page.DOCUMENT_TYPE.equals(type) || (Folder.FOLDER_TYPE.equals(type)))
            && StringUtils.isBlank(templatePage)) {
        templatePage = actionRequest.getPreferences().getValue("defaultTemplatePage", null);

        if (StringUtils.isBlank(templatePage)) {
            throw new PortletException("Invalid template page: " + templatePage);
        }
    }

    try {
        RequestContext requestContext = (RequestContext) actionRequest
                .getAttribute(RequestContext.REQUEST_PORTALENV);
        ContentPage contentPage = requestContext.getPage();

        String spacePath = space.getPath();
        String contentPagePath = contentPage.getPath();
        String contentFolderPath = StringUtils
                .defaultIfEmpty(StringUtils.substringBeforeLast(contentPagePath, "/"), "/");
        String nodeName = name.replace(' ', '_');
        String nodePath = null;

        if (contentFolderPath.startsWith(spacePath)) {
            nodePath = StringUtils.removeEnd(contentFolderPath, "/") + "/"
                    + StringUtils.removeStart(nodeName, "/");
        } else {
            nodePath = StringUtils.removeEnd(spacePath, "/") + "/" + StringUtils.removeStart(nodeName, "/");
        }

        if (Page.DOCUMENT_TYPE.equals(type)) {
            String path = nodePath + Page.DOCUMENT_TYPE;
            Page source = pageManager.getPage(templatePage);
            Page newPage = pageManager.copyPage(source, path, false);
            newPage.setTitle(name);
            pageManager.updatePage(newPage);

            requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null);

            String redirect = admin.getPortalURL(actionRequest, actionResponse, path);
            actionResponse.sendRedirect(redirect);
        } else if (Folder.FOLDER_TYPE.equals(type)) {
            String path = nodePath;
            Folder folder = pageManager.newFolder(path);
            folder.setTitle(name);
            pageManager.updateFolder(folder);

            String defaultPagePath = folder.getPath() + "/" + Folder.FALLBACK_DEFAULT_PAGE;
            Page source = pageManager.getPage(templatePage);
            Page newPage = pageManager.copyPage(source, defaultPagePath, false);
            pageManager.updatePage(newPage);

            requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null);
        } else if (Link.DOCUMENT_TYPE.equals(type)) {
            String path = nodePath + Link.DOCUMENT_TYPE;
            Link link = pageManager.newLink(path);
            link.setTitle(name);
            pageManager.updateLink(link);

            requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null);
        }
    } catch (Exception e) {
        log.error("Failed to update page.", e);
    }
}

From source file:org.apache.lucene.search.SearchUtil.java

public static String removeTitle(String contents, String title) {
    if (contents.indexOf("$TITLE_START$") != -1 && contents.indexOf("$TITLE_END$") != -1) {
        StringBuilder sb = new StringBuilder(contents);
        int start = sb.indexOf("$TITLE_START$");
        int end = sb.indexOf("$TITLE_END$");
        String tmp = sb.replace(start, end + "$TITLE_END$".length(), "").toString();
        return StringUtils.removeStart(tmp, title);
    } else {//from  ww  w  . jav a  2  s  .c  o m
        return contents;
    }
}

From source file:org.apache.maven.scm.provider.svn.svnjava.command.status.SvnStatusHandler.java

/**
 * This is  an  implementation  of {@link ISVNStatusHandler#handleStatus(org.tmatesoft.svn.core.wc.SVNStatus)
 *///ww w  .  j av a 2s .  co  m
public void handleStatus(SVNStatus status) {
    /* Gets  the  status  of  file/directory/symbolic link  text  contents.
     * It is  SVNStatusType  who  contains  information on the state of  an
     * item.
     */
    SVNStatusType contentsStatus = status.getCombinedNodeAndContentsStatus();
    //status.getContentsStatus();

    ScmFileStatus scmStatus = null;

    if (contentsStatus == SVNStatusType.STATUS_MODIFIED) {
        scmStatus = ScmFileStatus.MODIFIED;
    } else if (contentsStatus == SVNStatusType.STATUS_CONFLICTED) {
        scmStatus = ScmFileStatus.CONFLICT;
    } else if (contentsStatus == SVNStatusType.STATUS_MERGED) {
        /* The file item was merGed (changes that came from the  repository
         * did not overlap local changes and were merged into the file).
         * "G"
         */
        scmStatus = ScmFileStatus.PATCHED;
    } else if (contentsStatus == SVNStatusType.STATUS_DELETED) {
        /* The file, directory or symbolic link item has been scheduled for
         * Deletion from the repository.
         * "D"
         */
        scmStatus = ScmFileStatus.DELETED;
    } else if (contentsStatus == SVNStatusType.STATUS_ADDED) {
        /* The file, directory or symbolic link item has been scheduled for
         * Addition to the repository.
         * "A"
         */
        scmStatus = ScmFileStatus.ADDED;
    } else if (contentsStatus == SVNStatusType.STATUS_UNVERSIONED) {
        /* The file, directory or symbolic link item is not  under  version
         * control.
         * "?"
         */
        scmStatus = ScmFileStatus.UNKNOWN;
    } else if (contentsStatus == SVNStatusType.STATUS_EXTERNAL) {
        /* The item is unversioned, but is used by an eXternals definition.
         * "X"
         */
        scmStatus = ScmFileStatus.UNKNOWN;
    } else if (contentsStatus == SVNStatusType.STATUS_IGNORED) {
        /* The file, directory or symbolic link item is not  under  version
         * control, and is configured to be Ignored during 'add',  'import'
         * and 'status' operations.
         * "I"
         */
        // We don't care about files that are ignored.
        scmStatus = null;
    } else if (contentsStatus == SVNStatusType.STATUS_MISSING
            || contentsStatus == SVNStatusType.STATUS_INCOMPLETE) {
        /* The file, directory or  symbolic  link  item  is  under  version
         * control but is missing or somehow incomplete. The  item  can  be
         * missing if it is removed using a command incompatible  with  the
         * native Subversion command line client (for example, just removed
         * from the filesystem). In the case the item is  a  directory,  it
         * can  be  incomplete if the user happened to interrupt a checkout
         * or update.
         * "!"
         */
        // TODO: This isn't the right status here. ScmFileStatus doesn't have an error.
        scmStatus = ScmFileStatus.UNKNOWN;
    } else if (contentsStatus == SVNStatusType.STATUS_OBSTRUCTED) {
        /* The file, directory or symbolic link item is in  the  repository
         * as one kind of object, but what's actually in the user's working
         * copy is some other kind. For example, Subversion  might  have  a
         * file in the repository,  but  the  user  removed  the  file  and
         * created a directory in its place, without using the 'svn delete'
         * or 'svn add' command (or JavaSVN analogues for them).
         * "~"
         */
        // TODO: This isn't the right status here. ScmFileStatus doesn't have an error.
        scmStatus = ScmFileStatus.CONFLICT;
    } else if (contentsStatus == SVNStatusType.STATUS_REPLACED) {
        /* The file, directory or symbolic link item was  Replaced  in  the
         * user's working copy; that is, the item was deleted,  and  a  new
         * item with the same name was added (within  a  single  revision).
         * While they may have the same name, the repository considers them
         * to be distinct objects with distinct histories.
         * "R"
         */
        scmStatus = ScmFileStatus.ADDED;
    } else if (contentsStatus == SVNStatusType.STATUS_NONE || contentsStatus == SVNStatusType.STATUS_NORMAL) {
        /*
         * The item was not modified (normal).
         * " "
         */
        // Ignore these
        scmStatus = null;
    }

    /*
     * Now getting the status of properties of an item. SVNStatusType  also
     * contains information on the properties state.
     */
    SVNStatusType propertiesStatus = status.getPropertiesStatus();
    /*
     * Default - properties are normal (unmodified).
     */
    if (scmStatus == null && propertiesStatus == SVNStatusType.STATUS_MODIFIED) {
        /*
         * Properties were modified.
         * "M"
         */
        scmStatus = ScmFileStatus.MODIFIED;
    } else if (scmStatus == null && propertiesStatus == SVNStatusType.STATUS_CONFLICTED) {
        /*
         * Properties are in conflict with the repository.
         * "C"
         */
        scmStatus = ScmFileStatus.CONFLICT;
    }

    // Only add files and not directories to our list.
    if (scmStatus != null && status.getKind() != SVNNodeKind.DIR) {
        String normalizedPath = FilenameUtils.normalizeFilename(status.getFile().getAbsolutePath());
        normalizedPath = StringUtils.remove(normalizedPath,
                FilenameUtils.normalizeFilename(this.baseDir.getAbsolutePath()));

        normalizedPath = StringUtils.removeStart(normalizedPath, "/");
        files.add(new ScmFile(normalizedPath, scmStatus));
    }
}

From source file:org.apache.ranger.plugin.policyengine.RangerPolicyRepository.java

private RangerServiceDef normalizeAccessTypeDefs(RangerServiceDef serviceDef, final String componentType) {

    if (serviceDef != null && StringUtils.isNotBlank(componentType)) {

        List<RangerServiceDef.RangerAccessTypeDef> accessTypeDefs = serviceDef.getAccessTypes();

        if (CollectionUtils.isNotEmpty(accessTypeDefs)) {

            String prefix = componentType + AbstractServiceStore.COMPONENT_ACCESSTYPE_SEPARATOR;

            List<RangerServiceDef.RangerAccessTypeDef> unneededAccessTypeDefs = null;

            for (RangerServiceDef.RangerAccessTypeDef accessTypeDef : accessTypeDefs) {

                String accessType = accessTypeDef.getName();

                if (StringUtils.startsWith(accessType, prefix)) {

                    String newAccessType = StringUtils.removeStart(accessType, prefix);

                    accessTypeDef.setName(newAccessType);

                    Collection<String> impliedGrants = accessTypeDef.getImpliedGrants();

                    if (CollectionUtils.isNotEmpty(impliedGrants)) {

                        Collection<String> newImpliedGrants = null;

                        for (String impliedGrant : impliedGrants) {

                            if (StringUtils.startsWith(impliedGrant, prefix)) {

                                String newImpliedGrant = StringUtils.removeStart(impliedGrant, prefix);

                                if (newImpliedGrants == null) {
                                    newImpliedGrants = new ArrayList<String>();
                                }//from  ww  w  .j  a va 2s  .  com

                                newImpliedGrants.add(newImpliedGrant);
                            }
                        }
                        accessTypeDef.setImpliedGrants(newImpliedGrants);

                    }
                } else if (StringUtils.contains(accessType,
                        AbstractServiceStore.COMPONENT_ACCESSTYPE_SEPARATOR)) {
                    if (unneededAccessTypeDefs == null) {
                        unneededAccessTypeDefs = new ArrayList<RangerServiceDef.RangerAccessTypeDef>();
                    }

                    unneededAccessTypeDefs.add(accessTypeDef);
                }
            }

            if (unneededAccessTypeDefs != null) {
                accessTypeDefs.removeAll(unneededAccessTypeDefs);
            }
        }
    }

    return serviceDef;
}