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

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

Introduction

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

Prototype

public static int indexOfDifference(final CharSequence cs1, final CharSequence cs2) 

Source Link

Document

Compares two CharSequences, and returns the index at which the CharSequences begin to differ.

For example, indexOfDifference("i am a machine", "i am a robot") -> 7

 StringUtils.indexOfDifference(null, null) = -1 StringUtils.indexOfDifference("", "") = -1 StringUtils.indexOfDifference("", "abc") = 0 StringUtils.indexOfDifference("abc", "") = 0 StringUtils.indexOfDifference("abc", "abc") = -1 StringUtils.indexOfDifference("ab", "abxyz") = 2 StringUtils.indexOfDifference("abcde", "abxyz") = 2 StringUtils.indexOfDifference("abcde", "xyz") = 0 

Usage

From source file:c3.ops.priam.backup.AbstractBackupPath.java

/**
 * Given a date range, find a common string prefix Eg: 20120212, 20120213 =>
 * 2012021/*  ww w .j  av a  2  s  .  co m*/
 */
public String match(Date start, Date end) {
    String sString = formatDate(start);
    String eString = formatDate(end);
    int diff = StringUtils.indexOfDifference(sString, eString);
    if (diff < 0)
        return sString;
    return sString.substring(0, diff);
}

From source file:com.sunsprinter.diffunit.core.comparison.AbstractFileComparer.java

protected void assertEqual(final Collection<String> knownGoodLines, final String knownGoodPath,
        final InputLocationType knownGoodLocationType, final Collection<String> generatedLines,
        final File generatedFile) throws Exception {
    final String knownGoodFullPath;
    if (knownGoodLocationType == InputLocationType.CLASSPATH) {
        knownGoodFullPath = knownGoodPath;
    } else {//from w  ww . ja  v  a2  s. c  om
        knownGoodFullPath = new File(knownGoodPath).getAbsolutePath();
    }

    final StringBuilder errorBuilder = new StringBuilder();

    if (knownGoodLines.size() != generatedLines.size()) {
        errorBuilder
                .append(String.format(
                        "The number of lines is different.  The known good file has %d lines.  "
                                + "The generated file has %d lines.  ",
                        knownGoodLines.size(), generatedLines.size()));
    }

    int i = 1;
    String firstDifferenceMessage = null;
    final Iterator<String> knownGoodIterator = knownGoodLines.iterator();
    final Iterator<String> generatedIterator = generatedLines.iterator();
    while (firstDifferenceMessage == null && knownGoodIterator.hasNext() && generatedIterator.hasNext()) {
        final String knownGoodLine = knownGoodIterator.next();
        final String generatedLine = generatedIterator.next();
        if (!knownGoodLine.equals(generatedLine)) {
            firstDifferenceMessage = String.format(
                    "First difference detected at line number %d, position %d.\n\n" + "Known Good: %s\n"
                            + "Generated : %s\n",
                    i, StringUtils.indexOfDifference(knownGoodLine, generatedLine), knownGoodLine,
                    generatedLine);
        }
        i++;
    }
    if (firstDifferenceMessage != null) {
        errorBuilder.append(firstDifferenceMessage);
    }

    if (errorBuilder.length() != 0) {
        fail(String.format("Generated file %s does not match known good file %s.  %s",
                generatedFile.getAbsolutePath(), knownGoodFullPath, errorBuilder));
    }
}

From source file:org.eclipse.php.composer.test.ComposerCoreTestPlugin.java

/**
 * Compares expected result with the actual.
 * //  w w  w . ja  v a 2 s  .c  o m
 * @param expected
 * @param actual
 * @return difference string or <code>null</code> in case expected result is
 *         equal to the actual.
 */
public static String compareContents(String expected, String actual) {
    actual = actual.replaceAll("[\r\n]+", "\n").trim();
    expected = expected.replaceAll("[\r\n]+", "\n").trim();

    int expectedDiff = StringUtils.indexOfDifference(actual, expected);
    if (expectedDiff >= 0) {
        int actualDiff = StringUtils.indexOfDifference(expected, actual);
        return getDiffError(expected, actual, expectedDiff, actualDiff);
    }
    return null;
}

From source file:org.eclipse.php.composer.test.ComposerCoreTestPlugin.java

/**
 * Compares expected result with the actual ingoring whitespace characters
 * /* ww  w.  j  a v  a 2 s . c o m*/
 * @param expected
 * @param actual
 * @return difference string or <code>null</code> in case expected result is
 *         equal to the actual.
 */
public static String compareContentsIgnoreWhitespace(String expected, String actual) {
    String tmpExpected = expected;
    String tmpActual = actual;
    String diff = StringUtils.difference(tmpExpected, tmpActual);
    while (diff.length() > 0) {
        String diff2 = StringUtils.difference(tmpActual, tmpExpected);

        if (!Character.isWhitespace(diff.charAt(0)) && !Character.isWhitespace(diff2.charAt(0))) {
            int expectedDiff = StringUtils.indexOfDifference(tmpActual, tmpExpected)
                    + (expected.length() - tmpExpected.length());
            int actualDiff = StringUtils.indexOfDifference(tmpExpected, tmpActual)
                    + (actual.length() - tmpActual.length());
            return getDiffError(expected, actual, expectedDiff, actualDiff);
        }

        tmpActual = diff.trim();
        tmpExpected = diff2.trim();

        diff = StringUtils.difference(tmpExpected, tmpActual);
    }
    return null;
}

From source file:org.evosuite.regression.RegressionAssertionCounter.java

/** Calculate the number of different exceptions.
 * /*from w w  w. j a  v a  2s  . co m*/
 * @param originalExceptionMapping
 * @param regressionExceptionMapping
 * @return
 */
public static double compareExceptionDiffs(Map<Integer, Throwable> originalExceptionMapping,
        Map<Integer, Throwable> regressionExceptionMapping) {

    double exDiff = Math.abs((double) (originalExceptionMapping.size() - regressionExceptionMapping.size()));

    /*
     * If the number of exceptions is different, clearly the executions are
     * propagating to different results. Otherwise, we need to compare the
     * same assertions to make sure they're actually the same.
     */

    if (exDiff == 0) {
        // For all exceptions thrown original class
        for (Entry<Integer, Throwable> origException : originalExceptionMapping.entrySet()) {
            boolean skip = false;

            // Skip if the exception or the message are null
            // Sometimes the getMesage may call the CUT's exception handler which may crash
            try {
                if (origException.getValue() == null || origException.getValue().getMessage() == null) {
                    originalExceptionMapping.remove(origException.getKey());
                    skip = true;
                }
            } catch (Throwable t) {
                continue;
            }

            // See if exception throwing classes differed
            try {
                Throwable x = origException.getValue();
                Class<?> ex = getExceptionClassToUse(x);
                String sourceClass = RegressionAssertionCounter.getSourceClassName(x);
                if (sourceClass != null && isValidSource(sourceClass) && isExceptionToAssertThrownBy(ex)) {
                    // Get other exception throwing class and compare them
                    Throwable otherX = regressionExceptionMapping.get(origException.getKey());
                    String otherSourceClass = RegressionAssertionCounter.getSourceClassName(otherX);
                    if (sourceClass != otherSourceClass) {
                        exDiff++;
                        //logger.warn("Exception throwing classes differed: {} {}", sourceClass, otherSourceClass);
                    }

                }
            } catch (Throwable t) {
                // ignore
            }

            // Skip if the exceptions are not comparable
            try {
                if (regressionExceptionMapping.containsKey(origException.getKey())
                        && (regressionExceptionMapping.get(origException.getKey()) == null
                                || regressionExceptionMapping.get(origException.getKey())
                                        .getMessage() == null)) {
                    regressionExceptionMapping.remove(origException.getKey());
                    skip = true;
                }
            } catch (Throwable t) {
                continue;
            }

            // If they start differing from @objectID skip this one
            if (!skip && regressionExceptionMapping.get(origException.getKey()) != null) {
                String origExceptionMessage = origException.getValue().getMessage();
                String regExceptionMessage = regressionExceptionMapping.get(origException.getKey())
                        .getMessage();
                int diffIndex = StringUtils.indexOfDifference(origExceptionMessage, regExceptionMessage);
                if (diffIndex > 0) {
                    if (origExceptionMessage.charAt(diffIndex - 1) == '@') {
                        originalExceptionMapping.remove(origException.getKey());
                        regressionExceptionMapping.remove(origException.getKey());
                        skip = true;
                    } else {
                        // If @ is in the last 10 characters, it's likely an object pointer comparison issue
                        int howFarBack = 10;
                        if (diffIndex > howFarBack) {
                            String last10 = origExceptionMessage.substring(diffIndex - howFarBack, diffIndex);
                            if (last10.contains("@")) {
                                originalExceptionMapping.remove(origException.getKey());
                                regressionExceptionMapping.remove(origException.getKey());
                                skip = true;
                            }
                        }
                    }

                }
            }

            // ignore security manager exceptions
            if (!skip && origException.getValue().getMessage().contains("Security manager blocks")) {
                originalExceptionMapping.remove(origException.getKey());
                regressionExceptionMapping.remove(origException.getKey());
                skip = true;
            }

            if (skip)
                continue;

            // do the comparison
            if (!regressionExceptionMapping.containsKey(origException.getKey()) || (!regressionExceptionMapping
                    .get(origException.getKey()).getMessage().equals(origException.getValue().getMessage()))) {
                exDiff++;
            }
        }
        // For all exceptions in the regression class.
        // Any bad exceptions were removed from this object earlier
        for (Entry<Integer, Throwable> regException : regressionExceptionMapping.entrySet()) {
            if (!originalExceptionMapping.containsKey(regException.getKey()))
                exDiff++;
        }
    }

    return exDiff;
}

From source file:org.evosuite.regression.RegressionExceptionHelper.java

/**
 * Calculate the number of different exceptions, given two sets of exceptions.
 *//* ww w. ja  va  2  s.c o  m*/
public static int compareExceptionDiffs(Map<Integer, Throwable> originalExceptionMapping,
        Map<Integer, Throwable> regressionExceptionMapping) {

    int exDiff = (int) Math.abs((originalExceptionMapping.size() - regressionExceptionMapping.size()));

    /*
     * If the number of exceptions is different, clearly the executions are
     * propagating to different results. Otherwise, we need to compare the
     * same assertions to make sure they're actually the same.
     */

    if (exDiff == 0) {
        // For all exceptions thrown original class
        for (Map.Entry<Integer, Throwable> origException : originalExceptionMapping.entrySet()) {
            boolean skip = false;

            // Skip if the exception or the message are null
            // Sometimes the getMesage may call the CUT's exception handler which may crash
            try {
                if (origException.getValue() == null || origException.getValue().getMessage() == null) {
                    originalExceptionMapping.remove(origException.getKey());
                    skip = true;
                }
            } catch (Throwable t) {
                continue;
            }

            // See if exception throwing classes differed
            try {
                Throwable x = origException.getValue();
                Class<?> ex = getExceptionClassToUse(x);
                String sourceClass = getSourceClassName(x);
                if (sourceClass != null && isValidSource(sourceClass) && isExceptionToAssertValid(ex)) {
                    // Get other exception throwing class and compare them
                    Throwable otherX = regressionExceptionMapping.get(origException.getKey());
                    String otherSourceClass = getSourceClassName(otherX);
                    if (!sourceClass.equals(otherSourceClass)) {
                        exDiff++;
                        //logger.warn("Exception throwing classes differed: {} {}", sourceClass, otherSourceClass);
                    }

                }
            } catch (Throwable t) {
                // ignore
            }

            // Skip if the exceptions are not comparable
            try {
                if (regressionExceptionMapping.containsKey(origException.getKey())
                        && (regressionExceptionMapping.get(origException.getKey()) == null
                                || regressionExceptionMapping.get(origException.getKey())
                                        .getMessage() == null)) {
                    regressionExceptionMapping.remove(origException.getKey());
                    skip = true;
                }
            } catch (Throwable t) {
                continue;
            }

            // If they start differing from @objectID skip this one
            if (!skip && regressionExceptionMapping.get(origException.getKey()) != null) {
                String origExceptionMessage = origException.getValue().getMessage();
                String regExceptionMessage = regressionExceptionMapping.get(origException.getKey())
                        .getMessage();
                int diffIndex = StringUtils.indexOfDifference(origExceptionMessage, regExceptionMessage);
                if (diffIndex > 0) {
                    if (origExceptionMessage.charAt(diffIndex - 1) == '@') {
                        originalExceptionMapping.remove(origException.getKey());
                        regressionExceptionMapping.remove(origException.getKey());
                        skip = true;
                    } else {
                        // If @ is in the last 10 characters, it's likely an object pointer comparison issue
                        int howFarBack = 10;
                        if (diffIndex > howFarBack) {
                            String last10 = origExceptionMessage.substring(diffIndex - howFarBack, diffIndex);
                            if (last10.contains("@")) {
                                originalExceptionMapping.remove(origException.getKey());
                                regressionExceptionMapping.remove(origException.getKey());
                                skip = true;
                            }
                        }
                    }

                }
            }

            // ignore security manager exceptions
            if (!skip && origException.getValue().getMessage().contains("Security manager blocks")) {
                originalExceptionMapping.remove(origException.getKey());
                regressionExceptionMapping.remove(origException.getKey());
                skip = true;
            }

            if (skip) {
                continue;
            }

            // do the comparison
            if (!regressionExceptionMapping.containsKey(origException.getKey()) || (!regressionExceptionMapping
                    .get(origException.getKey()).getMessage().equals(origException.getValue().getMessage()))) {
                exDiff++;
            }
        }
        // For all exceptions in the regression class.
        // Any bad exceptions were removed from this object earlier
        for (Map.Entry<Integer, Throwable> regException : regressionExceptionMapping.entrySet()) {
            if (!originalExceptionMapping.containsKey(regException.getKey())) {
                exDiff++;
            }
        }
    }

    return exDiff;
}

From source file:org.voltdb.catalog.CatalogDiffEngine.java

/**
 * Pre-order walk of catalog generating add, delete and set commands
 * that compose that full difference.//from   w  w  w.  ja v  a2s  .c o  m
 * @param prevType
 * @param newType
 */
private void diffRecursively(CatalogType prevType, CatalogType newType) {
    assert (prevType != null) : "Null previous object found in catalog diff traversal.";
    assert (newType != null) : "Null new object found in catalog diff traversal";

    Object materializerValue = null;
    // Consider shifting into the strict more required within materialized view definitions.
    if (prevType instanceof Table) {
        // Under normal circumstances, it's highly unpossible that another (nested?) table will
        // appear in the details of a materialized view table. So, when it does (!?), be sure to
        // complain -- and don't let it throw off the accounting of the strict diff mode.
        // That is, don't set the local "materializerValue".
        if (m_inStrictMatViewDiffMode) {
            // Maybe this should log or append to m_errors?
            System.out.println("ERROR: unexpected nesting of a Table in CatalogDiffEngine.");
        } else {
            materializerValue = prevType.getField("materializer");
            if (materializerValue != null) {
                // This table is a materialized view, so the changes to it and its children are
                // strictly limited, e.g. no adding/dropping columns.
                // In a future development, such changes may be allowed, but they may be implemented
                // differently (get different catalog commands), such as through a wholesale drop/add
                // of the entire view and materialized table definitions.
                // The non-null local "materializerValue" is a reminder to pop out of this mode
                // before returning from this level of the recursion.
                m_inStrictMatViewDiffMode = true;
                if (m_triggeredVerbosity) {
                    System.out.println("DEBUG VERBOSE diffRecursively entering strict mat view mode");
                }
            }
        }
    }

    // diff local fields
    for (String field : prevType.getFields()) {
        // this field is (or was) set at runtime, so ignore it for diff purposes
        if (field.equals("isUp")) {
            continue;
        }

        boolean verbosityTriggeredHere = false;
        if ((!m_triggeredVerbosity) && field.equals(m_triggerForVerbosity)) {
            System.out.println(
                    "DEBUG VERBOSE diffRecursively verbosity (triggered by field '" + field + "' is ON");
            verbosityTriggeredHere = true;
            m_triggeredVerbosity = true;
        }
        // check if the types are different
        // options are: both null => same
        //              one null and one not => different
        //              both not null => check Object.equals()
        Object prevValue = prevType.getField(field);
        Object newValue = newType.getField(field);
        if ((prevValue == null) != (newValue == null)) {
            if (m_triggeredVerbosity) {
                if (prevValue == null) {
                    System.out.println("DEBUG VERBOSE diffRecursively found new '" + field + "' only.");
                } else {
                    System.out.println("DEBUG VERBOSE diffRecursively found prev '" + field + "' only.");
                }
            }
            writeModification(newType, prevType, field);
        }
        // if they're both not null (above/below ifs implies this)
        else if (prevValue != null) {
            // if comparing CatalogTypes (both must be same)
            if (prevValue instanceof CatalogType) {
                assert (newValue instanceof CatalogType);
                String prevPath = ((CatalogType) prevValue).getCatalogPath();
                String newPath = ((CatalogType) newValue).getCatalogPath();
                if (prevPath.compareTo(newPath) != 0) {
                    if (m_triggeredVerbosity) {
                        int padWidth = StringUtils.indexOfDifference(prevPath, newPath);
                        String pad = StringUtils.repeat(" ", padWidth);
                        System.out.println(
                                "DEBUG VERBOSE diffRecursively found a path change to '" + field + "':");
                        System.out.println("DEBUG VERBOSE prevPath=" + prevPath);
                        System.out.println("DEBUG VERBOSE diff at->" + pad + "^ position:" + padWidth);
                        System.out.println("DEBUG VERBOSE  newPath=" + newPath);
                    }
                    writeModification(newType, prevType, field);
                }
            }
            // if scalar types
            else {
                if (prevValue.equals(newValue) == false) {
                    if (m_triggeredVerbosity) {
                        System.out.println(
                                "DEBUG VERBOSE diffRecursively found a scalar change to '" + field + "':");
                        System.out.println("DEBUG VERBOSE diffRecursively prev:" + prevValue);
                        System.out.println("DEBUG VERBOSE diffRecursively new :" + newValue);
                    }
                    writeModification(newType, prevType, field);
                }
            }
        }
        if (verbosityTriggeredHere) {
            System.out.println("DEBUG VERBOSE diffRecursively verbosity is OFF");
            m_triggeredVerbosity = false;
        }
    }

    // recurse
    for (String field : prevType.getChildCollections()) {
        boolean verbosityTriggeredHere = false;
        if (field.equals(m_triggerForVerbosity)) {
            System.out.println("DEBUG VERBOSE diffRecursively verbosity ON");
            m_triggeredVerbosity = true;
            verbosityTriggeredHere = true;
        }
        CatalogMap<? extends CatalogType> prevMap = prevType.getCollection(field);
        CatalogMap<? extends CatalogType> newMap = newType.getCollection(field);
        getCommandsToDiff(field, prevMap, newMap);
        if (verbosityTriggeredHere) {
            System.out.println("DEBUG VERBOSE diffRecursively verbosity OFF");
            m_triggeredVerbosity = false;
        }
    }

    if (materializerValue != null) {
        // Just getting back from recursing into a materialized view table,
        // so drop the strictness required only in that context.
        // It's safe to assume that the prior mode to which this must pop back is the non-strict
        // mode because nesting of table definitions is unpossible AND we guarded against its
        // potential side effects, above, anyway.
        m_inStrictMatViewDiffMode = false;
    }

}

From source file:uk.ac.ebi.eva.pipeline.io.mappers.VariantVcfFactory.java

/**
 * Calculates the normalized start, end, reference and alternate of a variant where the
 * reference and the alternate are not identical.
 * <p>/*  w w w . j av a 2s  .  c o  m*/
 * This task comprises 2 steps: removing the trailing bases that are
 * identical in both alleles, then the leading identical bases.
 * <p>
 * It is left aligned because the traling bases are removed before the leading ones, implying a normalization where
 * the position is moved the least possible from its original location.
 * @param chromosome needed for error reporting and logging
 * @param position Input starting position
 * @param reference Input reference allele
 * @param alternate Input alternate allele
 * @return The new start, end, reference and alternate alleles wrapped in a VariantKeyFields
 */
protected VariantKeyFields normalizeLeftAlign(String chromosome, int position, String reference,
        String alternate) throws NotAVariantException {
    if (reference.equals(alternate)) {
        throw new NotAVariantException("One alternate allele is identical to the reference. Variant found as: "
                + chromosome + ":" + position + ":" + reference + ">" + alternate);
    }

    // Remove the trailing bases
    String refReversed = StringUtils.reverse(reference);
    String altReversed = StringUtils.reverse(alternate);
    int indexOfDifference = StringUtils.indexOfDifference(refReversed, altReversed);
    reference = StringUtils.reverse(refReversed.substring(indexOfDifference));
    alternate = StringUtils.reverse(altReversed.substring(indexOfDifference));

    // Remove the leading bases
    indexOfDifference = StringUtils.indexOfDifference(reference, alternate);
    int start = position + indexOfDifference;
    int length = max(reference.length(), alternate.length());
    int end = position + length - 1; // -1 because end is inclusive
    if (indexOfDifference > 0) {
        reference = reference.substring(indexOfDifference);
        alternate = alternate.substring(indexOfDifference);
    }
    return new VariantKeyFields(start, end, reference, alternate);
}