Example usage for org.apache.commons.lang3 StringUtils splitPreserveAllTokens

List of usage examples for org.apache.commons.lang3 StringUtils splitPreserveAllTokens

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils splitPreserveAllTokens.

Prototype

public static String[] splitPreserveAllTokens(final String str, final String separatorChars) 

Source Link

Document

Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators.

Usage

From source file:com.google.dart.engine.services.refactoring.NamingConventions.java

/**
 * @return the {@link RefactoringStatus} with {@link RefactoringStatusSeverity#OK} if the name is
 *         valid, {@link RefactoringStatusSeverity#WARNING} if the name is discouraged, or
 *         {@link RefactoringStatusSeverity#ERROR} if the name is illegal.
 *///  w  ww .  j av a 2  s.c  o  m
public static RefactoringStatus validateLibraryName(String name) {
    // null
    if (name == null) {
        return RefactoringStatus.createErrorStatus("Library name must not be null.");
    }
    // blank
    if (StringUtils.isBlank(name)) {
        return RefactoringStatus.createErrorStatus("Library name must not be blank.");
    }
    // check identifiers
    String[] identifiers = StringUtils.splitPreserveAllTokens(name, '.');
    for (String identifier : identifiers) {
        RefactoringStatus status = validateIdentifier0(identifier, "Library name identifier");
        if (!status.isOK()) {
            return status;
        }
    }
    // should not have upper-case letters
    for (String identifier : identifiers) {
        char[] chars = identifier.toCharArray();
        for (char c : chars) {
            if (Character.isUpperCase(c)) {
                return RefactoringStatus.createWarningStatus(
                        "Library name should consist of lower-case identifier separated by dots.");
            }
        }
    }
    // OK
    return new RefactoringStatus();
}

From source file:de.unentscheidbar.validation.builtin.HostNameValidator.java

@Override
protected void validateNonEmptyString(ValidationResult problems, String model) {

    /*/*from w  ww  .j a  va  2  s . com*/
     * #1 Host names must not start with a dot.
     */
    if (model.startsWith(".")) {
        problems.add(Id.HOST_STARTS_WITH_DOT, model);
        return;
    }

    /*
     * #2 Host names must not start or end with a hyphen.
     */
    if (model.endsWith("-") || model.startsWith("-")) {
        problems.add(Id.HOST_STARTS_OR_ENDS_WITH_HYPHEN, model);
    }

    /*
     * #3 The complete host name must not be longer than 255 characters and does not permit
     * leading or trailing whitespace.
     */
    MayNotContainWhitespaceValidator.instance().validate(problems, model);
    if (model.length() > 255) {
        problems.add(Id.HOST_TOO_LONG);
    }

    /*
     * #4 Each label must consist of 1-63 characters. Only ASCII a-z, 0-9, period and hypen are
     * allowed.
     */
    String[] parts = StringUtils.splitPreserveAllTokens(model, '.');
    for (int i = 0; i < parts.length; i++) {
        validateLabel(problems, parts[i]);
    }
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * For rewrited urls like 'http://dev.com/q/search%20terms/anotherparameter/anotherparametervalue'
 *
 * @param url           url//  w  w  w.j a  v  a  2s  .  com
 * @param parameterName parameter name
 * @return rewrited parameter
 */
public static String getRewritedParameter(String url, String parameterName) {

    String[] parts = StringUtils.splitPreserveAllTokens(url, '/');

    if (parts == null || parts.length < 2) {
        return null;
    }

    String parameterValue = null;

    // Searching for the specified parameter name in url
    for (int i = 0; i < parts.length; i++) {
        if (parameterName.equals(parts[i])) {
            if (i < (parts.length - 1)) {
                // parameter name found, breaking loop
                parameterValue = parts[i + 1];
                break;
            }
        }
    }

    // Removing jsessionid
    parameterValue = removeJSessionId(parameterValue);

    return parameterValue;
}

From source file:com.xpn.xwiki.plugin.diff.DiffPlugin.java

/**
 * Return an html blocks representing word diffs between text1 and text2
 * //from w  w w .j  a  va 2  s  .  c om
 * @param text1 original content
 * @param text2 revised content
 * @return list of Delta objects
 */
public String getWordDifferencesAsHTML(String text1, String text2) throws XWikiException {
    text1 = "~~PLACEHOLDER~~" + text1 + "~~PLACEHOLDER~~";
    text2 = "~~PLACEHOLDER~~" + text2 + "~~PLACEHOLDER~~";

    StringBuffer html = new StringBuffer("<div class=\"diffmodifiedline\">");
    List list = getWordDifferencesAsList(text1, text2);
    String[] words = StringUtils.splitPreserveAllTokens(text1, ' ');
    int cursor = 0;
    boolean addSpace = false;

    for (int i = 0; i < list.size(); i++) {
        if (addSpace) {
            html.append(" ");
            addSpace = false;
        }

        Delta delta = (Delta) list.get(i);
        int position = delta.getOriginal().anchor();
        // First we fill in all text that has not been changed
        while (cursor < position) {
            html.append(escape(words[cursor]));
            html.append(" ");
            cursor++;
        }
        // Then we fill in what has been removed
        Chunk orig = delta.getOriginal();
        if (orig.size() > 0) {
            html.append("<span class=\"diffremoveword\">");
            List chunks = orig.chunk();
            for (int j = 0; j < chunks.size(); j++) {
                if (j > 0) {
                    html.append(" ");
                }
                html.append(escape((String) chunks.get(j)));
                cursor++;
            }
            html.append("</span>");
            addSpace = true;
        }

        // Then we fill in what has been added
        Chunk rev = delta.getRevised();
        if (rev.size() > 0) {
            html.append("<span class=\"diffaddword\">");
            List chunks = rev.chunk();
            for (int j = 0; j < chunks.size(); j++) {
                if (j > 0) {
                    html.append(" ");
                }
                html.append(escape((String) chunks.get(j)));
            }
            html.append("</span>");
            addSpace = true;
        }
    }

    // First we fill in all text that has not been changed
    while (cursor < words.length) {
        if (addSpace) {
            html.append(" ");
        }
        html.append(escape(words[cursor]));
        addSpace = true;
        cursor++;
    }

    html.append("</div>");
    return html.toString().replaceAll("~~PLACEHOLDER~~", "");
}

From source file:ch.cyberduck.core.irods.IRODSSession.java

protected String getRegion() {
    if (StringUtils.contains(host.getRegion(), ':')) {
        return StringUtils.splitPreserveAllTokens(host.getRegion(), ':')[0];
    }/*  w  w w .  java2 s  .c  om*/
    return host.getRegion();
}

From source file:ch.cyberduck.core.irods.IRODSSession.java

protected String getResource() {
    if (StringUtils.contains(host.getRegion(), ':')) {
        return StringUtils.splitPreserveAllTokens(host.getRegion(), ':')[1];
    }/*from  w  w  w.  java 2s .co  m*/
    return StringUtils.EMPTY;
}

From source file:com.viettel.util.doc.DocsUtility.java

public void replaceParagraph(String placeholder, String textToAdd) {
    // 1. get the paragraph
    List<Object> paragraphs = getAllElementFromObject(wordMLPackage.getMainDocumentPart(), P.class);

    P toReplace = null;/* w w w.ja  v a2s .  c  om*/
    for (Object p : paragraphs) {
        List<Object> texts = getAllElementFromObject(p, Text.class);
        for (Object t : texts) {
            Text content = (Text) t;
            if (content.getValue().equals(placeholder)) {
                toReplace = (P) p;
                break;
            }
        }
    }

    // we now have the paragraph that contains our placeholder: toReplace
    // 2. split into seperate lines
    String as[] = StringUtils.splitPreserveAllTokens(textToAdd, '\n');

    for (String ptext : as) {
        // 3. copy the found paragraph to keep styling correct
        P copy = (P) XmlUtils.deepCopy(toReplace);

        // replace the text elements from the copy
        List<?> texts = getAllElementFromObject(copy, Text.class);
        if (texts.size() > 0) {
            Text textToReplace = (Text) texts.get(0);
            textToReplace.setValue(ptext);
        }

        wordMLPackage.getMainDocumentPart().getContent().add(copy);
    }

    // 4. remove the original one
    ((ContentAccessor) toReplace.getParent()).getContent().remove(toReplace);

}

From source file:com.espe.distribuidas.pmaldito.servidorbdd.operaciones.Consultar.java

/**
 * metodo existe en recibe el codigo a buscar, la poscion en donde buscar y
 * el nombre de la tabla permite saber si existe o no el registro en
 * especial//from  w  w  w .  ja  va 2s . c  o  m
 *
 * @param codigo
 * @param posicion
 * @param tabla
 * @return
 */
@SuppressWarnings("ConvertToTryWithResources")
public boolean exiteEn(String codigo, Integer posicion, String tabla) {
    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
    Boolean validador = false;
    String string;
    String registro[];
    try {
        FileReader fr = new FileReader(tabla);
        BufferedReader br = new BufferedReader(fr);

        while ((string = br.readLine()) != null) {
            if (string.length() > 0) {
                registro = StringUtils.splitPreserveAllTokens(string, "|");
                System.out.println(registro.length);
                if (registro[posicion].equalsIgnoreCase(codigo)) {
                    validador = true;
                }
            } else {
                break;
            }
        }
        br.close();
    } catch (FileNotFoundException e) {
        System.err.println(e);
    } catch (IOException e1) {
        System.err.println(e1);
    }
    return validador;
}

From source file:com.qulice.checkstyle.CheckstyleValidator.java

/**
 * Create header content, from file./*from w  ww  .  j a  v  a  2s  .  c  o m*/
 * @param env The environment
 * @return The content of header
 * @see #configuration(Environment)
 */
private String header(final Environment env) {
    final String name = env.param("license", "LICENSE.txt");
    final URL url = CheckstyleValidator.toUrl(env, name);
    final String content;
    try {
        content = new Replaced(new Trimmed(new TextOf(url.openStream())), "[\\r\\n]+$", "").asString();
    } catch (final IOException ex) {
        throw new IllegalStateException("Failed to read license", ex);
    }
    final StringBuilder builder = new StringBuilder(Tv.HUNDRED);
    final String eol = System.getProperty("line.separator");
    builder.append("/*").append(eol);
    for (final String line : StringUtils.splitPreserveAllTokens(content, eol)) {
        builder.append(" *");
        if (!line.trim().isEmpty()) {
            builder.append(' ').append(line.trim());
        }
        builder.append(eol);
    }
    builder.append(" */");
    final String license = builder.toString();
    Logger.debug(this, "LICENSE found: %s", url);
    Logger.debug(this, "LICENSE full text after parsing:\n%s", license);
    return license;
}

From source file:de.bmarwell.j9kwsolver.util.ResponseUtils.java

/**
 * Parses the response for fields to set.
 * @param response the response sent by the server.
 * @return the CaptchaReturn Object with
 * information about the captcha assigned.
 *//*  w  w w.java2s  .  c  o m*/
private static CaptchaReturnExtended getExtendedFromResponse(final String response) {
    /* 
     * Extended response contains phrase keyword
     * ID|text|confirm|antwort|mouse=0|phrase=0|
     *     numeric=0|math=0|min_len=1|max_len=20|confirm=1|w|h|
     * e.g.
     * 11837102|text|||mouse=0|phrase=1|numeric=0|math=0|min_len=5|
     *     max_len=0|confirm=0|300|57|userstart=1387447122|
     *     startdate=1387447119|serverdate=1387447122|maxtimeout=35
     */
    RequestToURI.LOG.debug("Extended response: {}.", response);
    String[] splitresponse = StringUtils.splitPreserveAllTokens(response, '|');

    RequestToURI.LOG.debug("Splitresponse: {}.",
            ToStringBuilder.reflectionToString(splitresponse, ToStringStyle.MULTI_LINE_STYLE));

    /* Check item count */
    if (splitresponse.length < EXTENDED_ANSWER_MINLENGTH) {
        RequestToURI.LOG.warn("Extended response doesn't contain enough items");
        return null;
    }

    /* check first item is digits */
    if (!NumberUtils.isDigits(splitresponse[0])) {
        RequestToURI.LOG.error("Response's first item isn't a captcha id." + " Found {} instead.",
                splitresponse[0]);
        return null;
    }

    /* Now create captcha extended item and fill it */
    CaptchaReturnExtended cre = new CaptchaReturnExtended();
    cre.setCaptchaID(splitresponse[CaptchaReturn.Field.ID.getPosition()]);

    /* if text returned, set text */
    if (StringUtils.equals(splitresponse[CaptchaReturn.Field.TEXT.getPosition()], "text")) {
        RequestToURI.LOG.debug("Setting text captcha.");
        cre.setText(true);
    }

    /* Just confirm? */
    if (StringUtils.equals(splitresponse[CaptchaReturn.Field.CONFIRM.getPosition()], "text")) {
        cre.setConfirm(true);
    }

    /* Has solved text */
    if (StringUtils.isNotEmpty(splitresponse[CaptchaReturn.Field.CONFIRMTEXT.getPosition()])) {
        cre.setConfirmText(splitresponse[CaptchaReturn.Field.CONFIRMTEXT.getPosition()]);
    }

    /* Mouse event? */
    if (StringUtils.equals(splitresponse[CaptchaReturn.Field.MOUSE.getPosition()], "mouse=1")) {
        cre.setMouse(true);
    }

    // TODO: Add items

    return cre;
}