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:net.bible.service.format.osistohtml.osishandlers.OsisToCanonicalTextSaxHandler.java

@Override
protected void write(String s) {
    // reduce amount of whitespace becasue a lot of space was occurring between verses in ESVS and several other books
    if (!StringUtils.isWhitespace(s)) {
        super.write(s);
        spaceJustWritten = false;/*from  ww  w .  j a  va  2s. c o m*/
    } else if (!spaceJustWritten) {
        super.write(" ");
        spaceJustWritten = true;
    }
}

From source file:com.edgenius.wiki.render.impl.RichRenderEngineImpl.java

/**
 * Input HTML return Markup. RenderContext only contains spaceUname
 *///from  ww w  .j a v  a 2s  .  c om
public String render(String htmlText, RenderContext context) {
    long start = System.currentTimeMillis();

    htmlText = htmlText.replaceAll("\\r", "");

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Parse html text into HTMLNode list
    HtmlNodeListenerImpl listener = new HtmlNodeListenerImpl();
    HtmlParser htmlParser = new HtmlParser();
    htmlParser.scan(htmlText, listener);
    //get HTML node list
    HTMLNodeContainer nodeContainer = listener.getHtmlNode();
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // remove all tag which has id or aid is "norender"
    RichTagUtil.removeNoRenderTag(nodeContainer);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //after TinyMCE, it may contain some useless or duplicated HTML tag, 
    //such tag surrounding empty, or <font size=bb><font size=cc>some text</font></font> etc.
    //here will remove such useless and merge duplicated HTML tag
    optimizeHTML(nodeContainer);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // all Text node need do HTMLEscape and markup escape conversion,e.g, &gt; to >, *bold* to \*bold\* etc.
    //in this method, nodeContainer may be re-initialized to a new instance.
    nodeContainer = escapeText(htmlText, nodeContainer);

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //finally, arrive here... use all available filters to convert all html tag node to markup
    List<Filter> filters = filterProvider.getFilterList();
    for (Filter filter : filters) {
        nodeContainer = filter.filter(nodeContainer, context);
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //after filter complete, convert HTMLNode to string.
    StringBuffer markupText = new StringBuffer();
    //this flag is use to avoid surround consequence unknown html tag, such as <object><param><object>, only need surround one paired {html} 
    boolean reqHTMLEnd = false;
    boolean reqNewline = false;
    boolean lineStart = false;
    for (HTMLNode node : nodeContainer) {
        if (node.isTextNode()) {
            if (!StringUtils.isEmpty(node.getText())) {
                reqNewline = startNewline(markupText, node.getText(), reqNewline);
                if (reqHTMLEnd) {
                    markupText.append("{html}");
                    reqHTMLEnd = false;
                }
                if (lineStart) {
                    if (!StringUtils.isWhitespace(node.getText())) {
                        //if node is blank text, and it is just after a line start, skip it.
                        //for example, list <ol>   <li>something</li></ol>,  li is with LINE_START_TAG tag, however, spaces between
                        //<ol> and <li> are harmful (converted mark line start with space: "  # something), so remove blank here.
                        markupText.append(node.getText());
                        lineStart = false;
                    }
                } else {
                    markupText.append(node.getText());
                }
            } //skip empty text
        } else if (HTMLNode.LINE_END_TAG.equals(node.getText())) {
            reqNewline = true;
            lineStart = false;
        } else if (HTMLNode.LINE_START_TAG.equals(node.getText())) {
            //does next tag will in a new line start? if yes, do nothing, otherwise, append "\n"
            String line = markupText.toString();
            if (line.trim().length() > 0 && !StringUtil.endOfAny(line, new String[] { "\n", "\r" })) {
                if (reqHTMLEnd) {
                    markupText.append("{html}");
                    reqHTMLEnd = false;
                }
                markupText.append("\n");
            }
            lineStart = true;
        } else {
            lineStart = false;
            //this assume non text node always return non-empty value from node.getText() 
            reqNewline = startNewline(markupText, node.getText(), reqNewline);
            //some tag can not be handled by filters, then surrounding them by {html} macro,
            if (!reqHTMLEnd) {
                markupText.append("{html}");
                reqHTMLEnd = true;
            }
            markupText.append(node.getText());
        }
    }

    if (reqHTMLEnd)
        markupText.append("{html}");

    log.info("Render rich content to markup takes: " + (System.currentTimeMillis() - start));

    return markupText.toString();
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderXPath.java

@Override
public void initialize(UimaContext arg0) throws ResourceInitializationException {
    super.initialize(arg0);

    fileIterator = getFileSetIterator();
    XPath xpath = XPathFactory.newInstance().newXPath();
    nodes = new ArrayDeque<Node>();

    if (StringUtils.isWhitespace(rootXPath)) {
        throw new IllegalArgumentException("Illegal root XPath expression. Please provide a valid one.");
    }//from   ww  w.  j  a v a2  s  .  c om
    try {
        compiledRootXPath = xpath.compile(rootXPath);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Illegal root XPath expression. Please provide a valid one.");
    }

    if (docIdTag != null) {
        if (StringUtils.isWhitespace(docIdTag)) {
            throw new IllegalArgumentException("Illegal ID XPath expression. Please provide a valid one.");
        }
        try {
            compiledIdXPath = xpath.compile(docIdTag);
        } catch (XPathExpressionException e) {
            throw new IllegalArgumentException("Illegal ID XPath expression. Please provide a valid one.");
        }
    }

    // Substitution
    if (substituteTags != null && substituteTags.length > 0) {
        if (substituteTags.length % 2 != 0) {
            throw new IllegalArgumentException("Parameter substitute tags must "
                    + "be given in an array of even number of elements, in 'before, after' order");
        }

        useSubstitution = true;
        substitution = new HashMap<String, String>(substituteTags.length);
        for (int i = 0; i < substituteTags.length; i += 2) {
            substitution.put(substituteTags[i], substituteTags[i + 1]);
        }
    }

    processNextFile();
}

From source file:msi.gama.application.workspace.WorkspaceModelsManager.java

/**
 * @param filePath//from  w  w w .jav  a2  s .  co m
 * @return
 */
private IFile findAndLoadIFile(final String filePath) {
    // GAMA.getGui().debug("WorkspaceModelsManager.findAndLoadIFile " + filePath);
    // No error in case of an empty argument
    if (filePath == null || filePath.isEmpty() || StringUtils.isWhitespace(filePath)) {
        return null;
    }
    final IPath path = new Path(filePath);

    // 1st case: the path can be identified as a file residing in the workspace
    IFile result = findInWorkspace(path);
    if (result != null) {
        return result;
    }
    // 2nd case: the path is outside the workspace
    result = findOutsideWorkspace(path);
    if (result != null) {
        return result;
    }
    System.out.println("File " + filePath
            + " cannot be located. Please check its name and location. Arguments provided were : "
            + Arrays.toString(CommandLineArgs.getApplicationArgs()));
    return null;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderXPath.java

@Override
public void getNext(CAS cas) throws IOException {
    // Initialize CAS with document meta data
    initCas(cas, currentFileResource, null);

    if (!StringUtils.isWhitespace(language)) {
        cas.setDocumentLanguage(language);
    }//  w ww  .  j  a  va 2  s . com

    // The buffer where document text is to be stored
    StringBuilder documentText = new StringBuilder();

    Node node = nodes.poll();
    if (node != null) {
        processNode(cas, node, documentText);
    }

    // Set document text in cas or error if nothing gets parsed out
    String documentTextString = documentText.toString();
    if (StringUtils.isWhitespace(documentTextString)) {
        cas.setDocumentText("[Parse error]");
    } else {
        cas.setDocumentText(documentTextString);
    }
}

From source file:com.gst.infrastructure.core.serialization.DatatableCommandFromApiJsonDeserializer.java

public void validateForUpdate(final String json) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//from ww w .j  av  a 2 s.co 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<>();
    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:edu.utah.further.core.api.xml.XmlUtil.java

/**
 * Basic StAX element printout. For more sophisticated functionality, use
 * {@link XmlStreamPrinter}./*from ww w  .  jav a 2  s . com*/
 * 
 * @param reader
 *            reader
 * @return reader's next element textual representation
 */
public static String getEventSimpleString(final XMLStreamReader reader) {
    switch (reader.getEventType()) {
    case XMLStreamConstants.START_ELEMENT:
        return "START_ELEMENT:\t\"" + reader.getLocalName() + "\"";
    case XMLStreamConstants.END_ELEMENT:
        return "END_ELEMENT:\t\"" + reader.getLocalName() + "\"";
    case XMLStreamConstants.START_DOCUMENT:
        return "START_DOCUMENT";
    case XMLStreamConstants.END_DOCUMENT:
        return "END_DOCUMENT";
    case XMLStreamConstants.CHARACTERS:
        return "CHARACTERS:\t\"" + reader.getText() + "\"" + " blank? "
                + StringUtils.isWhitespace(reader.getText());
    case XMLStreamConstants.SPACE:
        return "SPACE:\t\"" + reader.getText() + "\"";
    default:
        return "EVENT:\t" + reader.getEventType();
    }
}

From source file:com.zilotti.hostsjuggler.view.ActiveHostsFileWindow.java

private void highlightActiveHostsFile(File hostsFile) throws IOException, ParseException {
    BufferedReader br = null;/*ww  w .  j ava 2  s.c  o m*/

    try {
        /* Converts the file to text */
        // StringReader fileReader = new StringReader(getLinuxHostsFile()); // For testing
        br = new BufferedReader(new FileReader(hostsFile));

        /* Character counter */
        int charCounter = 0;

        /* Line counter */
        int lineCounter = 1;

        /* Line */
        String line = null;

        while ((line = br.readLine()) != null) {
            line += "\n";
            activeHostsFileStyledText.append(line);

            /*
             * Remark line
             */
            if (line.startsWith(REM_LINE_CHAR)) {
                int prevCharCounter = charCounter;
                charCounter += line.length();

                formatRemark(prevCharCounter, charCounter);

                if (log.isTraceEnabled()) {
                    log.trace("line  ='" + line + "'");
                    //log.trace("remark='"+ getWindowsHostsFile().substring(prevCharCounter, charCounter) +"' ("+ prevCharCounter +","+ charCounter +")");
                }
            } else if (StringUtils.isBlank(line)) // Empty line
            {
                charCounter += line.length();
            } else // Expects a host line
            {
                int localCharCounter = charCounter;
                charCounter += line.length();

                Scanner scanner = new Scanner(line);
                scanner.useDelimiter(Pattern.compile("(\\s)"));

                /* Output of the parsing code */
                String ipAddress = null;

                /* Verifies the number of tokens. At least two must exist (IP address and one name) */
                if (scanner.hasNext()) {
                    /* The first token must be an IP address */
                    {
                        ipAddress = scanner.next();

                        if (!NetworkUtils.isIpAddress(ipAddress))
                            throw new ParseException("IP address expected. Token found: " + ipAddress,
                                    lineCounter);

                        int prevCharCounter = localCharCounter;
                        localCharCounter += ipAddress.length() + 1; // Sums 1 because of the lost space

                        formatIpAddress(prevCharCounter, localCharCounter);
                    }

                    /* The remaining tokens are the host names associated to the IP address */
                    {
                        while (scanner.hasNext()) {
                            String hostName = scanner.next();

                            if (StringUtils.isWhitespace(hostName) || StringUtils.isBlank(hostName)) {
                                localCharCounter++;
                            } else if (NetworkUtils.isHostName(hostName)) {
                                int prevCharCounter = localCharCounter;
                                localCharCounter += hostName.length() + 1; // 1 to compensate the space lost

                                //                        if(log.isTraceEnabled())
                                //                           log.trace("hostName='"+ getWindowsHostsFile().substring(prevCharCounter, localCharCounter) +"' ("+ prevCharCounter +","+ localCharCounter +")");

                                formatHostName(prevCharCounter, localCharCounter);
                            } else
                                throw new ParseException("Host name expected at token " + localCharCounter
                                        + ". Found: " + hostName, lineCounter);
                        }
                    }
                } else
                    throw new ParseException("At least 2 tokens are expected from a host line.", lineCounter);
            }

            lineCounter++;
        }
    } finally {
        if (br != null)
            br.close();
    }
}

From source file:airlift.util.AirliftUtil.java

/**
 * Convert to short./*from  www .  ja  v  a2s  . co  m*/
 *
 * @param _byteArray the _byte array
 * @return the short
 */
public static Short convertToShort(byte[] _byteArray) {
    String convertedBytes = convertToString(_byteArray);
    return (StringUtils.isNumeric(convertedBytes) == true && StringUtils.isWhitespace(convertedBytes) == false)
            ? Short.parseShort(convertedBytes)
            : null;
}

From source file:airlift.util.AirliftUtil.java

/**
 * Convert to long./*  ww  w .  ja  v  a 2s  . c o  m*/
 *
 * @param _byteArray the _byte array
 * @return the long
 */
public static Long convertToLong(byte[] _byteArray) {
    String convertedBytes = convertToString(_byteArray);
    return (StringUtils.isNumeric(convertedBytes) == true && StringUtils.isWhitespace(convertedBytes) == false)
            ? Long.parseLong(convertedBytes)
            : null;
}