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

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

Introduction

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

Prototype

public static boolean isWhitespace(String str) 

Source Link

Document

Checks if the String contains only whitespace.

Usage

From source file:org.eclipse.uomo.xml.test.XMLTestCase.java

private Node getNextRelevantNode(Node node) {
    while (node != null && node.getNodeType() != Node.ELEMENT_NODE
            && !(node.getNodeType() == Node.TEXT_NODE && !StringUtils.isWhitespace(node.getNodeValue())))
        node = node.getNextSibling();/*w  w  w .  j a  va  2 s.c om*/
    return node;
}

From source file:org.eclipse.wb.internal.core.utils.xml.AbstractDocumentHandler.java

@Override
public final void text(String text, boolean isCDATA) throws Exception {
    if (!StringUtils.isWhitespace(text) && !m_nodeStack.isEmpty()) {
        DocumentElement element = m_nodeStack.peek();
        if (element.getTextNode() == null) {
            DocumentTextNode textNode = new DocumentTextNode(isCDATA);
            textNode.setText(text);//from  w w  w  .  j av a  2 s  .c  om
            // set offset/length
            int offset = element.getOpenTagOffset() + element.getOpenTagLength();
            int length = text.length();
            if (isCDATA) {
                length += "<![CDATA[]]>".length();
            }
            textNode.setLength(length);
            textNode.setOffset(offset);
            // append
            element.setTextNode(textNode);
        }
    }
}

From source file:org.executequery.gui.editor.QueryEditorTextPane.java

private void duplicateSelectionOrRowToOffset(int direction) {

    try {/*from w w w  .  j  ava2s. co  m*/

        int start = getStartOffsetAtSelectionOrCursor();
        int end = getEndOffsetAtSelectionOrCursor();

        int offset = 0;
        int selectionOffset = 0;

        String insertText = getText(start, (end - start));
        insertText = StringUtils.removeEnd(insertText, "\n");

        if (direction == DIRECTION_UP) {

            insertText += "\n";
            offset = start;
            selectionOffset = offset;

        } else {

            insertText = "\n" + insertText;
            offset = end - 1;
            selectionOffset = offset + 1;

            if (StringUtils.isWhitespace(insertText) && getLastRow() == getRowAt(end)) {

                return;
            }

        }

        insertTextAtOffset(offset, insertText);
        setCaretPosition(offset + insertText.length());
        moveCaretPosition(selectionOffset);

    } catch (Exception e) {
    }

}

From source file:org.jannocessor.service.render.TemplateHelper.java

public String indent(String code, String prefix) {

    StringBuilder sb = new StringBuilder();

    String[] lines = StringUtils.splitPreserveAllTokens(code, "\n");
    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];/*from w  ww.  j  ava2  s  .c o m*/

        if (!StringUtils.isWhitespace(line)) {
            line = prefix + line;
        }
        sb.append(line);

        if (i < lines.length - 1) {
            sb.append("\n");
        }
    }

    return sb.toString();
}

From source file:org.jbpm.bpel.integration.soap.SoapUtil.java

public static void copyChildNodes(SOAPElement target, Element source) throws SOAPException {
    // easy way out: no child nodes
    if (!source.hasChildNodes())
        return;//from  w w  w.  j a v  a2  s .c om
    // traverse child nodes
    for (Node child = source.getFirstChild(); child != null; child = child.getNextSibling()) {
        switch (child.getNodeType()) {
        case Node.ELEMENT_NODE: {
            copyChildElement(target, (Element) child);
            break;
        }
        case Node.TEXT_NODE:
        case Node.CDATA_SECTION_NODE: {
            String text = child.getNodeValue();
            // drop whitespace-only text nodes
            if (!StringUtils.isWhitespace(text)) {
                target.addTextNode(text);
                if (traceEnabled)
                    log.trace("appended text: " + text);
            }
            break;
        }
        default:
            log.debug("discarding child: " + child);
        }
    }
}

From source file:org.jongo.filter.DefaultFormatFilter.java

/**
 * Generates a new {@linkplain javax.ws.rs.core.Response} for a given 
 * {@link org.jongo.rest.xstream.JongoSuccess} generating the appropriate XML or JSON representation 
 * and setting the Content-Count and Content-Location headers.
 * @param response a {@link org.jongo.rest.xstream.JongoSuccess} to be converted to JSON or XML.
 * @param mime the {@linkplain javax.ws.rs.core.MediaType} used to determine the transport format.
 * @param status the current HTTP code of the response.
 * @return a new {@linkplain javax.ws.rs.core.Response} with the new headers and the content body
 * in either XML or JSON./*www  .j  av  a 2s  .  c o  m*/
 */
private Response formatSuccessResponse(final JongoSuccess response, final MediaType mime,
        final Integer status) {
    String res;
    l.debug("Formatting Success Response");
    if (isXMLCompatible(mime)) {
        StringBuilder b = new StringBuilder("<response><success>");
        b.append(response.isSuccess());
        b.append("</success><resource>");
        b.append(response.getResource());
        b.append("</resource><rows>");
        for (Row r : response.getRows()) {
            b.append("<row roi=\"");
            b.append(r.getRoi());
            b.append("\"><cells>");
            for (String key : r.getCells().keySet()) {
                String val = r.getCells().get(key);
                b.append("<");
                b.append(key.toLowerCase());
                b.append(">");
                b.append(val);
                b.append("</");
                b.append(key.toLowerCase());
                b.append(">");
            }
            b.append("</cells></row>");
        }
        b.append("</rows></response>");
        res = b.toString();
    } else {
        StringBuilder b = new StringBuilder("{");
        b.append("\"success\":");
        b.append(response.isSuccess());
        b.append(",\"cells\":[ "); //this last space is important!
        for (Row r : response.getRows()) {
            List<String> args = new ArrayList<String>();
            for (String key : r.getCells().keySet()) {
                String val = r.getCells().get(key);
                if (StringUtils.isNumeric(val)) {
                    if (StringUtils.isWhitespace(val)) {
                        args.add("\"" + key.toLowerCase() + "\"" + ":" + "\"\"");
                    } else {
                        args.add("\"" + key.toLowerCase() + "\"" + ":" + val);
                    }
                } else {
                    args.add("\"" + key.toLowerCase() + "\"" + ":" + "\"" + val + "\"");
                }
            }

            b.append("{");
            b.append(StringUtils.join(args, ","));
            b.append("}");
            b.append(",");
        }
        b.deleteCharAt(b.length() - 1);
        b.append("]}");
        res = b.toString();
    }

    return Response.status(status).entity(res).header("Content-Count", response.getRows().size())
            .header(HttpHeaders.CONTENT_LOCATION, response.getResource()).build();
}

From source file:org.jongo.JongoUtils.java

/**
 * Infers the java.sql.Types of the given String and returns the JDBC mappable Object corresponding to it.
 * The conversions are like this:/* w  w  w. j a v a  2s.co  m*/
 * String -> String
 * Numeric -> Integer
 * Date or Time -> Date
 * Decimal -> BigDecimal
 * ??? -> TimeStamp
 * @param val a String with the value to be mapped
 * @return a JDBC mappable object instance with the value
 */
public static Object parseValue(String val) {
    Object ret = null;
    if (!StringUtils.isWhitespace(val) && StringUtils.isNumeric(val)) {
        try {
            ret = Integer.valueOf(val);
        } catch (Exception e) {
            l.debug(e.getMessage());
        }
    } else {
        DateTime date = JongoUtils.isDateTime(val);
        if (date != null) {
            l.debug("Got a DateTime " + date.toString(ISODateTimeFormat.dateTime()));
            ret = new java.sql.Timestamp(date.getMillis());
        } else {
            date = JongoUtils.isDate(val);
            if (date != null) {
                l.debug("Got a Date " + date.toString(ISODateTimeFormat.date()));
                ret = new java.sql.Date(date.getMillis());
            } else {
                date = JongoUtils.isTime(val);
                if (date != null) {
                    l.debug("Got a Time " + date.toString(ISODateTimeFormat.time()));
                    ret = new java.sql.Time(date.getMillis());
                }
            }
        }

        if (ret == null && val != null) {
            l.debug("Not a datetime. Try someting else. ");
            try {
                ret = new BigDecimal(val);
            } catch (NumberFormatException e) {
                l.debug(e.getMessage());
                ret = val;
            }
        }
    }
    return ret;
}

From source file:org.mifosplatform.infrastructure.core.serialization.DatatableCommandFromApiJsonDeserializer.java

public void validateForUpdate(final String json) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//from  w w w  . j  a va 2s . c  o m
    // Because all parameters are optional, a check to see if at least one
    // parameter
    // has been specified is necessary in order to avoid JSON requests with
    // no parameters
    if (!json.matches("(?s)\\A\\{.*?(\\\".*?\\\"\\s*?:\\s*?)+.*?\\}\\z")) {
        throw new PlatformDataIntegrityException("error.msg.invalid.request.body.no.parameters",
                "Provided JSON request body does not have any parameters.");
    }

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForUpdate);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("datatable");

    final JsonElement element = this.fromApiJsonHelper.parse(json);
    final String apptableName = this.fromApiJsonHelper.extractStringNamed("apptableName", element);
    baseDataValidator.reset().parameter("apptableName").value(apptableName).ignoreIfNull().notBlank()
            .isOneOfTheseValues(this.supportedApptableNames);
    final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : "";

    final JsonArray changeColumns = this.fromApiJsonHelper.extractJsonArrayNamed("changeColumns", element);
    baseDataValidator.reset().parameter("changeColumns").value(changeColumns).ignoreIfNull()
            .jsonArrayNotEmpty();

    if (changeColumns != null) {
        for (final JsonElement column : changeColumns) {
            this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(),
                    this.supportedParametersForChangeColumns);

            final String name = this.fromApiJsonHelper.extractStringNamed("name", column);
            baseDataValidator.reset().parameter("name").value(name).notBlank()
                    .isNotOneOfTheseValues("id", fkColumnName)
                    .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);

            final String newName = this.fromApiJsonHelper.extractStringNamed("newName", column);
            baseDataValidator.reset().parameter("newName").value(newName).ignoreIfNull().notBlank()
                    .notExceedingLengthOf(50).isNotOneOfTheseValues("id", fkColumnName)
                    .matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN);

            if (this.fromApiJsonHelper.parameterExists("length", column)) {
                final String lengthStr = this.fromApiJsonHelper.extractStringNamed("length", column);
                if (StringUtils.isWhitespace(lengthStr) || !StringUtils.isNumeric(lengthStr)
                        || StringUtils.isBlank(lengthStr)) {
                    baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero");
                } else {
                    final Integer length = Integer.parseInt(lengthStr);
                    baseDataValidator.reset().parameter("length").value(length).ignoreIfNull().notBlank()
                            .positiveAmount();
                }
            }

            final String code = this.fromApiJsonHelper.extractStringNamed("code", column);
            baseDataValidator.reset().parameter("code").value(code).ignoreIfNull().notBlank()
                    .notExceedingLengthOf(100).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);

            final String newCode = this.fromApiJsonHelper.extractStringNamed("newCode", column);
            baseDataValidator.reset().parameter("newCode").value(newCode).ignoreIfNull().notBlank()
                    .notExceedingLengthOf(100).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);

            if (StringUtils.isBlank(code) && StringUtils.isNotBlank(newCode)) {
                baseDataValidator.reset().parameter("code").value(code)
                        .cantBeBlankWhenParameterProvidedIs("newCode", newCode);
            }

            final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column);
            baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank()
                    .isOneOfTheseValues(true, false);

            final Boolean after = this.fromApiJsonHelper.extractBooleanNamed("after", column);
            baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank()
                    .isOneOfTheseValues(true, false);
        }
    }

    final JsonArray addColumns = this.fromApiJsonHelper.extractJsonArrayNamed("addColumns", element);
    baseDataValidator.reset().parameter("addColumns").value(addColumns).ignoreIfNull().jsonArrayNotEmpty();

    if (addColumns != null) {
        for (final JsonElement column : addColumns) {
            this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(),
                    this.supportedParametersForAddColumns);

            final String name = this.fromApiJsonHelper.extractStringNamed("name", column);
            baseDataValidator.reset().parameter("name").value(name).notBlank()
                    .isNotOneOfTheseValues("id", fkColumnName)
                    .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);

            validateType(baseDataValidator, column);

            final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column);
            baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank()
                    .isOneOfTheseValues(true, false);

            final Boolean after = this.fromApiJsonHelper.extractBooleanNamed("after", column);
            baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank()
                    .isOneOfTheseValues(true, false);
        }
    }

    final JsonArray dropColumns = this.fromApiJsonHelper.extractJsonArrayNamed("dropColumns", element);
    baseDataValidator.reset().parameter("dropColumns").value(dropColumns).ignoreIfNull().jsonArrayNotEmpty();

    if (dropColumns != null) {
        for (final JsonElement column : dropColumns) {
            this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(),
                    this.supportedParametersForDropColumns);

            final String name = this.fromApiJsonHelper.extractStringNamed("name", column);
            baseDataValidator.reset().parameter("name").value(name).notBlank()
                    .isNotOneOfTheseValues("id", fkColumnName)
                    .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN);
        }
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:org.openlegacy.terminal.web.render.support.DefaultBidiElementsProvider.java

private Element createLabelInner(Element rootNode, TerminalField field, ScreenSize screenSize) {
    String value = field.getVisualValue();
    if (value == null || value.trim().length() > 0) {
        value = field.getValue();// ww  w  .  ja va  2  s.  c o m
    }
    if (field.isHidden() || StringUtils.isWhitespace(value) && field.getBackColor() == Color.BLACK) {
        return null;
    }
    if (field.getBackColor() == Color.BLACK) {
        value = value.trim();
    }

    Element label = createTag(rootNode, HtmlConstants.SPAN);
    populateCommonAttributes(label, field);

    Text textNode = rootNode.getOwnerDocument().createTextNode(value);
    label.appendChild(textNode);

    rootNode.appendChild(label);
    return label;

}

From source file:org.openlegacy.terminal.web.render.support.DefaultElementsProvider.java

@Override
public Element createLabel(Element rootNode, TerminalField field, ScreenSize screenSize) {

    String value = field.getValue();
    if (field.isHidden() || StringUtils.isWhitespace(value) && field.getBackColor() == Color.BLACK) {
        return null;
    }// ww w  .  j  a  v  a 2 s.co  m
    if (field.getBackColor() == Color.BLACK) {
        value = value.trim();
    }

    Element label = createTag(rootNode, HtmlConstants.SPAN);
    populateCommonAttributes(label, field);

    Text textNode = rootNode.getOwnerDocument().createTextNode(value);
    label.appendChild(textNode);

    rootNode.appendChild(label);
    return label;
}