Example usage for com.google.common.base Strings commonPrefix

List of usage examples for com.google.common.base Strings commonPrefix

Introduction

In this page you can find the example usage for com.google.common.base Strings commonPrefix.

Prototype

public static String commonPrefix(CharSequence a, CharSequence b) 

Source Link

Document

Returns the longest string prefix such that a.toString().startsWith(prefix) && b.toString().startsWith(prefix) , taking care not to split surrogate pairs.

Usage

From source file:org.wisdom.source.ast.model.PathComparator.java

/**
 * /foo < /foo/ < /foo/bar < /fooa
 *
 * @param o1// w ww.  ja va2s.  c  o  m
 * @param o2
 * @return
 */
@Override
public int compare(String o1, String o2) {

    if (o1.equals(o2)) {
        return 0;
    }

    String prefix = Strings.commonPrefix(o1, o2);
    if (prefix.length() == 0) {
        // No common prefix
        return o1.compareTo(o2);
    }

    if (o1.length() == prefix.length()) {
        return -1;
    }

    return o1.compareTo(o2);

}

From source file:com.cloudera.science.avro.streaming.AvroAsJSONInputFormat.java

@Override
public RecordReader<Text, Text> getRecordReader(InputSplit split, JobConf job, Reporter reporter)
        throws IOException {
    if (schemas == null) {
        loadSchemas(job);//from   ww w .j a  v a2 s .  c  o  m
    }
    FileSplit fs = (FileSplit) split;
    Schema schema = null;
    if (schemas.size() == 1) {
        schema = schemas.get(0);
    } else {
        // Need to figure out which schema we're loading
        String current = fs.getPath().toString();
        int index = -1;
        int bestMatchLength = -1;
        for (int i = 0; i < inputPaths.length; i++) {
            int match = Strings.commonPrefix(current, inputPaths[i]).length();
            if (match > bestMatchLength) {
                bestMatchLength = match;
                index = i;
            }
        }
        schema = schemas.get(index);
    }
    return new AvroAsJSONRecordReader(schema, job, fs);
}

From source file:com.android.tools.idea.npw.importing.ImportUIUtil.java

/**
 * Returns a relative path string to be shown in the UI. Wizard logic
 * operates with VirtualFile's so these paths are only for user. The paths
 * shown are relative to the file system location user specified, showing
 * relative paths will be easier for the user to read.
 */// ww w  .j  ava  2 s  . c  o m
static String getRelativePath(@Nullable VirtualFile baseFile, @Nullable VirtualFile file) {
    if (file == null) {
        return "";
    }
    String path = file.getPath();
    if (baseFile == null) {
        return path;
    } else if (file.equals(baseFile)) {
        return ".";
    } else if (!baseFile.isDirectory()) {
        return getRelativePath(baseFile.getParent(), file);
    } else {
        String basePath = baseFile.getPath();
        if (path.startsWith(basePath + "/")) {
            return path.substring(basePath.length() + 1);
        } else if (file.getFileSystem().equals(baseFile.getFileSystem())) {
            StringBuilder builder = new StringBuilder(basePath.length());
            String prefix = Strings.commonPrefix(path, basePath);
            if (!prefix.endsWith("/")) {
                prefix = prefix.substring(0, prefix.lastIndexOf("/") + 1);
            }
            if (!path.startsWith(basePath)) {
                Iterable<String> segments = Splitter.on("/").split(basePath.substring(prefix.length()));
                Joiner.on("/").appendTo(builder, Iterables.transform(segments, Functions.constant("..")));
                builder.append("/");
            }
            builder.append(path.substring(prefix.length()));
            return builder.toString();
        } else {
            return path;
        }
    }
}

From source file:org.diqube.loader.compression.CompressedStringDictionaryBuilder.java

/**
 * Build the dictionary./*from  w w  w.  jav a 2  s .com*/
 * 
 * @return {@link Pair} containing the new {@link StringDictionary} and an ID change map (maps from temporary ID that
 *         was provided in {@link #fromEntityMap(Map)} to the final ID assigned in the resulting dict).
 */
public Pair<StringDictionary<?>, Map<Long, Long>> build() {
    SortedSet<String> keys = (SortedSet<String>) entityMap.keySet();

    Map<Long, Long> idMap = new HashMap<>();
    long newId = 0;
    for (String key : keys) {
        long curId = newId++;
        if (entityMap.get(key) != curId)
            idMap.put(entityMap.get(key), curId);
    }

    ConstructionParentNode root = new ConstructionParentNode();
    ConstructionParentNode curNode = root;
    String curNodePrefix = "";

    newId = 0;
    // note that the keys are traversed in sorted order already!
    for (String stringValue : keys) {

        // go up the current tree until our prefix matches, this might go up as far as the root node!
        while (!stringValue.startsWith(curNodePrefix)) {
            curNodePrefix = curNodePrefix.substring(0,
                    curNodePrefix.length() - curNode.getParentToThisStringLength());
            curNode = curNode.getParent();
        }

        String remaining = stringValue.substring(curNodePrefix.length(), stringValue.length()).intern();

        // check if there is a key that has a common prefix with our key. Note that there can be only one such key! See
        // class comment of TrieStringDictionary for why this is true.
        List<String> possiblyInterestingKeys = new LinkedList<>();
        possiblyInterestingKeys.add(curNode.getChildTerminals().floorKey(remaining));
        possiblyInterestingKeys.add(curNode.getChildTerminals().ceilingKey(remaining));
        possiblyInterestingKeys.add(curNode.getChildNodes().floorKey(remaining));
        possiblyInterestingKeys.add(curNode.getChildNodes().ceilingKey(remaining));
        String interestingKey = null;
        String interestingCommonPrefix = null;
        for (String possiblyInterestingKey : possiblyInterestingKeys) {
            if (possiblyInterestingKey == null || possiblyInterestingKey.equals(""))
                // ignore the empty-string-terminal nodes - they will not match our new string.
                continue;

            String tmp = Strings.commonPrefix(possiblyInterestingKey, remaining);
            if (!"".equals(tmp)) {
                interestingKey = possiblyInterestingKey;
                interestingCommonPrefix = tmp.intern();
                break;
            }
        }

        if (interestingKey != null) {
            // we found an entry with a common prefix - create new parent node and move the old node there and our new
            // string, too.
            ConstructionParentNode newParent = new ConstructionParentNode();
            newParent.setParent(curNode);
            newParent.setParentToThisStringLength(interestingCommonPrefix.length());
            newParent.getChildTerminals().put(removePrefix(remaining, interestingCommonPrefix),
                    new TerminalNode(newId++));

            if (curNode.getChildNodes().containsKey(interestingKey)) {
                ConstructionParentNode nodeToMove = curNode.getChildNodes().get(interestingKey);
                nodeToMove.setParentToThisStringLength(
                        nodeToMove.getParentToThisStringLength() - interestingCommonPrefix.length());
                newParent.getChildNodes().put(removePrefix(interestingKey, interestingCommonPrefix),
                        nodeToMove);
                curNode.getChildNodes().remove(interestingKey);
            } else {
                // curNode.getChildTerminals().containsKey(interestingKey)
                newParent.getChildTerminals().put(removePrefix(interestingKey, interestingCommonPrefix),
                        curNode.getChildTerminals().get(interestingKey));
                curNode.getChildTerminals().remove(interestingKey);
            }

            curNode.getChildNodes().put(interestingCommonPrefix, newParent);

            // continue working in the new parent.
            curNode = newParent;
            curNodePrefix += interestingCommonPrefix;
        } else {
            // there was no node with a common prefix. add a new terminal node!
            curNode.getChildTerminals().put(remaining, new TerminalNode(newId++));
        }
    }

    TrieStringDictionary res = new TrieStringDictionary(root.constructFinalNode(), entityMap.firstKey(),
            entityMap.lastKey(), entityMap.size() - 1);
    return new Pair<>(res, idMap);
}

From source file:tech.tablesaw.columns.strings.StringMapFunctions.java

default StringColumn commonPrefix(Column<?> column2) {

    StringColumn newColumn = StringColumn.create(name() + column2.name() + "[prefix]");

    for (int r = 0; r < size(); r++) {
        String value1 = getString(r);
        String value2 = column2.getString(r);
        newColumn.append(Strings.commonPrefix(value1, value2));
    }//  w  w  w  .  j  a va2s .  c  om
    return newColumn;
}

From source file:annis.gui.SearchUI.java

private void checkServiceVersion() {
    try {/*  w  w w  . j a  va 2s .c  o  m*/
        WebResource resRelease = Helper.getAnnisWebResource().path("version").path("release");
        String releaseService = resRelease.get(String.class);
        String releaseGUI = VersionInfo.getReleaseName();

        // check if the release version differs and show a big warning
        if (!releaseGUI.equals(releaseService)) {
            Notification.show("Different service version",
                    "The service uses version " + releaseService + " but the user interface is using version  "
                            + releaseGUI + ". This can produce unwanted errors.",
                    Notification.Type.WARNING_MESSAGE);
        } else {
            // show a smaller warning if the revisions are not the same
            WebResource resRevision = Helper.getAnnisWebResource().path("version").path("revision");
            String revisionService = resRevision.get(String.class);
            String revisionGUI = VersionInfo.getBuildRevision();

            if (!revisionService.equals(revisionGUI)) {
                // shorten the strings
                String commonPrefix = Strings.commonPrefix(revisionService, revisionGUI);
                int outputLength = Math.max(6, commonPrefix.length() + 2);
                String revisionServiceShort = revisionService.substring(0,
                        Math.min(revisionService.length() - 1, outputLength));
                String revisionGUIShort = revisionGUI.substring(0,
                        Math.min(revisionGUI.length() - 1, outputLength));

                Notification n = new Notification("Different service revision",
                        "The service uses revision <code title=\"" + revisionGUI + "\">" + revisionServiceShort
                                + "</code> but the user interface is using revision  <code title=\""
                                + revisionGUI + "\">" + revisionGUIShort + "</code>.",
                        Notification.Type.TRAY_NOTIFICATION);
                n.setHtmlContentAllowed(true);
                n.setDelayMsec(3000);
                n.show(Page.getCurrent());
            }
        }
    } catch (UniformInterfaceException ex) {
        log.warn("Could not get the version of the service", ex);
    } catch (ClientHandlerException ex) {
        log.warn("Could not get the version of the service because service is not running", ex);
    }
}

From source file:org.sosy_lab.cpachecker.cfa.parser.eclipse.c.EclipseCParser.java

/**
 * Given a file name, this function returns a "nice" representation of it.
 * This should be used for situations where the name is going
 * to be presented to the user.//from w ww . ja  v a  2s  .c  om
 * The result may be the empty string, if for example CPAchecker only uses
 * one file (we expect the user to know its name in this case).
 */
private Function<String, String> createNiceFileNameFunction(List<IASTTranslationUnit> asts) {
    Iterator<String> fileNames = Lists.transform(asts, new Function<IASTTranslationUnit, String>() {
        @Override
        public String apply(IASTTranslationUnit pInput) {
            return pInput.getFilePath();
        }
    }).iterator();

    if (asts.size() == 1) {
        final String mainFileName = fileNames.next();
        return new Function<String, String>() {
            @Override
            public String apply(String pInput) {
                return mainFileName.equals(pInput) ? "" // no file name necessary for main file if there is only one
                        : pInput;
            }
        };

    } else {
        String commonStringPrefix = fileNames.next();
        while (fileNames.hasNext()) {
            commonStringPrefix = Strings.commonPrefix(commonStringPrefix, fileNames.next());
        }

        final String commonPathPrefix;
        int pos = commonStringPrefix.lastIndexOf(File.separator);
        if (pos < 0) {
            commonPathPrefix = commonStringPrefix;
        } else {
            commonPathPrefix = commonStringPrefix.substring(0, pos + 1);
        }

        return new Function<String, String>() {
            @Override
            public String apply(String pInput) {
                if (pInput.isEmpty()) {
                    return pInput;
                }
                if (pInput.charAt(0) == '"' && pInput.charAt(pInput.length() - 1) == '"') {
                    pInput = pInput.substring(1, pInput.length() - 1);
                }
                if (pInput.startsWith(commonPathPrefix)) {
                    return pInput.substring(commonPathPrefix.length()).intern();
                } else {
                    return pInput.intern();
                }
            }
        };
    }
}