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.kuali.rice.krad.lookup.LookupUtils.java

/**
 * Generates a key string in case of multivalue return. The values are extracted
 * from the list of properties on the lineDataObject.
 *
 * If fieldConversionKeys is empty return the identifier string for the lineDataObject
 *
 * @param lineDataObject   Object from which to extract values
 * @param fieldConversionKeys List of keys whose values have to be concatenated
 * @return string representing the multivalue key 
 *//*  w w  w  .  j  a v a  2s .co  m*/
public static String generateMultiValueKey(Object lineDataObject, List<String> fieldConversionKeys) {
    String lineIdentifier = "";

    if (fieldConversionKeys == null || fieldConversionKeys.isEmpty()) {
        lineIdentifier = KRADServiceLocatorWeb.getLegacyDataAdapter()
                .getDataObjectIdentifierString(lineDataObject);
    } else {
        Collections.sort(fieldConversionKeys);
        for (String fromFieldName : fieldConversionKeys) {
            Object fromFieldValue = ObjectPropertyUtils.getPropertyValue(lineDataObject, fromFieldName);

            if (fromFieldValue != null) {
                lineIdentifier += fromFieldValue;
            }

            lineIdentifier += ":";
        }
        lineIdentifier = StringUtils.removeEnd(lineIdentifier, ":");
    }

    return lineIdentifier;
}

From source file:org.kuali.rice.krad.service.impl.DataObjectMetaDataServiceImpl.java

/**
 * @see org.kuali.rice.krad.service.DataObjectMetaDataService#getDataObjectIdentifierString
 *///from w ww.  j  av a 2  s . com
@Override
public String getDataObjectIdentifierString(Object dataObject) {
    String identifierString = "";

    if (dataObject == null) {
        identifierString = "Null";
        return identifierString;
    }

    Class<?> dataObjectClass = dataObject.getClass();

    // if PBO, use object id property
    if (PersistableBusinessObject.class.isAssignableFrom(dataObjectClass)) {
        String objectId = ObjectPropertyUtils.getPropertyValue(dataObject, UifPropertyPaths.OBJECT_ID);
        if (StringUtils.isBlank(objectId)) {
            objectId = UUID.randomUUID().toString();
            ObjectPropertyUtils.setPropertyValue(dataObject, UifPropertyPaths.OBJECT_ID, objectId);
        }

        identifierString = objectId;
    } else {
        // build identifier string from primary key values
        Map<String, ?> primaryKeyFieldValues = getPrimaryKeyFieldValues(dataObject, true);
        for (Map.Entry<String, ?> primaryKeyValue : primaryKeyFieldValues.entrySet()) {
            if (primaryKeyValue.getValue() == null) {
                identifierString += "Null";
            } else {
                identifierString += primaryKeyValue.getValue();
            }
            identifierString += ":";
        }
        identifierString = StringUtils.removeEnd(identifierString, ":");
    }

    return identifierString;
}

From source file:org.kuali.rice.krad.service.impl.KRADLegacyDataAdapterImpl.java

/**
 * @see org.kuali.rice.krad.service.DataObjectMetaDataService#getDataObjectIdentifierString
 *///from   ww  w  .j ava 2s.  c  o m
@Override
public String getDataObjectIdentifierString(Object dataObject) {
    String identifierString = "";

    if (dataObject == null) {
        identifierString = "Null";
        return identifierString;
    }

    Class<?> dataObjectClass = dataObject.getClass();
    // build identifier string from primary key values
    Map<String, ?> primaryKeyFieldValues = getPrimaryKeyFieldValues(dataObject, true);
    for (Map.Entry<String, ?> primaryKeyValue : primaryKeyFieldValues.entrySet()) {
        if (primaryKeyValue.getValue() == null) {
            identifierString += "Null";
        } else {
            identifierString += primaryKeyValue.getValue();
        }
        identifierString += ":";
    }
    return StringUtils.removeEnd(identifierString, ":");
}

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

/**
 * Process the expression for the item by putting placeholder values in for String properties and adding markers
 * for render expressions to the component; adds the original expression to the expressionMap
 *
 * @param name the property name/*from w w  w  .j  av  a2 s.  c om*/
 * @param item the component this expressio is on
 * @param expressionMap the map to add expressions to
 * @param toRemove the property name is added this map to be removed later
 */
public void processExpression(String name, Component item, Map<String, String> expressionMap,
        List<String> toRemove) {
    Class<?> clazz = ObjectPropertyUtils.getPropertyType(item, name);
    if (clazz == null) {
        return;
    }

    if (clazz.isAssignableFrom(String.class)) {
        //add expressions for string properties only
        expressionMap.put(name + SEPARATOR + item.getId(), item.getExpressionGraph().get(name));
        toRemove.add(name);
        ObjectPropertyUtils.setPropertyValue(item, name,
                EXPRESSION_TOKEN + name + SEPARATOR + item.getId() + EXPRESSION_TOKEN);

    } else if (name.endsWith(RENDER) && clazz.isAssignableFrom(boolean.class)) {
        //setup render tokens to be able to determine where to remove content for render false, if needed
        Component renderComponent = item;

        //check for nested render (child element)
        if (!name.equals(RENDER)) {
            renderComponent = ObjectPropertyUtils.getPropertyValue(item,
                    StringUtils.removeEnd(name, ".render"));
        }

        //add render expression to the map
        renderIdExpressionMap.put(renderComponent.getId(), item.getExpressionGraph().get(name));
        toRemove.add(name);

        String renderMarker = A_TOKEN + RENDER + A_TOKEN + renderComponent.getId() + A_TOKEN;

        //setup pre render content token
        String pre = renderComponent.getPreRenderContent() == null ? "" : renderComponent.getPreRenderContent();
        renderComponent.setPreRenderContent(renderMarker + pre);

        //setup post render content token
        String post = renderComponent.getPostRenderContent() == null ? ""
                : renderComponent.getPostRenderContent();
        renderComponent.setPostRenderContent(post + renderMarker);

        //force render to true
        ObjectPropertyUtils.setPropertyValue(item, name, true);
    }
}

From source file:org.kuali.rice.krad.uif.container.LightTable.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 w w w  . jav a 2 s.co m
 */
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.rice.krad.uif.field.DataField.java

/**
 * Generates the html to be used and sets the readOnlyDisplayReplacement for DataFields that contain lists and
 * do not have their own readOnlyDisplayReplacement defined.  The type of html generated is based on the options
 * set on readOnlyListDisplayType and readOnlyListDelimiter.
 *
 * @param list the list to be converted to readOnly html
 *///from www.j  a  v a2  s.com
protected String generateReadOnlyListDisplayReplacement(List<?> list) {
    String generatedHtml = "";

    //Default to delimited if nothing is set
    if (getReadOnlyListDisplayType() == null) {
        this.setReadOnlyListDisplayType(UifConstants.ReadOnlyListTypes.DELIMITED.name());
    }

    //begin generation setup
    if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.UL.name())) {
        generatedHtml = "<ul class='uif-readOnlyStringList'>";
    } else if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.OL.name())) {
        generatedHtml = "<ol class='uif-readOnlyStringList'>";
    } else if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.BREAK.name())) {
        setReadOnlyListDelimiter("<br/>");
    } else if (this.getReadOnlyListDelimiter() == null) {
        setReadOnlyListDelimiter(", ");
    }

    //iterate through each value
    for (Object value : list) {
        //if blank skip
        if (!TypeUtils.isSimpleType(value.getClass()) || StringUtils.isBlank(value.toString())) {
            continue;
        }

        //handle mask if any
        if (isApplyMask()) {
            value = getMaskFormatter().maskValue(value);
        }

        //TODO the value should use the formatted text property value we would expect to see instead of toString
        //two types - delimited and html list
        if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.UL.name())
                || getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.OL.name())) {
            generatedHtml = generatedHtml + "<li>" + value.toString() + "</li>";
        } else {
            //no matching needed - delimited is always the fallback and break uses same logic
            generatedHtml = generatedHtml + value.toString() + this.getReadOnlyListDelimiter();
        }
    }

    //end the generation
    if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.UL.name())) {
        generatedHtml = generatedHtml + "</ul>";
    } else if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.OL.name())) {
        generatedHtml = generatedHtml + "</ol>";
    } else {
        generatedHtml = StringUtils.removeEnd(generatedHtml, this.getReadOnlyListDelimiter());
    }

    if (StringUtils.isNotBlank(generatedHtml)) {
        return generatedHtml;
    } else {
        //this must be done or the ftl will skip and throw error
        return "&nbsp;";
    }
}

From source file:org.kuali.rice.krad.uif.field.DataFieldBase.java

/**
 * Generates the html to be used and sets the readOnlyDisplayReplacement for DataFields that contain lists and
 * do not have their own readOnlyDisplayReplacement defined.  The type of html generated is based on the options
 * set on readOnlyListDisplayType and readOnlyListDelimiter.
 *
 * @param list the list to be converted to readOnly html
 *///from w  w  w  .j a va  2  s . co  m
protected String generateReadOnlyListDisplayReplacement(List<?> list) {
    //Default to delimited if nothing is set
    if (getReadOnlyListDisplayType() == null) {
        this.setReadOnlyListDisplayType(UifConstants.ReadOnlyListTypes.DELIMITED.name());
    }

    String generatedHtml = "";

    //begin generation setup
    if (!list.isEmpty()) {
        if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.UL.name())) {
            generatedHtml = "<ul class='uif-readOnlyStringList'>";
        } else if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.OL.name())) {
            generatedHtml = "<ol class='uif-readOnlyStringList'>";
        } else if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.BREAK.name())) {
            setReadOnlyListDelimiter("<br/>");
        } else if (this.getReadOnlyListDelimiter() == null) {
            setReadOnlyListDelimiter(", ");
        }
    }

    //iterate through each value
    for (Object value : list) {
        //if blank skip
        if (!TypeUtils.isSimpleType(value.getClass()) || StringUtils.isBlank(value.toString())) {
            continue;
        }

        //handle mask if any
        if (isApplyMask()) {
            value = getMaskFormatter().maskValue(value);
        }

        //TODO the value should use the formatted text property value we would expect to see instead of toString
        //two types - delimited and html list
        if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.UL.name())
                || getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.OL.name())) {
            generatedHtml = generatedHtml + "<li>" + StringEscapeUtils.escapeHtml(value.toString()) + "</li>";
        } else {
            //no matching needed - delimited is always the fallback and break uses same logic
            generatedHtml = generatedHtml + StringEscapeUtils.escapeHtml(value.toString())
                    + this.getReadOnlyListDelimiter();
        }
    }

    //end the generation
    if (!list.isEmpty()) {
        if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.UL.name())) {
            generatedHtml = generatedHtml + "</ul>";
        } else if (getReadOnlyListDisplayType().equalsIgnoreCase(UifConstants.ReadOnlyListTypes.OL.name())) {
            generatedHtml = generatedHtml + "</ol>";
        } else {
            generatedHtml = StringUtils.removeEnd(generatedHtml, this.getReadOnlyListDelimiter());
        }
    }

    if (StringUtils.isBlank(generatedHtml)) {
        generatedHtml = "&nbsp;";
    }

    return generatedHtml;
}

From source file:org.kuali.rice.krad.uif.service.impl.ExpressionEvaluatorServiceImpl.java

/**
 * @see org.kuali.rice.krad.uif.service.ExpressionEvaluatorService#evaluateExpression(java.lang.Object,
 *      java.util.Map, java.lang.String)
 *///w  ww .  j  a va 2  s. c  o  m
public Object evaluateExpression(Object contextObject, Map<String, Object> evaluationParameters,
        String expressionStr) {
    StandardEvaluationContext context = new StandardEvaluationContext(contextObject);
    context.setVariables(evaluationParameters);
    addCustomFunctions(context);

    // if expression contains placeholders remove before evaluating
    if (StringUtils.startsWith(expressionStr, UifConstants.EL_PLACEHOLDER_PREFIX)
            && StringUtils.endsWith(expressionStr, UifConstants.EL_PLACEHOLDER_SUFFIX)) {
        expressionStr = StringUtils.removeStart(expressionStr, UifConstants.EL_PLACEHOLDER_PREFIX);
        expressionStr = StringUtils.removeEnd(expressionStr, UifConstants.EL_PLACEHOLDER_SUFFIX);
    }

    ExpressionParser parser = new SpelExpressionParser();
    Object result = null;
    try {
        Expression expression = parser.parseExpression(expressionStr);

        result = expression.getValue(context);
    } catch (Exception e) {
        LOG.error("Exception evaluating expression: " + expressionStr);
        throw new RuntimeException("Exception evaluating expression: " + expressionStr, e);
    }

    return result;
}

From source file:org.kuali.rice.krad.uif.service.impl.UifDefaultingServiceImpl.java

protected Control getControlInstance(AttributeDefinition attrDef, DataObjectAttribute dataObjectAttribute) {
    Control c = null;//from  w ww  .java  2 s .c  o  m
    // Check for the hidden hint - if present - then use that control type
    if (dataObjectAttribute != null && hasHintOfType(dataObjectAttribute, UifDisplayHintType.HIDDEN)) {
        c = ComponentFactory.getHiddenControl();
    } else if (attrDef.getOptionsFinder() != null) {
        // if a values finder has been established, use a radio button group or drop-down list
        if (dataObjectAttribute != null && hasHintOfType(dataObjectAttribute, UifDisplayHintType.RADIO)) {
            c = ComponentFactory.getRadioGroupControl();
        } else {
            c = ComponentFactory.getSelectControl();
        }
    } else if (attrDef.getName().endsWith(".principalName") && dataObjectAttribute != null) {
        // FIXME: JHK: Yes, I know this is a *HORRIBLE* hack - but the alternative
        // would look even more "hacky" and error-prone
        c = ComponentFactory.getUserControl();
        // Need to find the relationship information
        // get the relationship ID by removing .principalName from the attribute name
        String relationshipName = StringUtils.removeEnd(attrDef.getName(), ".principalName");
        DataObjectMetadata metadata = dataObjectService.getMetadataRepository()
                .getMetadata(dataObjectAttribute.getOwningType());
        if (metadata != null) {
            DataObjectRelationship relationship = metadata.getRelationship(relationshipName);
            if (relationship != null && CollectionUtils.isNotEmpty(relationship.getAttributeRelationships())) {
                ((UserControl) c).setPrincipalIdPropertyName(
                        relationship.getAttributeRelationships().get(0).getParentAttributeName());
                ((UserControl) c).setPersonNamePropertyName(
                        relationshipName + "." + KimConstants.AttributeConstants.NAME);
                ((UserControl) c).setPersonObjectPropertyName(relationshipName);
            }
        } else {
            LOG.warn("Attempt to pull relationship name: " + relationshipName
                    + " resulted in missing metadata when looking for: " + dataObjectAttribute.getOwningType());
        }
    } else {
        switch (attrDef.getDataType()) {
        case STRING:
            // TODO: Determine better way to store the "200" metric below
            if (attrDef.getMaxLength() != null && attrDef.getMaxLength().intValue() > 200) {
                c = ComponentFactory.getTextAreaControl();
            } else {
                c = ComponentFactory.getTextControl();
            }
            break;
        case BOOLEAN:
            c = ComponentFactory.getCheckboxControl();
            break;
        case DATE:
        case DATETIME:
        case TRUNCATED_DATE:
            c = ComponentFactory.getDateControl();
            break;
        case CURRENCY:
        case DOUBLE:
        case FLOAT:
        case INTEGER:
        case LARGE_INTEGER:
        case LONG:
        case PRECISE_DECIMAL:
            c = ComponentFactory.getTextControl();
            break;
        case MARKUP:
            c = ComponentFactory.getTextAreaControl();
            break;
        default:
            c = ComponentFactory.getTextControl();
            break;
        }
    }
    return c;
}

From source file:org.kuali.rice.krad.uif.util.ClientValidationUtils.java

/**
 * Generates the js object used to override all default messages for validator jquery plugin
 * with custom messages retrieved from the message service
 * //from w  w w . j  a va2s. c  o  m
 * @return script for message override
 */
public static String generateValidatorMessagesOption() {
    MessageService messageService = KRADServiceLocatorWeb.getMessageService();

    String mOption = "";
    String keyValuePairs = "";
    for (ValidationMessageKeys element : EnumSet.allOf(ValidationMessageKeys.class)) {
        String key = element.toString();
        String message = messageService.getMessageText(UifConstants.Messages.VALIDATION_MSG_KEY_PREFIX + key);

        if (StringUtils.isNotEmpty(message)) {
            message = MessageStructureUtils.translateStringMessage(message);
            keyValuePairs = keyValuePairs + "\n" + key + ": '" + message + "',";
        }
    }

    keyValuePairs = StringUtils.removeEnd(keyValuePairs, ",");
    if (StringUtils.isNotEmpty(keyValuePairs)) {
        mOption = "{" + keyValuePairs + "}";
    }

    return mOption;
}