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

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

Introduction

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

Prototype

public static String removeEnd(final String str, final String remove) 

Source Link

Document

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

A null source string will return null .

Usage

From source file:org.kuali.coeus.org.kuali.rice.krad.uif.container.KcLightTable.java

/**
 * Build the rows from the rowTemplate passed in.  This method uses regex to locate pieces of the row that need
 * to be replaced with row specific content per row.
 *
 * @param view the view instance the table is being built within
 * @param rowTemplate the first row of the collection in html generated from the ftl
 * @param model the model//from  www. j a  v a2s . c om
 */
public void buildRows(View view, String rowTemplate, UifFormBase model) {
    if (StringUtils.isBlank(rowTemplate)) {
        return;
    }

    rowTemplate = StringUtils.removeEnd(rowTemplate, ",");
    rowTemplate = rowTemplate.replace("\n", "");
    rowTemplate = rowTemplate.replace("\r", "");

    StringBuffer rows = new StringBuffer();
    List<Object> collectionObjects = ObjectPropertyUtils.getPropertyValue(model, bindingInfo.getBindingPath());

    //uncheck any checked checkboxes globally for this row
    rowTemplate = rowTemplate.replace("checked=\"checked\"", "");

    //init token patterns
    Pattern idPattern = Pattern.compile(ID_TOKEN + "(.*?)" + ID_TOKEN);
    Pattern expressionPattern = Pattern.compile(EXPRESSION_TOKEN + "(.*?)" + EXPRESSION_TOKEN);

    ExpressionEvaluator expressionEvaluator = ViewLifecycle.getExpressionEvaluator();
    expressionEvaluator.initializeEvaluationContext(model);

    int lineIndex = 0;
    for (Object obj : collectionObjects) {
        //add line index to all ids
        String row = idPattern.matcher(rowTemplate).replaceAll("$1" + UifConstants.IdSuffixes.LINE + lineIndex);

        //create the expanded context
        Map<String, Object> expandedContext = new HashMap<String, Object>();
        expandedContext.put(UifConstants.ContextVariableNames.LINE, obj);
        expandedContext.put(UifConstants.ContextVariableNames.INDEX, lineIndex);
        expandedContext.put(UifConstants.ContextVariableNames.VIEW, view);

        currentColumnValue = "";

        int itemIndex = 0;
        for (Component item : this.getItems()) {
            //determine original id for this component
            String originalId = initialComponentIds.get(itemIndex);

            //special DataField handling
            row = handleDataFieldInRow(item, obj, row, lineIndex, originalId);

            //special InputField handling
            row = handleInputFieldInRow(item, obj, row, lineIndex, originalId);

            //add item context
            if (item.getContext() != null) {
                expandedContext.putAll(item.getContext());
            }

            //evaluate expressions found by the pattern
            row = evaluateAndReplaceExpressionValues(row, lineIndex, model, expandedContext, expressionPattern,
                    expressionEvaluator);

            if (currentColumnValue == null) {
                currentColumnValue = "";
            }

            row = row.replace(SORT_VALUE + itemIndex + A_TOKEN, currentColumnValue);

            itemIndex++;
        }

        // get rowCss class
        boolean isOdd = lineIndex % 2 == 0;
        String rowCss = KRADUtils.generateRowCssClassString(conditionalRowCssClasses, lineIndex, isOdd,
                expandedContext, expressionEvaluator);

        row = row.replace("\"", "\\\"");
        row = row.replace(ROW_CLASS, rowCss);
        row = "{" + row + "},";

        //special render property expression handling
        row = evaluateRenderExpressions(row, lineIndex, model, expandedContext, expressionEvaluator);

        //append row
        rows.append(row);
        lineIndex++;
    }

    StringBuffer tableToolsColumnOptions = new StringBuffer("[");
    for (int index = 0; index < this.getItems().size(); index++) {
        String colOptions = richTable.constructTableColumnOptions(index, true, false, String.class, null);
        tableToolsColumnOptions.append(colOptions + " , ");
    }

    String aoColumnDefs = StringUtils.removeEnd(tableToolsColumnOptions.toString(), " , ") + "]";
    Map<String, String> rtTemplateOptions = richTable.getTemplateOptions();

    if (rtTemplateOptions == null) {
        richTable.setTemplateOptions(rtTemplateOptions = new HashMap<String, String>());
    }

    rtTemplateOptions.put(UifConstants.TableToolsKeys.AO_COLUMN_DEFS, aoColumnDefs);

    // construct aaData option to set data in dataTable options (speed enhancement)
    String aaData = StringUtils.removeEnd(rows.toString(), ",");
    aaData = "[" + aaData + "]";
    aaData = aaData.replace(KRADConstants.QUOTE_PLACEHOLDER, "\"");

    //set the aaData option on datatable for faster rendering
    rtTemplateOptions.put(UifConstants.TableToolsKeys.AA_DATA, aaData);

    //make sure deferred rendering is forced whether set or not
    rtTemplateOptions.put(UifConstants.TableToolsKeys.DEFER_RENDER, UifConstants.TableToolsValues.TRUE);
}

From source file:org.kuali.kra.lookup.keyvalue.LookupableBoValuesFinder.java

@Override
public List<KeyValue> getKeyValues() {
    List<KeyValue> keyValues = new ArrayList<KeyValue>();

    DataDictionaryService dataDictionaryService = KcServiceLocator.getService(DataDictionaryService.class);
    // this only has entries that have been loaded - force load?

    Map<String, BusinessObjectEntry> businessObjectEntries = dataDictionaryService.getDataDictionary()
            .getBusinessObjectEntries();

    Map<String, Integer> labelCounts = getLabelCounts(businessObjectEntries);

    for (String businessObject : businessObjectEntries.keySet()) {
        org.kuali.rice.kns.datadictionary.BusinessObjectEntry businessObjectEntry = (org.kuali.rice.kns.datadictionary.BusinessObjectEntry) businessObjectEntries
                .get(businessObject);// w w  w  .ja  va2 s. c  o  m
        if ((businessObjectEntry.hasLookupDefinition())
                && (kcBo(businessObject) || supportedRiceBo(businessObject))) {
            String key = businessObject;

            String label = StringUtils.removeEnd(businessObjectEntry.getLookupDefinition().getTitle().trim(),
                    " Lookup");

            if (labelCounts.get(label) > 1) {
                label = label + " (" + key.toString().substring(key.toString().lastIndexOf(".") + 1) + ")";
            }

            KeyValue KeyValue = new ConcreteKeyValue(key, label);
            if (!keyValues.contains(KeyValue)) {
                keyValues.add(KeyValue);
            }
        }
    }

    // added comparator below to alphabetize lists on label
    Collections.sort(keyValues, new KeyValueComparator());
    keyValues.add(0, new ConcreteKeyValue("", "select"));

    return keyValues;
}

From source file:org.kuali.kra.lookup.keyvalue.LookupableBoValuesFinder.java

public Map<String, Integer> getLabelCounts(Map<String, BusinessObjectEntry> businessObjectEntries) {
    Map<String, Integer> labels = new HashMap<String, Integer>();

    for (String businessObject : businessObjectEntries.keySet()) {
        org.kuali.rice.kns.datadictionary.BusinessObjectEntry businessObjectEntry = (org.kuali.rice.kns.datadictionary.BusinessObjectEntry) businessObjectEntries
                .get(businessObject);//  www .ja  v  a  2s. com
        if ((businessObjectEntry.hasLookupDefinition())
                && (kcBo(businessObject) || supportedRiceBo(businessObject))) {
            String label = StringUtils.removeEnd(businessObjectEntry.getLookupDefinition().getTitle().trim(),
                    " Lookup");
            if (labels.containsKey(label)) {
                Integer count = labels.get(label) + 1;
                labels.put(label, count);
            } else {
                labels.put(label, 1);
            }
        }
    }

    return labels;
}

From source file:org.languagetool.rules.de.CaseRule.java

private boolean isLanguage(int i, AnalyzedTokenReadings[] tokens, String token) {
    boolean maybeLanguage = (token.endsWith("sch") && languages.contains(token))
            || languages.contains(StringUtils.removeEnd(StringUtils.removeEnd(token, "n"), "e")); // z.B. "im Japanischen" / z.B. "ins Japanische bersetzt"
    AnalyzedTokenReadings prevToken = i > 0 ? tokens[i - 1] : null;
    AnalyzedTokenReadings nextReadings = i < tokens.length - 1 ? tokens[i + 1] : null;
    return maybeLanguage
            && (!hasNounReading(nextReadings) || (prevToken != null && prevToken.getToken().equals("auf")));
}

From source file:org.languagetool.rules.de.GermanSpellerRule.java

private boolean ignoreByHangingHyphen(List<String> words, int idx) throws IOException {
    String word = words.get(idx);
    String nextWord = getWordAfterEnumerationOrNull(words, idx + 1);
    nextWord = StringUtils.removeEnd(nextWord, ".");

    boolean isCompound = nextWord != null
            && (compoundTokenizer.tokenize(nextWord).size() > 1 || nextWord.indexOf('-') > 0);
    if (isCompound) {
        word = StringUtils.removeEnd(word, "-");
        boolean isMisspelled = hunspellDict.misspelled(word); // "Stil- und Grammatikprfung" or "Stil-, Text- und Grammatikprfung"
        if (isMisspelled && (super.ignoreWord(word) || wordsToBeIgnoredInCompounds.contains(word))) {
            isMisspelled = false;/* w  w w  .  j  a v  a  2 s .c  o m*/
        } else if (isMisspelled && word.endsWith("s") && isNeedingFugenS(StringUtils.removeEnd(word, "s"))) {
            // Vertuschungs- und Bespitzelungsmanahmen: remove trailing "s" before checking "Vertuschungs" so that the spell checker finds it
            isMisspelled = hunspellDict.misspelled(StringUtils.removeEnd(word, "s"));
        }
        return !isMisspelled;
    }
    return false;
}

From source file:org.languagetool.rules.spelling.hunspell.CompoundAwareHunspellRule.java

protected List<String> getCandidates(List<String> parts) {
    int partCount = 0;
    List<String> candidates = new ArrayList<>();
    for (String part : parts) {
        if (hunspellDict.misspelled(part)) {
            // assume noun, so use uppercase:
            boolean doUpperCase = partCount > 0 && !StringTools.startsWithUppercase(part);
            List<String> suggestions = morfoSpeller
                    .getSuggestions(doUpperCase ? StringTools.uppercaseFirstChar(part) : part);
            if (suggestions.isEmpty()) {
                suggestions = morfoSpeller
                        .getSuggestions(doUpperCase ? StringTools.lowercaseFirstChar(part) : part);
            }// www. j a  v  a  2 s.  c  o  m
            boolean appendS = false;
            if (doUpperCase && part.endsWith("s")) { // maybe infix-s as in "Dampfschiffahrtskapitn" -> "Dampfschifffahrtskapitn"
                suggestions.addAll(morfoSpeller.getSuggestions(StringUtils.removeEnd(part, "s")));
                appendS = true;
            }
            for (String suggestion : suggestions) {
                List<String> partsCopy = new ArrayList<>(parts);
                if (appendS) {
                    suggestion += "s";
                }
                if (partCount > 0 && parts.get(partCount).startsWith("-")
                        && parts.get(partCount).length() > 1) {
                    partsCopy.set(partCount, "-" + StringTools.uppercaseFirstChar(suggestion.substring(1)));
                } else if (partCount > 0 && !parts.get(partCount - 1).endsWith("-")) {
                    partsCopy.set(partCount, suggestion.toLowerCase());
                } else {
                    partsCopy.set(partCount, suggestion);
                }
                String candidate = String.join("", partsCopy);
                if (!isMisspelled(candidate)) {
                    candidates.add(candidate);
                }
                // Arbeidszimmer -> Arbeitszimmer:
                if (partCount < parts.size() - 1 && part.endsWith("s") && suggestion.endsWith("-")) {
                    partsCopy.set(partCount, suggestion.substring(0, suggestion.length() - 1));
                    String infixCandidate = String.join("", partsCopy);
                    if (!isMisspelled(infixCandidate)) {
                        candidates.add(infixCandidate);
                    }
                }
            }
        }
        // What if there's no misspelled parts like for Arbeitamt = Arbeit+Amt ??
        // -> morfologik must be extended to return similar words even for known words
        // But GermanSpellerRule.getCandidates() has a solution for the cases with infix "s".
        partCount++;
    }
    return candidates;
}

From source file:org.languagetool.rules.spelling.hunspell.HunspellRule.java

private String removeTrailingDot(String word) {
    return StringUtils.removeEnd(word, ".");
}

From source file:org.languagetool.tagging.de.GermanTagger.java

public List<AnalyzedTokenReadings> tag(List<String> sentenceTokens, boolean ignoreCase) throws IOException {
    initializeIfRequired();/*from   w ww  .j  a  v  a  2s.co m*/

    boolean firstWord = true;
    List<AnalyzedTokenReadings> tokenReadings = new ArrayList<>();
    int pos = 0;

    String prevWord = null;
    for (String word : sentenceTokens) {
        List<AnalyzedToken> readings = new ArrayList<>();
        List<TaggedWord> taggerTokens = getWordTagger().tag(word);

        //Only first iteration. Consider ":" as a potential sentence start marker
        if ((firstWord || ":".equals(prevWord)) && taggerTokens.isEmpty() && ignoreCase) { // e.g. "Das" -> "das" at start of sentence
            taggerTokens = getWordTagger().tag(word.toLowerCase());
            firstWord = word.matches("^\\W?$");
        } else if (pos == 0 && ignoreCase) { // "Haben", "Sollen", "Knnen", "Gerade" etc. at start of sentence
            taggerTokens.addAll(getWordTagger().tag(word.toLowerCase()));
        } else if (pos > 1 && taggerTokens.isEmpty() && ignoreCase) {
            int idx = sentenceTokens.indexOf(word);
            // add lowercase token readings to words at start of direct speech
            if (idx > 2 && sentenceTokens.get(idx - 1).contentEquals("")
                    && sentenceTokens.get(idx - 3).contentEquals(":")) {
                taggerTokens.addAll(getWordTagger().tag(word.toLowerCase()));
            }
        }

        if (taggerTokens.size() > 0) { //Word known, just add analyzed token to readings
            readings.addAll(getAnalyzedTokens(taggerTokens, word));
        } else { // Word not known, try to decompose it and use the last part for POS tagging:
            if (!StringTools.isEmpty(word.trim())) {
                List<String> compoundParts = compoundTokenizer.tokenize(word);
                if (compoundParts.size() <= 1) {//Could not find simple compound parts
                    // Recognize alternative imperative forms (e.g., "Geh bitte!" in addition to "Gehe bitte!")
                    List<AnalyzedToken> imperativeFormList = getImperativeForm(word, sentenceTokens, pos);
                    List<AnalyzedToken> substantivatedFormsList = getSubstantivatedForms(word, sentenceTokens,
                            pos);
                    if (imperativeFormList.size() > 0) {
                        readings.addAll(imperativeFormList);
                    } else if (substantivatedFormsList.size() > 0) {
                        readings.addAll(substantivatedFormsList);
                    } else {
                        if (StringUtils.startsWithAny(word, "bitter", "dunkel", "erz", "extra", "frh",
                                "gemein", "hyper", "lau", "mega", "minder", "stock", "super", "tod", "ultra",
                                "ur")) {
                            String lastPart = RegExUtils.removePattern(word,
                                    "^(bitter|dunkel|erz|extra|frh|gemein|grund|hyper|lau|mega|minder|stock|super|tod|ultra|ur|voll)");
                            if (lastPart.length() > 1) {
                                String firstPart = StringUtils.removeEnd(word, lastPart);
                                List<TaggedWord> taggedWords = getWordTagger().tag(lastPart);
                                for (TaggedWord taggedWord : taggedWords) {
                                    readings.add(new AnalyzedToken(word, taggedWord.getPosTag(),
                                            firstPart + taggedWord.getLemma()));
                                }
                            }
                        }
                        //Separate dash-linked words
                        //Only check single word tokens and skip words containing numbers because it's unpredictable
                        if (word.split(" ").length == 1 && !Character.isDigit(word.charAt(0))) {
                            String wordOrig = word;
                            word = sanitizeWord(word);
                            String wordStem = wordOrig.substring(0, wordOrig.length() - word.length());

                            //Tokenize, start word uppercase if it's a result of splitting
                            List<String> compoundedWord = compoundTokenizer.tokenize(word);
                            if (compoundedWord.size() > 1) {
                                word = StringTools
                                        .uppercaseFirstChar(compoundedWord.get(compoundedWord.size() - 1));
                            } else {
                                word = compoundedWord.get(compoundedWord.size() - 1);
                            }

                            List<TaggedWord> linkedTaggerTokens = addStem(getWordTagger().tag(word), wordStem); //Try to analyze the last part found

                            //Some words that are linked with a dash ('-') will be written in uppercase, even adjectives
                            if (wordOrig.contains("-") && linkedTaggerTokens.isEmpty()
                                    && matchesUppercaseAdjective(word)) {
                                word = StringTools.lowercaseFirstChar(word);
                                linkedTaggerTokens = getWordTagger().tag(word);
                            }

                            word = wordOrig;

                            boolean wordStartsUppercase = StringTools.startsWithUppercase(word);
                            if (linkedTaggerTokens.isEmpty()) {
                                readings.add(getNoInfoToken(word));
                            } else {
                                if (wordStartsUppercase) { //Choose between uppercase/lowercase Lemma
                                    readings.addAll(getAnalyzedTokens(linkedTaggerTokens, word));
                                } else {
                                    readings.addAll(
                                            getAnalyzedTokens(linkedTaggerTokens, word, compoundedWord));
                                }
                            }
                        } else {
                            readings.add(getNoInfoToken(word));
                        }
                    }
                } else {
                    // last part governs a word's POS:
                    String lastPart = compoundParts.get(compoundParts.size() - 1);
                    if (StringTools.startsWithUppercase(word)) {
                        lastPart = StringTools.uppercaseFirstChar(lastPart);
                    }
                    List<TaggedWord> partTaggerTokens = getWordTagger().tag(lastPart);
                    if (partTaggerTokens.isEmpty()) {
                        readings.add(getNoInfoToken(word));
                    } else {
                        readings.addAll(getAnalyzedTokens(partTaggerTokens, word, compoundParts));
                    }
                }
            } else {
                readings.add(getNoInfoToken(word));
            }
        }
        tokenReadings.add(new AnalyzedTokenReadings(readings.toArray(new AnalyzedToken[readings.size()]), pos));
        pos += word.length();
        prevWord = word;
    }
    return tokenReadings;
}

From source file:org.lazulite.boot.autoconfigure.core.web.bind.util.ZTreeUtils.java

/***
 * ZTree ID ids ZTree ID  String  ?id/* w  ww  .  jav  a2  s. c  o m*/
 *
 * @param m
 * @param open
 * @param onlyCheckLeaf
 * @return
 */
public static <M extends BaseEntity<ID> & Treeable<ID>, ID extends Serializable> ZTree<String> convertToZtreeIdTotal(
        M m, boolean open, boolean onlyCheckLeaf) {
    ZTree<String> zTree = new ZTree<String>();
    zTree.setId(m.getParentIds() + m.getId());

    zTree.setPid(StringUtils.removeEnd(m.getParentIds(), m.getSeparator()));

    zTree.setName(m.getName());
    zTree.setIconSkin(m.getIcon());
    zTree.setOpen(open);
    zTree.setRoot(m.isRoot());
    zTree.setIsParent(m.isHasChildren());
    zTree.setDiy(m.getDiy());
    if (onlyCheckLeaf && zTree.isIsParent()) {
        zTree.setNocheck(true);
    } else {
        zTree.setNocheck(false);
    }

    return zTree;
}

From source file:org.lazydog.jdnsaas.utility.ZoneUtility.java

/**
 * Hide the constructor.//  ww w. ja va2  s.c o m
 * 
 * @param  zoneName  the zone name.
 */
private ZoneUtility(final String zoneName) {
    this.relativeZoneName = (zoneName.endsWith(LABEL_SEPARATOR))
            ? StringUtils.removeEnd(zoneName, LABEL_SEPARATOR)
            : zoneName;
}