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.uif.util.ConstraintStateUtils.java

/**
 * Determines if the constraint passed in applies for the applicableState, based on the stateMapping
 *
 * <p>Note: this method will automatically return TRUE if the stateMapping is null, the Constraint is not a BaseConstraint,
 * if there are no states defined on the Constraint, or if the state it applies to cannot be found in the stateMapping,
 * because in all these cases the Constraint is considered
 * stateless and will apply to any state</p>
 *
 * @param applicableState the state to check to see if the constraint applies
 * @param constraint the Constraint to check
 * @param stateMapping the StateMapping object containing state information
 * @return true if the Constraint applies to the applicableState, false otherwise
 *//*from w w  w .  java 2 s  . co  m*/
public static boolean constraintAppliesForState(String applicableState, Constraint constraint,
        StateMapping stateMapping) {
    List<String> stateOrder = new ArrayList<String>();
    if (stateMapping != null) {
        stateOrder = stateMapping.getStates();
    }

    if (stateMapping == null || !(constraint instanceof BaseConstraint)
            || StringUtils.isEmpty(applicableState)) {
        //process constraint because it is considered "stateless" if not a BaseConstraint
        //or no associated state mapping or no has no state to compare to
        return true;
    } else if (((BaseConstraint) constraint).getStates() == null
            || ((BaseConstraint) constraint).getStates().isEmpty()) {
        //simple case - no states for this constraint, so always apply
        return true;
    } else if (((BaseConstraint) constraint).getStates().contains(applicableState)
            && stateOrder.contains(applicableState)) {
        //constraint applies for the applicableState and the state exists for the object
        return true;
    } else {
        for (String constraintState : ((BaseConstraint) constraint).getStates()) {
            //range case
            if (constraintState.contains(">")) {
                String[] rangeArray = constraintState.split(">");
                if (rangeArray[1].endsWith("+")) {
                    //make 2nd part of range current state being checked if nothing is
                    //matched below for the range case
                    constraintState = rangeArray[1];
                    rangeArray[1] = StringUtils.removeEnd(rangeArray[1], "+");
                }
                if (stateOrder.contains(rangeArray[0]) && stateOrder.contains(rangeArray[1])) {
                    for (int i = stateOrder.indexOf(rangeArray[0]); i <= stateOrder
                            .indexOf(rangeArray[1]); i++) {
                        if (stateOrder.get(i).equals(applicableState)) {
                            return true;
                        }
                    }
                } else {
                    throw new RuntimeException("Invalid state range: " + constraintState);
                }
            }

            //+ case (everything after and including this state)
            if (constraintState.contains("+")) {
                constraintState = StringUtils.removeEnd(constraintState, "+");
                if (stateOrder.contains(constraintState)) {
                    for (int i = stateOrder.indexOf(constraintState); i < stateOrder.size(); i++) {
                        if (stateOrder.get(i).equals(applicableState)) {
                            return true;
                        }
                    }
                } else {
                    throw new RuntimeException("Invalid constraint state: " + constraintState);
                }
            }
        }
    }
    //if no case is matched, return false
    return false;
}

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   w ww.  j  av a2s .  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.ExpressionUtils.java

/**
 * Used internally by parseExpression to evalute if the current stack is a property
 * name (ie, will be a control on the form)
 *
 * @param stack//from  w ww  .  ja v a 2 s .  co m
 * @param controlNames
 */
public static void evaluateCurrentStack(String stack, List<String> controlNames) {
    if (StringUtils.isNotBlank(stack)) {
        if (!(stack.equals("==") || stack.equals("!=") || stack.equals(">") || stack.equals("<")
                || stack.equals(">=") || stack.equals("<=") || stack.equalsIgnoreCase("ne")
                || stack.equalsIgnoreCase("eq") || stack.equalsIgnoreCase("gt") || stack.equalsIgnoreCase("lt")
                || stack.equalsIgnoreCase("lte") || stack.equalsIgnoreCase("gte")
                || stack.equalsIgnoreCase("matches") || stack.equalsIgnoreCase("null")
                || stack.equalsIgnoreCase("false") || stack.equalsIgnoreCase("true")
                || stack.equalsIgnoreCase("and") || stack.equalsIgnoreCase("or") || stack.contains("#empty")
                || stack.equals("!") || stack.contains("#emptyList") || stack.contains("#listContains")
                || stack.startsWith("'") || stack.endsWith("'"))) {

            boolean isNumber = false;
            if ((StringUtils.isNumeric(stack.substring(0, 1)) || stack.substring(0, 1).equals("-"))) {
                try {
                    Double.parseDouble(stack);
                    isNumber = true;
                } catch (NumberFormatException e) {
                    isNumber = false;
                }
            }

            if (!(isNumber)) {
                //correct argument of a custom function ending in comma
                if (StringUtils.endsWith(stack, ",")) {
                    stack = StringUtils.removeEnd(stack, ",").trim();
                }

                if (!controlNames.contains(stack)) {
                    controlNames.add(stack);
                }
            }
        }
    }
}

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.jav a  2  s .c  om*/
    // 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

/**
 * Parses the message text passed in and returns the resulting rich message component structure.
 *
 * <p>If special characters [] are detected the message is split at that location.  The types of features supported
 * by the parse are (note that &lt;&gt; are not part of the content, they specify placeholders):
 * <ul>/*from w ww .  j  a  v  a 2 s.  co m*/
 * <li>[id=&lt;component id&gt;] - insert component with id specified at that location in the message</li>
 * <li>[n] - insert component at index n from the inlineComponent list</li>
 * <li>[&lt;html tag&gt;][/&lt;html tag&gt;] - insert html content directly into the message content at that
 * location,
 * without the need to escape the &lt;&gt; characters in xml</li>
 * <li>[color=&lt;html color code/name&gt;][/color] - wrap content in color tags to make text that color
 * in the message</li>
 * <li>[css=&lt;css classes&gt;][/css] - apply css classes specified to the wrapped content - same as wrapping
 * the content in span with class property set</li>
 * <li>[link=&lt;href src&gt;][/link] - an easier way to create an anchor that will open in a new page to the
 * href specified after =</li>
 * <li>[action=&lt;href src&gt;][/action] - create an action link inline without having to specify a component by
 * id or index.  The options for this are as follows and MUST be in a comma seperated list in the order specified
 * (specify 1-4 always in this order):
 * <ul>
 * <li>methodToCall(String)</li>
 * <li>validateClientSide(boolean) - true if not set</li>
 * <li>ajaxSubmit(boolean) - true if not set</li>
 * <li>successCallback(js function or function declaration) - this only works when ajaxSubmit is true</li>
 * </ul>
 * The tag would look something like this [action=methodToCall]Action[/action] in most common cases.  And in more
 * complex cases [action=methodToCall,true,true,functionName]Action[/action].  <p>In addition to these settings,
 * you can also specify data to send to the server in this fashion (space is required between settings and data):
 * </p>
 * [action=&lt;action settings&gt; data={key1: 'value 1', key2: value2}]
 * </li>
 * </ul>
 * If the [] characters are needed in message text, they need to be declared with an escape character: \\[ \\]
 * </p>
 *
 * @param messageId id of the message
 * @param messageText message text to be parsed
 * @param componentList the inlineComponent list
 * @param view the current view
 * @param parseComponents true to parse components
 * @return list of components representing the parsed message structure
 */
public static List<Component> parseMessage(String messageId, String messageText, List<Component> componentList,
        View view, boolean parseComponents) {
    messageText = messageText.replace("\\" + KRADConstants.MessageParsing.LEFT_TOKEN,
            KRADConstants.MessageParsing.LEFT_BRACKET);
    messageText = messageText.replace("\\" + KRADConstants.MessageParsing.RIGHT_TOKEN,
            KRADConstants.MessageParsing.RIGHT_BRACKET);
    messageText = messageText.replace(KRADConstants.MessageParsing.RIGHT_TOKEN,
            KRADConstants.MessageParsing.RIGHT_TOKEN_PLACEHOLDER);
    String[] messagePieces = messageText.split("[\\" + KRADConstants.MessageParsing.LEFT_TOKEN + "|\\"
            + KRADConstants.MessageParsing.RIGHT_TOKEN + "]");

    List<Component> messageComponentStructure = new ArrayList<Component>();

    //current message object to concatenate to after it is generated to prevent whitespace issues and
    //creation of multiple unneeded objects
    Message currentMessageComponent = null;

    for (String messagePiece : messagePieces) {
        if (messagePiece.endsWith(KRADConstants.MessageParsing.RIGHT_TOKEN_MARKER)) {
            messagePiece = StringUtils.removeEnd(messagePiece, KRADConstants.MessageParsing.RIGHT_TOKEN_MARKER);

            if (StringUtils.startsWithIgnoreCase(messagePiece,
                    KRADConstants.MessageParsing.COMPONENT_BY_ID + "=") && parseComponents) {
                //Component by Id
                currentMessageComponent = processIdComponentContent(messagePiece, messageComponentStructure,
                        currentMessageComponent, view);
            } else if (messagePiece.matches("^[0-9]+( .+=.+)*$") && parseComponents) {
                //Component by index of inlineComponents
                currentMessageComponent = processIndexComponentContent(messagePiece, componentList,
                        messageComponentStructure, currentMessageComponent, view, messageId);
            } else if (StringUtils.startsWithIgnoreCase(messagePiece, KRADConstants.MessageParsing.COLOR + "=")
                    || StringUtils.startsWithIgnoreCase(messagePiece,
                            "/" + KRADConstants.MessageParsing.COLOR)) {
                //Color span
                currentMessageComponent = processColorContent(messagePiece, currentMessageComponent, view);
            } else if (StringUtils.startsWithIgnoreCase(messagePiece,
                    KRADConstants.MessageParsing.CSS_CLASSES + "=")
                    || StringUtils.startsWithIgnoreCase(messagePiece,
                            "/" + KRADConstants.MessageParsing.CSS_CLASSES)) {
                //css class span
                currentMessageComponent = processCssClassContent(messagePiece, currentMessageComponent, view);
            } else if (StringUtils.startsWithIgnoreCase(messagePiece, KRADConstants.MessageParsing.LINK + "=")
                    || StringUtils.startsWithIgnoreCase(messagePiece,
                            "/" + KRADConstants.MessageParsing.LINK)) {
                //link (a tag)
                currentMessageComponent = processLinkContent(messagePiece, currentMessageComponent, view);
            } else if (StringUtils.startsWithIgnoreCase(messagePiece,
                    KRADConstants.MessageParsing.ACTION_LINK + "=")
                    || StringUtils.startsWithIgnoreCase(messagePiece,
                            "/" + KRADConstants.MessageParsing.ACTION_LINK)) {
                //action link (a tag)
                currentMessageComponent = processActionLinkContent(messagePiece, currentMessageComponent, view);
            } else if (messagePiece.equals("")) {
                //do nothing    
            } else {
                //raw html content
                currentMessageComponent = processHtmlContent(messagePiece, currentMessageComponent, view);
            }
        } else {
            //raw string
            messagePiece = addBlanks(messagePiece);
            currentMessageComponent = concatenateStringMessageContent(currentMessageComponent, messagePiece,
                    view);
        }
    }

    if (currentMessageComponent != null && StringUtils.isNotEmpty(currentMessageComponent.getMessageText())) {
        messageComponentStructure.add(currentMessageComponent);
        currentMessageComponent = null;
    }

    return messageComponentStructure;
}

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
 *///  www.ja  v  a  2 s .  c  om
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
 *///from   w ww.  j av 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;
}

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

/**
 * Process a piece of the message that has link content by creating an anchor (a tag) with the href set
 *
 * @param messagePiece String piece with link content
 * @param currentMessageComponent the state of the current text based message being built
 * @param view current View//w w  w  .j av a2 s . c  o  m
 * @return currentMessageComponent with the new textual content generated by this method appended to its
 *         messageText
 */
private static Message processLinkContent(String messagePiece, Message currentMessageComponent, View view) {
    if (!StringUtils.startsWithIgnoreCase(messagePiece, "/")) {
        //clean up href
        messagePiece = StringUtils.removeStart(messagePiece, KRADConstants.MessageParsing.LINK + "=");
        messagePiece = StringUtils.removeStart(messagePiece, "'");
        messagePiece = StringUtils.removeEnd(messagePiece, "'");
        messagePiece = StringUtils.removeStart(messagePiece, "\"");
        messagePiece = StringUtils.removeEnd(messagePiece, "\"");

        messagePiece = "<a href='" + messagePiece + "' target='_blank'>";
    } else {
        messagePiece = "</a>";
    }

    return concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
}

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

/**
 * Translates an Object to a String for representing the given Object as a JavaScript value
 * /*ww  w  .j  av  a 2s  .  c o  m*/
 * <p>
 * Handles null, List, Map, and Set collections, along with non quoting for numeric and boolean
 * types. Complex types are treated as a String value using toString
 * </p>
 * 
 * @param value Object instance to translate
 * @return JS value
 */
public static String translateValue(Object value) {
    String jsValue = "";

    if (value == null) {
        jsValue = "null";
        return jsValue;
    }

    if (value instanceof List) {
        jsValue = "[";

        List<Object> list = (List<Object>) value;
        for (Object listItem : list) {
            jsValue += translateValue(listItem);
            jsValue += ",";
        }
        jsValue = StringUtils.removeEnd(jsValue, ",");

        jsValue += "]";
    } else if (value instanceof Set) {
        jsValue = "[";

        Set<Object> set = (Set<Object>) value;
        for (Object setItem : set) {
            jsValue += translateValue(setItem);
            jsValue += ",";
        }
        jsValue = StringUtils.removeEnd(jsValue, ",");

        jsValue += "]";
    } else if (value instanceof Map) {
        jsValue = "{";

        Map<Object, Object> map = (Map<Object, Object>) value;
        for (Map.Entry<Object, Object> mapEntry : map.entrySet()) {
            jsValue += "\"" + mapEntry.getKey().toString() + "\":";
            jsValue += translateValue(mapEntry.getValue());
            jsValue += ",";
        }
        jsValue = StringUtils.removeEnd(jsValue, ",");

        jsValue += "}";
    } else {
        Class<?> valueClass = value.getClass();
        if (TypeUtils.isSimpleType(valueClass) || TypeUtils.isClassClass(valueClass)) {
            boolean quoteValue = true;

            if (TypeUtils.isBooleanClass(valueClass) || TypeUtils.isDecimalClass(valueClass)
                    || TypeUtils.isIntegralClass(valueClass)) {
                quoteValue = false;
            }

            if (quoteValue) {
                jsValue = "\"";
            }

            jsValue += value.toString();

            if (quoteValue) {
                jsValue += "\"";
            }
        } else {
            // treat as data object
            jsValue = "{";
            Map<String, PropertyDescriptor> propertyDescriptors = ObjectPropertyUtils
                    .getPropertyDescriptors(valueClass);
            for (String propertyName : propertyDescriptors.keySet()) {
                if (ObjectPropertyUtils.isReadableProperty(value, propertyName)
                        && !"class".equals(propertyName)) {
                    Object propertyValue = ObjectPropertyUtils.getPropertyValueAsText(value, propertyName);
                    jsValue += propertyName + ":";
                    jsValue += translateValue(propertyValue);
                    jsValue += ",";
                }
            }
            jsValue = StringUtils.removeEnd(jsValue, ",");

            jsValue += "}";
        }
    }

    return jsValue;
}

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

/**
 * Converts a map of string values to a json equivalent by converting the string values through
 * the convertToJsValue(String) method; this will output a string representation of the map in
 * json format//ww  w.ja v  a  2 s .c  om
 * 
 * @param stringMap the map of String values to convert to a simple json object representation
 * @return the json object as a string (for use in js)
 */
public static String convertToJsValue(Map<String, String> stringMap) {
    if (stringMap == null || stringMap.isEmpty()) {
        return "{}";
    }

    String convertedValue = "{";
    for (String key : stringMap.keySet()) {
        convertedValue = convertedValue + "\"" + key + "\":" + convertToJsValue(stringMap.get(key)) + ",";
    }

    convertedValue = StringUtils.removeEnd(convertedValue, ",");
    convertedValue = convertedValue + "}";

    return convertedValue;
}