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

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

Introduction

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

Prototype

public static String getCommonPrefix(final String... strs) 

Source Link

Document

Compares all Strings in an array and returns the initial sequence of characters that is common to all of them.

For example, getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "

 StringUtils.getCommonPrefix(null) = "" StringUtils.getCommonPrefix(new String[] {}) = "" StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc" StringUtils.getCommonPrefix(new String[] {null, null}) = "" StringUtils.getCommonPrefix(new String[] {"", ""}) = "" StringUtils.getCommonPrefix(new String[] {"", null}) = "" StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = "" StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = "" StringUtils.getCommonPrefix(new String[] {"", "abc"}) = "" StringUtils.getCommonPrefix(new String[] {"abc", ""}) = "" StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc" StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a" StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab" StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab" StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = "" StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = "" StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a " 

Usage

From source file:kenh.expl.functions.GetCommonPrefix.java

public String process(String[] strs) {
    return StringUtils.getCommonPrefix(strs);
}

From source file:de.vandermeer.skb.datatool.commons.DataSet.java

/**
 * Returns the path common to all files in the given file list.
 * The rest (after this common path) will be used for auto-key-generation
 * @param fsl list of data files/*  w w w.jav a 2s  .c  o  m*/
 * @return common path of all files in the list
 */
String calcCommonPath(List<FileSource> fsl) {
    //get shortest absolute path, everything else is part of the key
    Set<String> paths = new HashSet<>();
    for (FileSource fs : fsl) {
        paths.add(fs.getAbsolutePath());
    }
    String ret = StringUtils.getCommonPrefix(paths.toArray(new String[] {}));
    if (ret.endsWith(File.separator)) {
        ret = StringUtils.substringBeforeLast(ret, File.separator);
    }
    return ret;
}

From source file:com.gdn.iam.spring.security.FortressDecisionVoter.java

private String getFilterUrl(HttpServletRequest request) {
    String commonString = null;/* www.j a  v a  2s  .  c om*/
    for (String url : permissionModels) {
        LOG.trace("url : {}", url);
        if (commonString == null) {
            LOG.trace("request uri contains url : {}", request.getRequestURI().contains(url));
            if (request.getRequestURI().contains(url)) {
                String registeredUrl = getApplicationBasePath() + url;
                LOG.trace("requested url : {}", request.getRequestURL().toString());
                LOG.trace("registered url : {}", registeredUrl);
                commonString = StringUtils
                        .getCommonPrefix(new String[] { request.getRequestURL().toString(), registeredUrl });
            }
        }
    }
    return commonString;
}

From source file:io.atomix.core.tree.DocumentPath.java

/**
 * Returns the path that points to the least common ancestor of the specified
 * collection of paths.//from   w w  w .  j av  a2  s.  c  o m
 *
 * @param paths collection of path
 * @return path to least common ancestor
 */
public static DocumentPath leastCommonAncestor(Collection<DocumentPath> paths) {
    if (paths.isEmpty()) {
        return null;
    }
    return DocumentPath.from(
            StringUtils.getCommonPrefix(paths.stream().map(DocumentPath::toString).toArray(String[]::new)));
}

From source file:airportApp.Query.java

/**
 * This method suggests the closest matching word and country code.
 * /*  www .  j a  va2 s  .  co m*/
 * The matching is done based on the longest common prefix. The method will 
 * work acceptably, if the user does not misspell the beginning of the 
 * country (i.e. it will work well with "zimb" = "Zimbabwe").
 * 
 * @param country User input for which a match will be returned.
 * @return Returns a Suggestion object (the closest match to the input 
 * argument and its associated country code) or null , if the match fails 
 * for any reason.
 */
private static Suggestion simpleSuggestCountry(String country) {

    Suggestion suggestion = null;
    String suggestionMatch = "";
    String suggestionCode = "";
    int longestCommonPrefix = -1;

    try {
        countriesReader = new BufferedReader(new FileReader("resources/countries.csv"));

        String line; // pointer (line reader) used with the countries

        countriesReader.readLine(); // skip first line (column names)

        while ((line = countriesReader.readLine()) != null) {

            Country c = Utils.readCountry(line);

            // use the longest common prefix of code name and country name
            int codePrefix = StringUtils
                    .getCommonPrefix(new String[] { country.toLowerCase(), c.getCode().toLowerCase() })
                    .length();
            int namePrefix = StringUtils
                    .getCommonPrefix(new String[] { country.toLowerCase(), c.getName().toLowerCase() })
                    .length();
            int lcp = ((codePrefix > namePrefix) ? codePrefix : namePrefix);

            // keep track of the associated match
            String match = ((codePrefix > namePrefix) ? c.getCode() : c.getName());

            // keep track of the associated country code
            String code = c.getCode();

            // for the first country just overwrite global values
            if (longestCommonPrefix == -1) {

                longestCommonPrefix = lcp;
                suggestionMatch = match;
                suggestionCode = code;
            } else { // for the rest use the global comaprison

                if (lcp > longestCommonPrefix) {

                    longestCommonPrefix = lcp;
                    suggestionMatch = match;
                    suggestionCode = code;
                }
            }

            suggestion = new Suggestion(suggestionMatch, suggestionCode);

        }

    } catch (IllegalArgumentException ex) {
        System.err.println("Error: " + ex.getMessage());
    } catch (FileNotFoundException ex) {
        System.err.println("Error: " + ex.getMessage());
    } catch (IOException ex) {
        System.err.println("Error: " + ex.getMessage());
    }

    return suggestion;
}

From source file:org.dswarm.common.model.util.AttributePathUtil.java

public static Optional<AttributePath> determineCommonAttributePath(final ContentSchema contentSchema) {

    if (contentSchema.getKeyAttributePaths() == null && contentSchema.getValueAttributePath() == null) {

        return Optional.absent();
    }/*w w w  .  j  a v  a 2s  .co m*/

    final Map<String, AttributePath> attributePaths = new HashMap<>();
    final Map<String, Attribute> attributes = new HashMap<>();

    if (contentSchema.getKeyAttributePaths() != null) {

        for (final AttributePath attributePath : contentSchema.getKeyAttributePaths()) {

            fillMaps(attributePath, attributePaths, attributes);
        }
    }

    if (contentSchema.getValueAttributePath() != null) {

        fillMaps(contentSchema.getValueAttributePath(), attributePaths, attributes);
    }

    final String commonPrefix = StringUtils
            .getCommonPrefix(attributePaths.keySet().toArray(new String[attributePaths.size()]));

    final String commonAttributePathString = cleanCommonPrefix(commonPrefix);

    if (attributePaths.containsKey(commonAttributePathString)) {

        return Optional.fromNullable(attributePaths.get(commonAttributePathString));
    }

    final String[] attributeURIs = commonAttributePathString.split(DMPStatics.ATTRIBUTE_DELIMITER.toString());

    final LinkedList<Attribute> apAttributes = new LinkedList<>();

    for (final String attributeURI : attributeURIs) {

        final Attribute attribute = attributes.get(attributeURI);
        apAttributes.add(attribute);
    }

    return Optional.of(new AttributePath(apAttributes));
}

From source file:org.jboss.qa.jenkins.test.executor.utils.unpack.UnPacker.java

protected static int countRootFolders(List<String> fileNames) {
    String prefix = StringUtils.getCommonPrefix(fileNames.toArray(new String[fileNames.size()]));
    if (!prefix.endsWith(File.separator)) {
        prefix = prefix.substring(0, prefix.lastIndexOf(File.separator) + 1);
    }/* w w  w  .  jav  a 2s. c om*/

    // The first found prefix can match only directory:
    // root/ (will be removed)
    // root/a (will be removed)
    // root/a/a/file.txt (root/a/ is the prefix)
    // root/abreak;/b/file.txt
    if (fileNames.remove(prefix)) {
        return countRootFolders(fileNames);
    }
    return StringUtils.countMatches(prefix, File.separator);
}

From source file:org.outofbits.sesame.schemagen.SchemaGeneration.java

/**
 * Tries to detect the common namespace of all subjects of the given vocabulary. If the root
 * resource is given, it will be ignored in the list for detection.
 *
 * @param rootResource the root resource of the vocabulary, or null if unknown.
 * @return detected the common namespace of all subjects of the given vocabulary or null, if
 * no commonalities can be detected.//from  w w  w . jav  a 2s. c  o  m
 */
private String detectBaseNamespace(Model vocabModel, Resource rootResource) {
    String baseNamespace = StringUtils
            .getCommonPrefix(vocabModel.subjects().stream().filter(resource -> !resource.equals(rootResource))
                    .map(Resource::stringValue).collect(Collectors.toList()).toArray(new String[0]));
    return !baseNamespace.isEmpty() ? baseNamespace : null;
}