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.kuali.rice.krad.uif.element.Action.java

/**
 * When the action is updating a component sets up the refresh script for the component (found by the
 * given refresh id or refresh property name.
 *
 * @param view view instance the action belongs to
 *///from  ww w.  j a v a 2 s .  co  m
protected void setupRefreshAction(View view) {
    // if refresh property or id is given, make return type update component
    // TODO: what if the refresh id is the page id? we should set the return type as update page
    if (StringUtils.isNotBlank(refreshPropertyName) || StringUtils.isNotBlank(refreshId)) {
        ajaxReturnType = UifConstants.AjaxReturnTypes.UPDATECOMPONENT.getKey();
    }

    // if refresh property name is given, adjust the binding and then attempt to find the
    // component in the view index
    Component refreshComponent = null;
    if (StringUtils.isNotBlank(refreshPropertyName)) {
        // TODO: does this support all binding prefixes?
        if (refreshPropertyName.startsWith(UifConstants.NO_BIND_ADJUST_PREFIX)) {
            refreshPropertyName = StringUtils.removeStart(refreshPropertyName,
                    UifConstants.NO_BIND_ADJUST_PREFIX);
        } else if (StringUtils.isNotBlank(view.getDefaultBindingObjectPath())) {
            refreshPropertyName = view.getDefaultBindingObjectPath() + "." + refreshPropertyName;
        }

        DataField dataField = view.getViewIndex().getDataFieldByPath(refreshPropertyName);
        if (dataField != null) {
            refreshComponent = dataField;
            refreshId = refreshComponent.getId();
        }
    } else if (StringUtils.isNotBlank(refreshId)) {
        Component component = view.getViewIndex().getComponentById(refreshId);
        if (component != null) {
            refreshComponent = component;
        }
    }

    if (refreshComponent != null) {
        refreshComponent.setRefreshedByAction(true);
    }
}

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

/**
 * The following finalization is performed:
 *
 * <ul>//  w w  w.j  a  v a2s. c  om
 * <li>Add methodToCall action parameter if set and setup event code for
 * setting action parameters</li>
 * </ul>
 *
 * @see org.kuali.rice.krad.uif.component.ComponentBase#performFinalize(org.kuali.rice.krad.uif.view.View,
 *      java.lang.Object, org.kuali.rice.krad.uif.component.Component)
 */
@Override
public void performFinalize(View view, Object model, Component parent) {
    Component refreshComponent = null;

    // if refresh property name is given, adjust the binding and then attempt to find the
    // component in the view index
    if (StringUtils.isNotBlank(refreshPropertyName)) {
        // TODO: does this support all binding prefixes?
        if (refreshPropertyName.startsWith(UifConstants.NO_BIND_ADJUST_PREFIX)) {
            refreshPropertyName = StringUtils.removeStart(refreshPropertyName,
                    UifConstants.NO_BIND_ADJUST_PREFIX);
        } else if (StringUtils.isNotBlank(view.getDefaultBindingObjectPath())) {
            refreshPropertyName = view.getDefaultBindingObjectPath() + "." + refreshPropertyName;
        }

        DataField dataField = view.getViewIndex().getDataFieldByPath(refreshPropertyName);
        if (dataField != null) {
            refreshComponent = dataField;
        }
    } else if (StringUtils.isNotBlank(refreshId)) {
        Component component = view.getViewIndex().getComponentById(refreshId);
        if (component != null) {
            refreshComponent = component;
        }
    }

    String actionScript = "";
    if (refreshComponent != null) {
        refreshComponent.setRefreshedByAction(true);
        // update initial state
        Component initialComponent = view.getViewIndex().getInitialComponentStates()
                .get(refreshComponent.getFactoryId());
        if (initialComponent != null) {
            initialComponent.setRefreshedByAction(true);
            view.getViewIndex().getInitialComponentStates().put(refreshComponent.getFactoryId(),
                    initialComponent);
        }

        // refresh component for action
        actionScript = "retrieveComponent('" + refreshComponent.getId() + "','"
                + refreshComponent.getFactoryId() + "','" + getMethodToCall() + "');";
    } else {
        // refresh page
        actionScript = "submitForm();";
    }

    // add action script to client JS
    if (StringUtils.isNotBlank(getClientSideJs())) {
        actionScript = getClientSideJs() + actionScript;
    }
    setClientSideJs(actionScript);

    super.performFinalize(view, model, parent);
}

From source file:org.kuali.rice.krad.uif.layout.CollectionLayoutUtils.java

public static void prepareSelectFieldForLine(Field selectField, CollectionGroup collectionGroup,
        String lineBindingPath, Object line) {
    // if select property name set use as property name for select field
    String selectPropertyName = collectionGroup.getLineSelectPropertyName();
    if (StringUtils.isNotBlank(selectPropertyName)) {
        // if select property contains form prefix, will bind to form and not each line
        if (selectPropertyName.startsWith(UifConstants.NO_BIND_ADJUST_PREFIX)) {
            selectPropertyName = StringUtils.removeStart(selectPropertyName,
                    UifConstants.NO_BIND_ADJUST_PREFIX);
            ((DataBinding) selectField).getBindingInfo().setBindingName(selectPropertyName);
            ((DataBinding) selectField).getBindingInfo().setBindToForm(true);
        } else {//from w ww .j a  v a 2  s.  c o m
            ((DataBinding) selectField).getBindingInfo().setBindingName(selectPropertyName);
            ((DataBinding) selectField).getBindingInfo().setBindByNamePrefix(lineBindingPath);
        }
    } else {
        // select property name not given, use UifFormBase#selectedCollectionLines
        String collectionLineKey = KRADUtils
                .translateToMapSafeKey(collectionGroup.getBindingInfo().getBindingPath());
        String selectBindingPath = UifPropertyPaths.SELECTED_COLLECTION_LINES + "['" + collectionLineKey + "']";

        ((DataBinding) selectField).getBindingInfo().setBindingName(selectBindingPath);
        ((DataBinding) selectField).getBindingInfo().setBindToForm(true);
    }

    setControlValueToLineIdentifier(selectField, line);
}

From source file:org.kuali.rice.krad.uif.layout.TableLayoutManager.java

/**
 * Assembles the field instances for the collection line. The given sequence
 * field prototype is copied for the line sequence field. Likewise a copy of
 * the actionFieldPrototype is made and the given actions are set as the
 * items for the action field. Finally the generated items are assembled
 * together into the allRowFields list with the given lineFields.
 *
 * @see org.kuali.rice.krad.uif.layout.CollectionLayoutManager#buildLine(org.kuali.rice.krad.uif.view.View,
 *      java.lang.Object, org.kuali.rice.krad.uif.container.CollectionGroup,
 *      java.util.List, java.util.List, java.lang.String, java.util.List,
 *      java.lang.String, java.lang.Object, int)
 *//*w  w  w . jav a  2s . c o  m*/
public void buildLine(View view, Object model, CollectionGroup collectionGroup, List<Field> lineFields,
        List<FieldGroup> subCollectionFields, String bindingPath, List<Action> actions, String idSuffix,
        Object currentLine, int lineIndex) {

    // since expressions are not evaluated on child components yet, we need to evaluate any properties
    // we are going to read for building the table
    ExpressionEvaluator expressionEvaluator = view.getViewHelperService().getExpressionEvaluator();
    for (Field lineField : lineFields) {
        lineField.pushObjectToContext(UifConstants.ContextVariableNames.PARENT, collectionGroup);
        lineField.pushAllToContext(view.getViewHelperService().getCommonContext(view, lineField));

        expressionEvaluator.evaluatePropertyExpression(view, lineField.getContext(), lineField,
                UifPropertyPaths.ROW_SPAN, true);
        expressionEvaluator.evaluatePropertyExpression(view, lineField.getContext(), lineField,
                UifPropertyPaths.COL_SPAN, true);
        expressionEvaluator.evaluatePropertyExpression(view, lineField.getContext(), lineField,
                UifPropertyPaths.REQUIRED, true);
        expressionEvaluator.evaluatePropertyExpression(view, lineField.getContext(), lineField,
                UifPropertyPaths.READ_ONLY, true);
    }

    // if first line for table set number of data columns
    if (allRowFields.isEmpty()) {
        if (isSuppressLineWrapping()) {
            setNumberOfDataColumns(lineFields.size());
        } else {
            setNumberOfDataColumns(getNumberOfColumns());
        }
    }

    boolean isAddLine = false;

    // If first row or row wrap is happening
    if (lineIndex == -1 || (lineFields.size() != numberOfDataColumns
            && ((lineIndex + 1) * numberOfDataColumns) < lineFields.size())) {
        isAddLine = true;
    }

    // capture the first row of fields for widgets that build off the table
    if (lineIndex == 0 || this.firstRowFields.isEmpty()) {
        this.firstRowFields = lineFields;
    }

    boolean renderActions = collectionGroup.isRenderLineActions() && !collectionGroup.isReadOnly();
    int extraColumns = 0;
    String rowCss = "";
    boolean addLineInTable = collectionGroup.isRenderAddLine() && !collectionGroup.isReadOnly()
            && !isSeparateAddLine();

    if (collectionGroup.isHighlightNewItems() && ((UifFormBase) model).isAddedCollectionItem(currentLine)) {
        rowCss = collectionGroup.getNewItemsCssClass();
    } else if (isAddLine && addLineInTable) {
        rowCss = collectionGroup.getAddItemCssClass();
        this.addStyleClass(CssConstants.Classes.HAS_ADD_LINE);
    }

    // do not allow null rowCss
    if (rowCss == null) {
        rowCss = "";
    }

    // conditionalRowCssClass generation logic, if applicable
    if (conditionalRowCssClasses != null && !conditionalRowCssClasses.isEmpty()) {
        int oddRemainder = 1;
        if (!addLineInTable) {
            oddRemainder = 0;
        }

        boolean isOdd = lineIndex % 2 == oddRemainder || lineIndex == -1;
        Map<String, Object> lineContext = new HashMap<String, Object>();

        lineContext.putAll(this.getContext());
        lineContext.put(UifConstants.ContextVariableNames.LINE, currentLine);
        lineContext.put(UifConstants.ContextVariableNames.MANAGER, this);
        lineContext.put(UifConstants.ContextVariableNames.VIEW, view);
        lineContext.put(UifConstants.ContextVariableNames.LINE_SUFFIX, idSuffix);
        lineContext.put(UifConstants.ContextVariableNames.INDEX, Integer.valueOf(lineIndex));
        lineContext.put(UifConstants.ContextVariableNames.COLLECTION_GROUP, collectionGroup);
        lineContext.put(UifConstants.ContextVariableNames.IS_ADD_LINE, isAddLine && !isSeparateAddLine());
        lineContext.put(UifConstants.ContextVariableNames.READONLY_LINE, collectionGroup.isReadOnly());

        // get row css based on conditionalRowCssClasses map
        rowCss = rowCss + " " + KRADUtils.generateRowCssClassString(conditionalRowCssClasses, lineIndex, isOdd,
                lineContext, expressionEvaluator);
    }

    rowCss = StringUtils.removeStart(rowCss, " ");
    this.getRowCssClasses().add(rowCss);

    // if separate add line prepare the add line group
    if (isAddLine && separateAddLine) {
        if (StringUtils.isBlank(addLineGroup.getTitle())
                && StringUtils.isBlank(addLineGroup.getHeader().getHeaderText())) {
            addLineGroup.getHeader().setHeaderText(collectionGroup.getAddLabel());
        }
        addLineGroup.setItems(lineFields);

        List<Component> footerItems = new ArrayList<Component>(actions);
        footerItems.addAll(addLineGroup.getFooter().getItems());
        addLineGroup.getFooter().setItems(footerItems);

        if (collectionGroup.isAddViaLightBox()) {
            String actionScript = "showLightboxComponent('" + addLineGroup.getId() + "');";
            if (StringUtils.isNotBlank(collectionGroup.getAddViaLightBoxAction().getActionScript())) {
                actionScript = collectionGroup.getAddViaLightBoxAction().getActionScript() + actionScript;
            }
            collectionGroup.getAddViaLightBoxAction().setActionScript(actionScript);
            addLineGroup.setStyle("display: none");
        }

        return;
    }

    // TODO: implement repeat header
    if (!headerAdded) {
        headerLabels = new ArrayList<Label>();
        allRowFields = new ArrayList<Field>();

        buildTableHeaderRows(collectionGroup, lineFields);
        ComponentUtils.pushObjectToContext(headerLabels, UifConstants.ContextVariableNames.LINE, currentLine);
        ComponentUtils.pushObjectToContext(headerLabels, UifConstants.ContextVariableNames.INDEX,
                new Integer(lineIndex));
        headerAdded = true;
    }

    // set label field rendered to true on line fields and adjust cell properties
    for (Field field : lineFields) {
        field.setLabelRendered(true);
        field.setFieldLabel(null);

        setCellAttributes(field);
    }

    int rowCount = calculateNumberOfRows(lineFields);
    int rowSpan = rowCount + subCollectionFields.size();

    if (actionColumnIndex == 1 && renderActions) {
        addActionColumn(idSuffix, currentLine, lineIndex, rowSpan, actions);
    }

    // sequence field is always first and should span all rows for the line
    if (renderSequenceField) {
        Field sequenceField = null;
        if (!isAddLine) {
            sequenceField = ComponentUtils.copy(getSequenceFieldPrototype(), idSuffix);

            //Ignore in validation processing
            sequenceField.addDataAttribute(UifConstants.DataAttributes.VIGNORE, "yes");

            if (generateAutoSequence && (sequenceField instanceof MessageField)) {
                ((MessageField) sequenceField).setMessageText(Integer.toString(lineIndex + 1));
            }
        } else {
            sequenceField = ComponentFactory.getMessageField();
            view.assignComponentIds(sequenceField);

            Message sequenceMessage = ComponentUtils.copy(collectionGroup.getAddLineLabel(), idSuffix);
            ((MessageField) sequenceField).setMessage(sequenceMessage);

            // adjusting add line label to match sequence prototype cells attributes
            sequenceField.setCellWidth(getSequenceFieldPrototype().getCellWidth());
            sequenceField.setCellStyle(getSequenceFieldPrototype().getCellStyle());
        }

        sequenceField.setRowSpan(rowSpan);

        if (sequenceField instanceof DataBinding) {
            ((DataBinding) sequenceField).getBindingInfo().setBindByNamePrefix(bindingPath);
        }

        setCellAttributes(sequenceField);

        ComponentUtils.updateContextForLine(sequenceField, currentLine, lineIndex, idSuffix);
        allRowFields.add(sequenceField);
        extraColumns++;

        if (actionColumnIndex == 2 && renderActions) {
            addActionColumn(idSuffix, currentLine, lineIndex, rowSpan, actions);
        }
    }

    // select field will come after sequence field (if enabled) or be first column
    if (collectionGroup.isIncludeLineSelectionField()) {
        Field selectField = ComponentUtils.copy(getSelectFieldPrototype(), idSuffix);
        CollectionLayoutUtils.prepareSelectFieldForLine(selectField, collectionGroup, bindingPath, currentLine);

        ComponentUtils.updateContextForLine(selectField, currentLine, lineIndex, idSuffix);
        setCellAttributes(selectField);

        allRowFields.add(selectField);

        extraColumns++;

        if (renderActions) {
            if ((actionColumnIndex == 3 && renderSequenceField)
                    || (actionColumnIndex == 2 && !renderSequenceField)) {
                addActionColumn(idSuffix, currentLine, lineIndex, rowSpan, actions);
            }
        }
    }

    // now add the fields in the correct position
    int cellPosition = 0;
    int columnNumber = 0;

    boolean renderActionsLast = actionColumnIndex == -1 || actionColumnIndex > lineFields.size() + extraColumns;
    boolean hasGrouping = (groupingPropertyNames != null || StringUtils.isNotBlank(this.getGroupingTitle()));
    boolean insertActionField = false;

    for (Field lineField : lineFields) {
        //Check to see if ActionField needs to be inserted before this lineField because of wrapping.
        // Since actionField has a colSpan of 1 add that to the previous cellPosition instead of the
        // current lineField's colSpan.
        // Only insert if ActionField has to be placed at the end. Else the specification of actionColumnIndex should
        // take care of putting it in the right location
        insertActionField = (cellPosition != 0 && lineFields.size() != numberOfDataColumns) && renderActions
                && renderActionsLast && ((cellPosition % numberOfDataColumns) == 0);

        cellPosition += lineField.getColSpan();
        columnNumber++;

        //special handling for grouping field - this field MUST be first
        if (hasGrouping && lineField instanceof MessageField
                && lineField.getDataAttributes().get(UifConstants.DataAttributes.ROLE) != null
                && lineField.getDataAttributes().get(UifConstants.DataAttributes.ROLE)
                        .equals(UifConstants.RoleTypes.ROW_GROUPING)) {
            int groupFieldIndex = allRowFields.size() - extraColumns;
            allRowFields.add(groupFieldIndex, lineField);
            groupingColumnIndex = 0;
            if (isAddLine) {
                ((MessageField) lineField).getMessage().getPropertyExpressions()
                        .remove(UifPropertyPaths.MESSAGE_TEXT);
                ((MessageField) lineField).getMessage().setMessageText("addLine");
            }
        } else {
            // If the row wraps before the last element
            if (insertActionField) {
                addActionColumn(idSuffix, currentLine, lineIndex, rowSpan, actions);
            }

            allRowFields.add(lineField);
        }

        // action field
        if (!renderActionsLast && cellPosition == (actionColumnIndex - extraColumns - 1)) {
            addActionColumn(idSuffix, currentLine, lineIndex, rowSpan, actions);
        }

        //details action
        if (lineField instanceof FieldGroup && ((FieldGroup) lineField).getItems() != null) {
            for (Component component : ((FieldGroup) lineField).getItems()) {
                if (component != null && component instanceof Action
                        && component.getDataAttributes().get("role") != null
                        && component.getDataAttributes().get("role").equals("detailsLink")
                        && StringUtils.isBlank(((Action) component).getActionScript())) {
                    ((Action) component)
                            .setActionScript("rowDetailsActionHandler(this,'" + this.getId() + "');");
                }
            }
        }

        //special column calculation handling to identify what type of handler will be attached
        //and add special styling
        if (lineField instanceof InputField && columnCalculations != null) {
            for (ColumnCalculationInfo cInfo : columnCalculations) {
                if (cInfo.getPropertyName().equals(((InputField) lineField).getPropertyName())) {
                    if (cInfo.isCalculateOnKeyUp()) {
                        lineField.addDataAttribute(UifConstants.DataAttributes.TOTAL, "keyup");
                    } else {
                        lineField.addDataAttribute(UifConstants.DataAttributes.TOTAL, "change");
                    }
                    lineField.addStyleClass("uif-calculationField");
                }
            }
        }
    }

    if (lineFields.size() == numberOfDataColumns && renderActions && renderActionsLast) {
        addActionColumn(idSuffix, currentLine, lineIndex, rowSpan, actions);
    }

    // update colspan on sub-collection fields
    for (FieldGroup subCollectionField : subCollectionFields) {
        subCollectionField.setColSpan(numberOfDataColumns);
    }

    // add sub-collection fields to end of data fields
    allRowFields.addAll(subCollectionFields);
}

From source file:org.kuali.rice.krad.uif.layout.TableLayoutManagerBase.java

/**
 * Assembles the field instances for the collection line.
 *
 * <p>The given sequence field prototype is copied for the line sequence field. Likewise a copy of
 * the actionFieldPrototype is made and the given actions are set as the items for the action field.
 * Finally the generated items are assembled together into the allRowFields list with the given
 * lineFields.</p>//from   w  w w.ja v a2  s. c  o  m
 *
 * {@inheritDoc}
 */
@Override
public void buildLine(LineBuilderContext lineBuilderContext) {
    View view = ViewLifecycle.getView();

    List<Field> lineFields = lineBuilderContext.getLineFields();
    CollectionGroup collectionGroup = lineBuilderContext.getCollectionGroup();
    int lineIndex = lineBuilderContext.getLineIndex();
    String idSuffix = lineBuilderContext.getIdSuffix();
    Object currentLine = lineBuilderContext.getCurrentLine();
    List<? extends Component> actions = lineBuilderContext.getLineActions();
    String bindingPath = lineBuilderContext.getBindingPath();

    // since expressions are not evaluated on child components yet, we need to evaluate any properties
    // we are going to read for building the table
    ExpressionEvaluator expressionEvaluator = ViewLifecycle.getExpressionEvaluator();
    for (Field lineField : lineFields) {
        lineField.pushObjectToContext(UifConstants.ContextVariableNames.PARENT, collectionGroup);
        lineField.pushAllToContext(view.getContext());
        lineField.pushObjectToContext(UifConstants.ContextVariableNames.THEME_IMAGES,
                view.getTheme().getImageDirectory());
        lineField.pushObjectToContext(UifConstants.ContextVariableNames.COMPONENT, lineField);

        expressionEvaluator.evaluatePropertyExpression(view, lineField.getContext(), lineField,
                UifPropertyPaths.ROW_SPAN, true);
        expressionEvaluator.evaluatePropertyExpression(view, lineField.getContext(), lineField,
                UifPropertyPaths.COL_SPAN, true);
        expressionEvaluator.evaluatePropertyExpression(view, lineField.getContext(), lineField,
                UifPropertyPaths.REQUIRED, true);
        expressionEvaluator.evaluatePropertyExpression(view, lineField.getContext(), lineField,
                UifPropertyPaths.READ_ONLY, true);
    }

    // if first line for table set number of data columns
    if (allRowFields.isEmpty()) {
        if (isSuppressLineWrapping()) {
            setNumberOfDataColumns(lineFields.size());
        } else {
            setNumberOfDataColumns(getNumberOfColumns());
        }
    }

    boolean isAddLine = false;

    // If first row or row wrap is happening
    if (lineIndex == -1 || (lineFields.size() != numberOfDataColumns
            && ((lineIndex + 1) * numberOfDataColumns) < lineFields.size())) {
        isAddLine = true;
    }

    // capture the first row of fields for widgets that build off the table
    if (lineIndex == 0 || this.firstRowFields.isEmpty()) {
        this.firstRowFields = lineFields;
    }

    boolean renderActions = collectionGroup.isRenderLineActions()
            && !Boolean.TRUE.equals(collectionGroup.getReadOnly());
    int extraColumns = 0;
    String rowCss = "";
    boolean addLineInTable = collectionGroup.isRenderAddLine()
            && !Boolean.TRUE.equals(collectionGroup.getReadOnly()) && !isSeparateAddLine();

    if (collectionGroup.isHighlightNewItems()
            && ((UifFormBase) lineBuilderContext.getModel()).isAddedCollectionItem(currentLine)) {
        rowCss = collectionGroup.getNewItemsCssClass();
    } else if (isAddLine && addLineInTable) {
        rowCss = collectionGroup.getAddItemCssClass();
        this.addStyleClass(CssConstants.Classes.HAS_ADD_LINE);
    }

    // do not allow null rowCss
    if (rowCss == null) {
        rowCss = "";
    }

    Map<String, Object> lineContext = new HashMap<String, Object>();
    lineContext.putAll(this.getContext());
    lineContext.put(UifConstants.ContextVariableNames.LINE, currentLine);
    lineContext.put(UifConstants.ContextVariableNames.MANAGER, this);
    lineContext.put(UifConstants.ContextVariableNames.VIEW, view);
    lineContext.put(UifConstants.ContextVariableNames.LINE_SUFFIX, idSuffix);
    lineContext.put(UifConstants.ContextVariableNames.INDEX, Integer.valueOf(lineIndex));
    lineContext.put(UifConstants.ContextVariableNames.COLLECTION_GROUP, collectionGroup);
    lineContext.put(UifConstants.ContextVariableNames.IS_ADD_LINE, isAddLine && !isSeparateAddLine());
    lineContext.put(UifConstants.ContextVariableNames.READONLY_LINE,
            Boolean.TRUE.equals(collectionGroup.getReadOnly()));

    // conditionalRowCssClass generation logic, if applicable
    if (conditionalRowCssClasses != null && !conditionalRowCssClasses.isEmpty()) {
        int oddRemainder = 1;
        if (!addLineInTable) {
            oddRemainder = 0;
        }

        boolean isOdd = lineIndex % 2 == oddRemainder || lineIndex == -1;

        // get row css based on conditionalRowCssClasses map
        rowCss = rowCss + " " + KRADUtils.generateRowCssClassString(conditionalRowCssClasses, lineIndex, isOdd,
                lineContext, expressionEvaluator);
    }

    // create row data attributes
    String rowDataAttributes = "";

    // add line
    if (isAddLine) {
        if (StringUtils.isNotBlank(collectionGroup.getAddLineEnterKeyAction())) {
            String addLineEnterKeyAction = collectionGroup.getAddLineEnterKeyAction();
            if (addLineEnterKeyAction.indexOf("@{") != -1) {
                addLineEnterKeyAction = expressionEvaluator.evaluateExpressionTemplate(lineContext,
                        collectionGroup.getAddLineEnterKeyAction());
            }
            rowDataAttributes = "data-" + UifConstants.DataAttributes.ENTER_KEY + "=\""
                    + KRADUtils.convertToHTMLAttributeSafeString(addLineEnterKeyAction) + "\"";
        }
    }
    // non add line
    else {
        if (StringUtils.isNotBlank(collectionGroup.getLineEnterKeyAction())) {
            String lineEnterKeyAction = collectionGroup.getLineEnterKeyAction();
            if (lineEnterKeyAction.indexOf("@{") != -1) {
                lineEnterKeyAction = expressionEvaluator.evaluateExpressionTemplate(lineContext,
                        collectionGroup.getLineEnterKeyAction());
            }
            rowDataAttributes = "data-" + UifConstants.DataAttributes.ENTER_KEY + "=\""
                    + KRADUtils.convertToHTMLAttributeSafeString(lineEnterKeyAction) + "\"";
        }
    }

    this.getRowDataAttributes().add(rowDataAttributes);

    // if separate add line prepare the add line group
    if (isAddLine && separateAddLine) {
        // add line enter key action
        addEnterKeyDataAttributeToGroup(getAddLineGroup(), lineContext, expressionEvaluator,
                collectionGroup.getAddLineEnterKeyAction());

        if (getAddLineGroup().getHeader() != null && StringUtils.isBlank(getAddLineGroup().getTitle())
                && StringUtils.isBlank(getAddLineGroup().getHeader().getHeaderText())) {
            getAddLineGroup().getHeader().setHeaderText(collectionGroup.getAddLabel());
        }

        getAddLineGroup().setItems(lineFields);

        if ((getAddLineGroup().getFooter() != null) && ((getAddLineGroup().getFooter().getItems() == null)
                || getAddLineGroup().getFooter().getItems().isEmpty())) {
            getAddLineGroup().getFooter().setItems(new ArrayList<Component>(actions));
        }

        // Note that a RowCssClass was not added to the LayoutManager for the collection for the separateAddLine
        return;
    }

    rowCss = StringUtils.removeStart(rowCss, " ");
    this.getRowCssClasses().add(rowCss);

    // TODO: implement repeat header
    if (!headerAdded) {
        headerLabels = new ArrayList<Label>();
        allRowFields = new ArrayList<Field>();

        buildTableHeaderRows(collectionGroup, lineFields);
        ContextUtils.pushObjectToContextDeep(headerLabels, UifConstants.ContextVariableNames.LINE, currentLine);
        ContextUtils.pushObjectToContextDeep(headerLabels, UifConstants.ContextVariableNames.INDEX,
                new Integer(lineIndex));
        headerAdded = true;
    }

    // set label field rendered to true on line fields and adjust cell properties
    for (Field field : lineFields) {
        field.setLabelRendered(true);
        field.setFieldLabel(null);

        setCellAttributes(field);
    }

    int rowCount = calculateNumberOfRows(lineFields);
    int rowSpan = rowCount;

    List<FieldGroup> subCollectionFields = lineBuilderContext.getSubCollectionFields();
    if (subCollectionFields != null) {
        rowSpan += subCollectionFields.size();
    }

    if (actionColumnIndex == 1 && renderActions) {
        addActionColumn(collectionGroup, idSuffix, currentLine, lineIndex, rowSpan, actions);
    }

    // sequence field is always first and should span all rows for the line
    if (renderSequenceField) {
        Field sequenceField = null;
        if (!isAddLine) {
            sequenceField = ComponentUtils.copy(getSequenceFieldPrototype(), idSuffix);

            //Ignore in validation processing
            sequenceField.addDataAttribute(UifConstants.DataAttributes.VIGNORE, "yes");

            if (generateAutoSequence && (sequenceField instanceof MessageField)) {
                ((MessageField) sequenceField).setMessageText(Integer.toString(lineIndex + 1));
            }
        } else {
            sequenceField = ComponentFactory.getMessageField();

            Message sequenceMessage = ComponentUtils.copy(collectionGroup.getAddLineLabel(), idSuffix);
            ((MessageField) sequenceField).setMessage(sequenceMessage);

            // adjusting add line label to match sequence prototype cells attributes
            sequenceField.setCellWidth(getSequenceFieldPrototype().getCellWidth());
            sequenceField.setWrapperStyle(getSequenceFieldPrototype().getWrapperStyle());
        }

        sequenceField.setRowSpan(rowSpan);

        if (sequenceField instanceof DataBinding) {
            ((DataBinding) sequenceField).getBindingInfo().setBindByNamePrefix(bindingPath);
        }

        setCellAttributes(sequenceField);

        ContextUtils.updateContextForLine(sequenceField, collectionGroup, currentLine, lineIndex, idSuffix);
        allRowFields.add(sequenceField);

        extraColumns++;

        if (actionColumnIndex == 2 && renderActions) {
            addActionColumn(collectionGroup, idSuffix, currentLine, lineIndex, rowSpan, actions);
        }
    }

    // select field will come after sequence field (if enabled) or be first column
    if (collectionGroup.isIncludeLineSelectionField()) {
        Field selectField = ComponentUtils.copy(getSelectFieldPrototype(), idSuffix);
        CollectionLayoutUtils.prepareSelectFieldForLine(selectField, collectionGroup, bindingPath, currentLine);

        ContextUtils.updateContextForLine(selectField, collectionGroup, currentLine, lineIndex, idSuffix);
        setCellAttributes(selectField);

        allRowFields.add(selectField);

        extraColumns++;

        if (renderActions) {
            if ((actionColumnIndex == 3 && renderSequenceField)
                    || (actionColumnIndex == 2 && !renderSequenceField)) {
                addActionColumn(collectionGroup, idSuffix, currentLine, lineIndex, rowSpan, actions);
            }
        }
    }

    // now add the fields in the correct position
    int cellPosition = 0;

    boolean renderActionsLast = actionColumnIndex == -1 || actionColumnIndex > lineFields.size() + extraColumns;
    boolean hasGrouping = (groupingPropertyNames != null || StringUtils.isNotBlank(this.getGroupingTitle()));
    boolean insertActionField = false;

    for (Field lineField : lineFields) {
        //Check to see if ActionField needs to be inserted before this lineField because of wrapping.
        // Since actionField has a colSpan of 1 add that to the previous cellPosition instead of the
        // current lineField's colSpan.
        // Only insert if ActionField has to be placed at the end. Else the specification of actionColumnIndex should
        // take care of putting it in the right location
        insertActionField = (cellPosition != 0 && lineFields.size() != numberOfDataColumns) && renderActions
                && renderActionsLast && ((cellPosition % numberOfDataColumns) == 0);

        cellPosition += lineField.getColSpan();

        //special handling for grouping field - this field MUST be first
        Map<String, String> lineFieldDataAttributes = lineField.getDataAttributes();
        if (hasGrouping && (lineField instanceof MessageField) && lineFieldDataAttributes != null
                && UifConstants.RoleTypes.ROW_GROUPING
                        .equals(lineFieldDataAttributes.get(UifConstants.DataAttributes.ROLE))) {
            int groupFieldIndex = allRowFields.size() - extraColumns;
            allRowFields.add(groupFieldIndex, lineField);
            groupingColumnIndex = 0;
            if (isAddLine) {
                ((MessageField) lineField).getMessage().getPropertyExpressions()
                        .remove(UifPropertyPaths.MESSAGE_TEXT);
                ((MessageField) lineField).getMessage().setMessageText("addLine");
            }
        } else {
            // If the row wraps before the last element
            if (insertActionField) {
                addActionColumn(collectionGroup, idSuffix, currentLine, lineIndex, rowSpan, actions);
            }

            allRowFields.add(lineField);
        }

        // action field
        if (!renderActionsLast && cellPosition == (actionColumnIndex - extraColumns - 1)) {
            addActionColumn(collectionGroup, idSuffix, currentLine, lineIndex, rowSpan, actions);
        }

        //details action
        if (lineField instanceof FieldGroup && ((FieldGroup) lineField).getItems() != null) {
            for (Component component : ((FieldGroup) lineField).getItems()) {
                if (component != null && component instanceof Action && (component.getDataAttributes() != null)
                        && component.getDataAttributes().get("role") != null
                        && component.getDataAttributes().get("role").equals("detailsLink")
                        && StringUtils.isBlank(((Action) component).getActionScript())) {
                    ((Action) component)
                            .setActionScript("rowDetailsActionHandler(this,'" + this.getId() + "');");
                }
            }
        }

        //special column calculation handling to identify what type of handler will be attached
        //and add special styling
        if (lineField instanceof InputField && columnCalculations != null) {
            for (ColumnCalculationInfo cInfo : columnCalculations) {
                if (cInfo.getPropertyName().equals(((InputField) lineField).getPropertyName())) {
                    if (cInfo.isCalculateOnKeyUp()) {
                        lineField.addDataAttribute(UifConstants.DataAttributes.TOTAL, "keyup");
                    } else {
                        lineField.addDataAttribute(UifConstants.DataAttributes.TOTAL, "change");
                    }
                    lineField.addStyleClass("uif-calculationField");
                }
            }
        }
    }

    if (lineFields.size() == numberOfDataColumns && renderActions && renderActionsLast) {
        addActionColumn(collectionGroup, idSuffix, currentLine, lineIndex, rowSpan, actions);
    }

    // update colspan on sub-collection fields
    if (subCollectionFields != null) {
        for (FieldGroup subCollectionField : subCollectionFields) {
            subCollectionField.setColSpan(numberOfDataColumns);
        }

        // add sub-collection fields to end of data fields
        allRowFields.addAll(subCollectionFields);
    }
}

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)
 *//*  ww  w .  j a  v a 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.util.ExpressionUtils.java

/**
 * Takes in an expression and a list to be filled in with names(property names)
 * of controls found in the expression. This method returns a js expression which can
 * be executed on the client to determine if the original exp was satisfied before
 * interacting with the server - ie, this js expression is equivalent to the one passed in.
 *
 * There are limitations on the Spring expression language that can be used as this method.
 * It is only used to parse expressions which are valid case statements for determining if
 * some action/processing should be performed.  ONLY Properties, comparison operators, booleans,
 * strings, matches expression, and boolean logic are supported.  Properties must
 * be a valid property on the form, and should have a visible control within the view.
 *
 * Example valid exp: account.name == 'Account Name'
 *
 * @param exp//from www  . ja  va 2 s .co  m
 * @param controlNames
 * @return parsed expression, expressed as JS for client side evaluation
 */
public static String parseExpression(String exp, List<String> controlNames) {
    // clean up expression to ease parsing
    exp = exp.trim();
    if (exp.startsWith("@{")) {
        exp = StringUtils.removeStart(exp, "@{");
        if (exp.endsWith("}")) {
            exp = StringUtils.removeEnd(exp, "}");
        }
    }

    exp = StringUtils.replace(exp, "!=", " != ");
    exp = StringUtils.replace(exp, "==", " == ");
    exp = StringUtils.replace(exp, ">", " > ");
    exp = StringUtils.replace(exp, "<", " < ");
    exp = StringUtils.replace(exp, "<=", " <= ");
    exp = StringUtils.replace(exp, ">=", " >= ");

    String conditionJs = exp;
    String stack = "";

    boolean expectingSingleQuote = false;
    boolean ignoreNext = false;
    for (int i = 0; i < exp.length(); i++) {
        char c = exp.charAt(i);
        if (!expectingSingleQuote && !ignoreNext && (c == '(' || c == ' ' || c == ')')) {
            evaluateCurrentStack(stack.trim(), controlNames);
            //reset stack
            stack = "";
            continue;
        } else if (!ignoreNext && c == '\'') {
            stack = stack + c;
            expectingSingleQuote = !expectingSingleQuote;
        } else if (c == '\\') {
            stack = stack + c;
            ignoreNext = !ignoreNext;
        } else {
            stack = stack + c;
            ignoreNext = false;
        }
    }

    if (StringUtils.isNotEmpty(stack)) {
        evaluateCurrentStack(stack.trim(), controlNames);
    }

    conditionJs = conditionJs.replaceAll("\\s(?i:ne)\\s", " != ").replaceAll("\\s(?i:eq)\\s", " == ")
            .replaceAll("\\s(?i:gt)\\s", " > ").replaceAll("\\s(?i:lt)\\s", " < ")
            .replaceAll("\\s(?i:lte)\\s", " <= ").replaceAll("\\s(?i:gte)\\s", " >= ")
            .replaceAll("\\s(?i:and)\\s", " && ").replaceAll("\\s(?i:or)\\s", " || ")
            .replaceAll("\\s(?i:not)\\s", " != ").replaceAll("\\s(?i:null)\\s?", " '' ")
            .replaceAll("\\s?(?i:#empty)\\((.*?)\\)", "isValueEmpty($1)")
            .replaceAll("\\s?(?i:#listContains)\\((.*?)\\)", "listContains($1)")
            .replaceAll("\\s?(?i:#emptyList)\\((.*?)\\)", "emptyList($1)");

    if (conditionJs.contains("matches")) {
        conditionJs = conditionJs.replaceAll("\\s+(?i:matches)\\s+'.*'", ".match(/" + "$0" + "/) != null ");
        conditionJs = conditionJs.replaceAll("\\(/\\s+(?i:matches)\\s+'", "(/");
        conditionJs = conditionJs.replaceAll("'\\s*/\\)", "/)");
    }

    List<String> removeControlNames = new ArrayList<String>();
    List<String> addControlNames = new ArrayList<String>();
    //convert property names to use coerceValue function and convert arrays to js arrays
    for (String propertyName : controlNames) {
        //array definitions are caught in controlNames because of the nature of the parse - convert them and remove
        if (propertyName.trim().startsWith("{") && propertyName.trim().endsWith("}")) {
            String array = propertyName.trim().replace('{', '[');
            array = array.replace('}', ']');
            conditionJs = conditionJs.replace(propertyName, array);
            removeControlNames.add(propertyName);
            continue;
        }

        //handle not
        if (propertyName.startsWith("!")) {
            String actualPropertyName = StringUtils.removeStart(propertyName, "!");
            conditionJs = conditionJs.replace(propertyName, "!coerceValue(\"" + actualPropertyName + "\")");
            removeControlNames.add(propertyName);
            addControlNames.add(actualPropertyName);
        } else {
            conditionJs = conditionJs.replace(propertyName, "coerceValue(\"" + propertyName + "\")");
        }
    }

    controlNames.removeAll(removeControlNames);
    controlNames.addAll(addControlNames);

    return conditionJs;
}

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

public static String retrieveLookupParameterValue(UifFormBase form, HttpServletRequest request,
        Class<?> lookupObjectClass, String propertyName, String propertyValueName) {
    String parameterValue = "";

    // get literal parameter values first
    if (StringUtils.startsWith(propertyValueName, "'") && StringUtils.endsWith(propertyValueName, "'")) {
        parameterValue = StringUtils.removeStart(propertyValueName, "'");
        parameterValue = StringUtils.removeEnd(propertyValueName, "'");
    } else if (parameterValue.startsWith(
            KRADConstants.LOOKUP_PARAMETER_LITERAL_PREFIX + KRADConstants.LOOKUP_PARAMETER_LITERAL_DELIMITER)) {
        parameterValue = StringUtils.removeStart(parameterValue, KRADConstants.LOOKUP_PARAMETER_LITERAL_PREFIX
                + KRADConstants.LOOKUP_PARAMETER_LITERAL_DELIMITER);
    }/*from  www . ja va  2  s. c  o  m*/
    // check if parameter is in request
    else if (request.getParameterMap().containsKey(propertyValueName)) {
        parameterValue = request.getParameter(propertyValueName);
    }
    // get parameter value from form object
    else {
        Object value = ObjectPropertyUtils.getPropertyValue(form, propertyValueName);
        if (value != null) {
            if (value instanceof String) {
                parameterValue = (String) value;
            }

            Formatter formatter = Formatter.getFormatter(value.getClass());
            parameterValue = (String) formatter.format(value);
        }
    }

    if (parameterValue != null && lookupObjectClass != null
            && KRADServiceLocatorWeb.getDataObjectAuthorizationService()
                    .attributeValueNeedsToBeEncryptedOnFormsAndLinks(lookupObjectClass, propertyName)) {
        try {
            if (CoreApiServiceLocator.getEncryptionService().isEnabled()) {
                parameterValue = CoreApiServiceLocator.getEncryptionService().encrypt(parameterValue)
                        + EncryptionService.ENCRYPTION_POST_PREFIX;
            }
        } catch (GeneralSecurityException e) {
            LOG.error("Unable to encrypt value for property name: " + propertyName);
            throw new RuntimeException(e);
        }
    }

    return parameterValue;
}

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

/**
 * Process the additional properties beyond index 0 of the tag (that was split into parts).
 *
 * <p>This will evaluate and set each of properties on the component passed in.  This only allows
 * setting of properties that can easily be converted to/from/are String type by Spring.</p>
 *
 * @param component component to have its properties set
 * @param tagParts the tag split into parts, index 0 is ignored
 * @return component with its properties set found in the tag's parts
 *///from   w  w  w.  j  av  a2s  . c  o  m
private static Component processAdditionalProperties(Component component, String[] tagParts) {
    String componentString = tagParts[0];
    tagParts = (String[]) ArrayUtils.remove(tagParts, 0);

    for (String part : tagParts) {
        String[] propertyValue = part.split("=");

        if (propertyValue.length == 2) {
            String path = propertyValue[0];
            String value = propertyValue[1].trim();
            value = StringUtils.removeStart(value, "'");
            value = StringUtils.removeEnd(value, "'");
            ObjectPropertyUtils.setPropertyValue(component, path, value);
        } else {
            throw new RuntimeException("Invalid Message structure for component defined as " + componentString
                    + " around " + part);
        }
    }

    return component;
}

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

/**
 * Inserts &amp;nbsp; into the string passed in, if spaces exist at the beginning and/or end,
 * so spacing is not lost in html translation.
 *
 * @param text string to insert  &amp;nbsp;
 * @return String with  &amp;nbsp; inserted, if applicable
 *///  ww  w. jav  a2s.  c o m
public static String addBlanks(String text) {
    if (StringUtils.startsWithIgnoreCase(text, " ")) {
        text = "&nbsp;" + StringUtils.removeStart(text, " ");
    }

    if (text.endsWith(" ")) {
        text = StringUtils.removeEnd(text, " ") + "&nbsp;";
    }

    return text;
}