Java Code Examples for java.util.SortedSet.isEmpty()

The following are Jave code examples for showing how to use isEmpty() of the java.util.SortedSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ditb   File: IntegrationTestLoadAndVerify.java   View Source Code Vote up 6 votes
private int doSearch(Configuration conf, String keysDir) throws Exception {
  Path inputDir = new Path(keysDir);

  getConf().set(SEARCHER_INPUTDIR_KEY, inputDir.toString());
  SortedSet<byte []> keys = readKeysToSearch(getConf());
  if (keys.isEmpty()) throw new RuntimeException("No keys to find");
  LOG.info("Count of keys to find: " + keys.size());
  for(byte [] key: keys)  LOG.info("Key: " + Bytes.toStringBinary(key));
  Path hbaseDir = new Path(getConf().get(HConstants.HBASE_DIR));
  // Now read all WALs. In two dirs. Presumes certain layout.
  Path walsDir = new Path(hbaseDir, HConstants.HREGION_LOGDIR_NAME);
  Path oldWalsDir = new Path(hbaseDir, HConstants.HREGION_OLDLOGDIR_NAME);
  LOG.info("Running Search with keys inputDir=" + inputDir +
    " against " + getConf().get(HConstants.HBASE_DIR));
  int ret = ToolRunner.run(new WALSearcher(getConf()), new String [] {walsDir.toString(), ""});
  if (ret != 0) return ret;
  return ToolRunner.run(new WALSearcher(getConf()), new String [] {oldWalsDir.toString(), ""});
}
 
Example 2
Project: guava-mock   File: SetGenerators.java   View Source Code Vote up 6 votes
@Override
protected SortedSet<Integer> create(Integer[] elements) {
  SortedSet<Integer> set = nullCheckedTreeSet(elements);
  if (set.isEmpty()) {
    /*
     * The (tooLow + 1, tooHigh) arguments below would be invalid because tooLow would be
     * greater than tooHigh.
     */
    return ContiguousSet.create(Range.openClosed(0, 1), DiscreteDomain.integers()).subSet(0, 1);
  }
  int tooHigh = set.last() + 1;
  int tooLow = set.first() - 1;
  set.add(tooHigh);
  set.add(tooLow);
  return checkedCreate(set).subSet(tooLow + 1, tooHigh);
}
 
Example 3
Project: openjdk-jdk10   File: SerializedFormBuilder.java   View Source Code Vote up 6 votes
/**
 * Build the package serialized form for the current package being processed.
 *
 * @param serializedSummariesTree content tree to which the documentation will be added
 * @throws DocletException if there is a problem while building the documentation
 */
protected void buildPackageSerializedForm(Content serializedSummariesTree) throws DocletException {
    Content packageSerializedTree = writer.getPackageSerializedHeader();
    SortedSet<TypeElement> classes = utils.getAllClassesUnfiltered(currentPackage);
    if (classes.isEmpty()) {
        return;
    }
    if (!serialInclude(utils, currentPackage)) {
        return;
    }
    if (!serialClassFoundToDocument(classes)) {
        return;
    }

    buildPackageHeader(packageSerializedTree);
    buildClassSerializedForm(packageSerializedTree);

    writer.addPackageSerializedTree(serializedSummariesTree, packageSerializedTree);
}
 
Example 4
Project: parabuild-ci   File: ExternalClass.java   View Source Code Vote up 6 votes
public IMethod getMostCompatibleMethod(String name, ISignature signature) {
  IMethod result = null;

  SortedSet compatibleMethods
    = new TreeSet(new MethodSpecificityComparator());

  Iterator it = getMethods().iterator();
  while (it.hasNext()) {
    IMethod method = (IMethod)it.next();
    if ( name.equals( method.getName() ) ) {
      if ( method.hasCompatibleSignature( signature ) ) {
        compatibleMethods.add(method);
      }
    }
  }

  if (!compatibleMethods.isEmpty()) {
    result = (IMethod)compatibleMethods.first();
  }

  return result;
}
 
Example 5
Project: elasticsearch_my   File: OldIndexBackwardsCompatibilityIT.java   View Source Code Vote up 6 votes
public void testAllVersionsTested() throws Exception {
    SortedSet<String> expectedVersions = new TreeSet<>();
    for (Version v : VersionUtils.allReleasedVersions()) {
        if (VersionUtils.isSnapshot(v)) continue;  // snapshots are unreleased, so there is no backcompat yet
        if (v.isRelease() == false) continue; // no guarantees for prereleases
        if (v.before(Version.CURRENT.minimumIndexCompatibilityVersion())) continue; // we can only support one major version backward
        if (v.equals(Version.CURRENT)) continue; // the current version is always compatible with itself
        expectedVersions.add("index-" + v.toString() + ".zip");
    }

    for (String index : indexes) {
        if (expectedVersions.remove(index) == false) {
            logger.warn("Old indexes tests contain extra index: {}", index);
        }
    }
    if (expectedVersions.isEmpty() == false) {
        StringBuilder msg = new StringBuilder("Old index tests are missing indexes:");
        for (String expected : expectedVersions) {
            msg.append("\n" + expected);
        }
        fail(msg.toString());
    }
}
 
Example 6
Project: s-store   File: CollectionUtil.java   View Source Code Vote up 6 votes
/**
 * Return the ith element of a set. Super lame
 * 
 * @param <T>
 * @param items
 * @param idx
 * @return
 */
public static <T> T get(Iterable<T> items, int idx) {
    if (items == null) {
        return (null);
    }
    else if (items instanceof List<?>) {
        return ((List<T>) items).get(idx);
    }
    else if (items instanceof ListOrderedSet<?>) {
        return ((ListOrderedSet<T>) items).get(idx);
    }
    else if (items instanceof SortedSet<?> && idx == 0) {
        SortedSet<T> set = (SortedSet<T>)items;
        return (set.isEmpty() ? null : set.first());
    }
    int ctr = 0;
    for (T t : items) {
        if (ctr++ == idx) return (t);
    }
    return (null);
}
 
Example 7
Project: vexillo   File: EncodingNode.java   View Source Code Vote up 6 votes
public EncodingNode(String[] ids, CodeSequence[] seqs) {
	SortedSet<String> idSet = new TreeSet<String>();
	SortedSet<String> nidSet = new TreeSet<String>();
	for (int i = 0; i < ids.length; i++) {
		String nid = ids[i].toLowerCase().replaceAll("[^a-z0-9]+", "");
		if (ids[i].length() > 0 && nid.length() > 0) {
			if (idSet.contains(ids[i])) throw new IllegalArgumentException("Duplicate id: " + ids[i]);
			if (nidSet.contains(nid)) throw new IllegalArgumentException("Duplicate id:" + nid);
			idSet.add(ids[i]);
			nidSet.add(nid);
		}
	}
	if (idSet.isEmpty() || nidSet.isEmpty()) throw new IllegalArgumentException("No ids");
	this.ids = idSet.toArray(new String[idSet.size()]);
	this.nids = nidSet.toArray(new String[nidSet.size()]);
	SortedSet<CodeSequence> seqSet = new TreeSet<CodeSequence>();
	for (int i = 0; i < seqs.length; i++) {
		if (seqs[i].length() > 0) {
			if (seqSet.contains(seqs[i])) throw new IllegalArgumentException("Duplicate code sequence: " + seqs[i]);
			seqSet.add(seqs[i]);
		}
	}
	if (seqSet.isEmpty()) throw new IllegalArgumentException("No code sequences");
	this.seqs = seqSet.toArray(new CodeSequence[seqSet.size()]);
}
 
Example 8
Project: openjdk-jdk10   File: PackageSummaryBuilder.java   View Source Code Vote up 6 votes
/**
 * Build the summary for the classes in this package.
 *
 * @param summaryContentTree the summary tree to which the class summary will
 *                           be added
 */
protected void buildClassSummary(Content summaryContentTree) {
    String classTableSummary =
            configuration.getText("doclet.Member_Table_Summary",
            configuration.getText("doclet.Class_Summary"),
            configuration.getText("doclet.classes"));
    List<String> classTableHeader = Arrays.asList(configuration.getText("doclet.Class"),
            configuration.getText("doclet.Description"));
    SortedSet<TypeElement> clist = utils.isSpecified(packageElement)
        ? utils.getTypeElementsAsSortedSet(utils.getOrdinaryClasses(packageElement))
        : configuration.typeElementCatalog.ordinaryClasses(packageElement);
    SortedSet<TypeElement> classes = utils.filterOutPrivateClasses(clist, configuration.javafx);
    if (!classes.isEmpty()) {
        packageWriter.addClassesSummary(classes,
                configuration.getText("doclet.Class_Summary"),
                classTableSummary, classTableHeader, summaryContentTree);
    }
}
 
Example 9
Project: parabuild-ci   File: ClassDef.java   View Source Code Vote up 6 votes
public IMethod getMostCompatibleMethod(String name, ISignature signature) {
    IMethod result = null;

    SortedSet compatibleMethods =
        new TreeSet(new MethodSpecificityComparator());

    Iterator it = methods.iterator();
    while (it.hasNext()) {
        MethodDef method = (MethodDef) it.next();
        if (name.equals(method.getName())) {
            if (method.hasCompatibleSignature(signature)) {
                compatibleMethods.add(method);
            }
        }
    }

    if (!compatibleMethods.isEmpty()) {
        result = (IMethod) compatibleMethods.first();
    }

    return result;
}
 
Example 10
Project: accumulate   File: SET.java   View Source Code Vote up 5 votes
/**
 * Return the largest key in this set <= k.
 */
public Key floor(Key k) {
    if (set.contains(k)) return k;

    // does not include key if present (!)
    SortedSet<Key> head = set.headSet(k);
    if (head.isEmpty()) return null;
    else return head.last();
}
 
Example 11
Project: incubator-netbeans   File: ResourcesTest.java   View Source Code Vote up 5 votes
/** Scan for accidentally commited files that get into product
 */
public void testInappropraiteEntries() throws Exception {
    SortedSet<Violation> violations = new TreeSet<Violation>();
    for (File f: org.netbeans.core.startup.Main.getModuleSystem().getModuleJars()) {
        // check JAR files only
        if (!f.getName().endsWith(".jar"))
            continue;
        
        if (!f.getName().endsWith("cssparser-0-9-4-fs.jar")) // #108644
            continue;
        
        JarFile jar = new JarFile(f);
        Enumeration<JarEntry> entries = jar.entries();
        JarEntry entry;
        BufferedImage img;
        while (entries.hasMoreElements()) {
            entry = entries.nextElement();
            if (entry.isDirectory())
                continue;
            
            if (entry.getName().endsWith("Thumbs.db")) {
                violations.add(new Violation(entry.getName(), jar.getName(), " should not be in module JAR"));
            }
            if (entry.getName().contains("nbproject/private")) {
                violations.add(new Violation(entry.getName(), jar.getName(), " should not be in module JAR"));
            }
        }
    }
    if (!violations.isEmpty()) {
        StringBuilder msg = new StringBuilder();
        msg.append("Some files does not belong to module JARs ("+violations.size()+"):\n");
        for (Violation viol: violations) {
            msg.append(viol).append('\n');
        }
        fail(msg.toString());
    }
}
 
Example 12
Project: googles-monorepo-demo   File: SetGenerators.java   View Source Code Vote up 5 votes
@Override
protected SortedSet<Integer> create(Integer[] elements) {
  SortedSet<Integer> set = nullCheckedTreeSet(elements);
  int tooHigh = (set.isEmpty()) ? 0 : set.last() + 1;
  set.add(tooHigh);
  return checkedCreate(set).headSet(tooHigh);
}
 
Example 13
Project: guava-mock   File: SetGenerators.java   View Source Code Vote up 5 votes
@Override
protected SortedSet<Integer> create(Integer[] elements) {
  SortedSet<Integer> set = nullCheckedTreeSet(elements);
  int tooLow = (set.isEmpty()) ? 0 : set.first() - 1;
  set.add(tooLow);
  return checkedCreate(set).tailSet(tooLow + 1);
}
 
Example 14
Project: openjdk-jdk10   File: ModuleWriterImpl.java   View Source Code Vote up 4 votes
/**
 * Add the provides list for the module.
 *
 * @param tbody the content tree to which the directive will be added
 */
public void addProvidesList(Content tbody) {
    boolean altColor = true;
    SortedSet<TypeElement> implSet;
    Content description;
    for (Map.Entry<TypeElement, SortedSet<TypeElement>> entry : provides.entrySet()) {
        TypeElement srv = entry.getKey();
        if (!displayServiceDirective(srv, providesTrees)) {
            continue;
        }
        implSet = entry.getValue();
        Content srvLinkContent = getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.PACKAGE, srv));
        HtmlTree thType = HtmlTree.TH_ROW_SCOPE(HtmlStyle.colFirst, srvLinkContent);
        HtmlTree tdDesc = new HtmlTree(HtmlTag.TD);
        tdDesc.addStyle(HtmlStyle.colLast);
        if (display(providesTrees)) {
            description = providesTrees.get(srv);
            if (description != null) {
                tdDesc.addContent(description);
            }
        }
        addSummaryComment(srv, tdDesc);
        // Only display the implementation details in the "all" mode.
        if (moduleMode == ModuleMode.ALL && !implSet.isEmpty()) {
            tdDesc.addContent(new HtmlTree(HtmlTag.BR));
            tdDesc.addContent("(");
            HtmlTree implSpan = HtmlTree.SPAN(HtmlStyle.implementationLabel, contents.implementation);
            tdDesc.addContent(implSpan);
            tdDesc.addContent(Contents.SPACE);
            String sep = "";
            for (TypeElement impl : implSet) {
                tdDesc.addContent(sep);
                tdDesc.addContent(getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.PACKAGE, impl)));
                sep = ", ";
            }
            tdDesc.addContent(")");
        }
        HtmlTree tr = HtmlTree.TR(thType);
        tr.addContent(tdDesc);
        tr.addStyle(altColor ? HtmlStyle.altColor : HtmlStyle.rowColor);
        tbody.addContent(tr);
        altColor = !altColor;
    }
}
 
Example 15
Project: guava-mock   File: ImmutableSortedSet.java   View Source Code Vote up 4 votes
static <E> ImmutableSortedSet<E> unsafeDelegateSortedSet(
    SortedSet<E> delegate, boolean isSubset) {
  return delegate.isEmpty()
      ? emptySet(delegate.comparator())
      : new RegularImmutableSortedSet<E>(delegate, isSubset);
}
 
Example 16
Project: hadoop   File: JournalSet.java   View Source Code Vote up 4 votes
/**
 * Return a manifest of what finalized edit logs are available. All available
 * edit logs are returned starting from the transaction id passed. If
 * 'fromTxId' falls in the middle of a log, that log is returned as well.
 * 
 * @param fromTxId Starting transaction id to read the logs.
 * @return RemoteEditLogManifest object.
 */
public synchronized RemoteEditLogManifest getEditLogManifest(long fromTxId) {
  // Collect RemoteEditLogs available from each FileJournalManager
  List<RemoteEditLog> allLogs = Lists.newArrayList();
  for (JournalAndStream j : journals) {
    if (j.getManager() instanceof FileJournalManager) {
      FileJournalManager fjm = (FileJournalManager)j.getManager();
      try {
        allLogs.addAll(fjm.getRemoteEditLogs(fromTxId, false));
      } catch (Throwable t) {
        LOG.warn("Cannot list edit logs in " + fjm, t);
      }
    }
  }
  
  // Group logs by their starting txid
  ImmutableListMultimap<Long, RemoteEditLog> logsByStartTxId =
    Multimaps.index(allLogs, RemoteEditLog.GET_START_TXID);
  long curStartTxId = fromTxId;

  List<RemoteEditLog> logs = Lists.newArrayList();
  while (true) {
    ImmutableList<RemoteEditLog> logGroup = logsByStartTxId.get(curStartTxId);
    if (logGroup.isEmpty()) {
      // we have a gap in logs - for example because we recovered some old
      // storage directory with ancient logs. Clear out any logs we've
      // accumulated so far, and then skip to the next segment of logs
      // after the gap.
      SortedSet<Long> startTxIds = Sets.newTreeSet(logsByStartTxId.keySet());
      startTxIds = startTxIds.tailSet(curStartTxId);
      if (startTxIds.isEmpty()) {
        break;
      } else {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Found gap in logs at " + curStartTxId + ": " +
              "not returning previous logs in manifest.");
        }
        logs.clear();
        curStartTxId = startTxIds.first();
        continue;
      }
    }

    // Find the one that extends the farthest forward
    RemoteEditLog bestLog = Collections.max(logGroup);
    logs.add(bestLog);
    // And then start looking from after that point
    curStartTxId = bestLog.getEndTxId() + 1;
  }
  RemoteEditLogManifest ret = new RemoteEditLogManifest(logs);
  
  if (LOG.isDebugEnabled()) {
    LOG.debug("Generated manifest for logs since " + fromTxId + ":"
        + ret);      
  }
  return ret;
}
 
Example 17
Project: ZooKeeper   File: WriteLock.java   View Source Code Vote up 4 votes
/**
 * the command that is run and retried for actually 
 * obtaining the lock
 * @return if the command was successful or not
 */
public boolean execute() throws KeeperException, InterruptedException {
    do {
        if (id == null) {
            long sessionId = zookeeper.getSessionId();
            String prefix = "x-" + sessionId + "-";
            // lets try look up the current ID if we failed 
            // in the middle of creating the znode
            findPrefixInChildren(prefix, zookeeper, dir);
            idName = new ZNodeName(id);
        }
        if (id != null) {
            List<String> names = zookeeper.getChildren(dir, false);
            if (names.isEmpty()) {
                LOG.warn("No children in: " + dir + " when we've just " +
                "created one! Lets recreate it...");
                // lets force the recreation of the id
                id = null;
            } else {
                // lets sort them explicitly (though they do seem to come back in order ususally :)
                SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
                for (String name : names) {
                    sortedNames.add(new ZNodeName(dir + "/" + name));
                }
                ownerId = sortedNames.first().getName();
                SortedSet<ZNodeName> lessThanMe = sortedNames.headSet(idName);
                if (!lessThanMe.isEmpty()) {
                    ZNodeName lastChildName = lessThanMe.last();
                    lastChildId = lastChildName.getName();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("watching less than me node: " + lastChildId);
                    }
                    Stat stat = zookeeper.exists(lastChildId, new LockWatcher());
                    if (stat != null) {
                        return Boolean.FALSE;
                    } else {
                        LOG.warn("Could not find the" +
                        		" stats for less than me: " + lastChildName.getName());
                    }
                } else {
                    if (isOwner()) {
                        if (callback != null) {
                            callback.lockAcquired();
                        }
                        return Boolean.TRUE;
                    }
                }
            }
        }
    }
    while (id == null);
    return Boolean.FALSE;
}
 
Example 18
Project: openjdk-jdk10   File: ModuleWriterImpl.java   View Source Code Vote up 4 votes
public int addPackageTableRows(Content tbody, int counter, ModulePackageTypes pType,
        Map<PackageElement,SortedSet<ModuleElement>> ap) {
    boolean altColor = true;
    for (Map.Entry<PackageElement, SortedSet<ModuleElement>> entry : ap.entrySet()) {
        PackageElement pkg = entry.getKey();
        SortedSet<ModuleElement> mdleList = entry.getValue();
        Content pkgLinkContent = getPackageLink(pkg, new StringContent(utils.getPackageName(pkg)));
        Content thPackage = HtmlTree.TH_ROW_SCOPE(HtmlStyle.colFirst, pkgLinkContent);
        HtmlTree tr = HtmlTree.TR(thPackage);
        if (moduleMode == ModuleMode.ALL) {
            HtmlTree tdModules = new HtmlTree(HtmlTag.TD);
            tdModules.addStyle(HtmlStyle.colSecond);
            if (!mdleList.isEmpty()) {
                int sep = 0;
                for (ModuleElement m : mdleList) {
                    if (sep > 0) {
                        tdModules.addContent(new HtmlTree(HtmlTag.BR));
                    }
                    tdModules.addContent(getModuleLink(m, new StringContent(m.getQualifiedName())));
                    sep++;
                }
            } else {
                tdModules.addContent(configuration.getText("doclet.All_Modules"));
            }
            tr.addContent(tdModules);
        }
        HtmlTree tdSummary = new HtmlTree(HtmlTag.TD);
        tdSummary.addStyle(HtmlStyle.colLast);
        addSummaryComment(pkg, tdSummary);
        tr.addContent(tdSummary);
        tr.addStyle(altColor ? HtmlStyle.altColor : HtmlStyle.rowColor);
        int pkgType = pType.tableTabs().value();
        packageTypesOr = packageTypesOr | pkgType;
        String tableId = "i" + counter;
        counter++;
        typeMap.put(tableId, pkgType);
        tr.addAttr(HtmlAttr.ID, tableId);
        tbody.addContent(tr);
        altColor = !altColor;
    }
    return counter;
}
 
Example 19
Project: JavaGraph   File: MultiLinedEditor.java   View Source Code Vote up 4 votes
private LinkedList<String> computeCompletions() {
    LinkedList<String> result = new LinkedList<>();
    Caret caret = getEditorComponent().getCaret();
    int dot = caret.getDot();
    int mark = caret.getMark();
    int min = Math.min(dot, mark);
    int max = Math.max(dot, mark);

    String content;
    try {
        // only do completion if the selection runs up to the end of a label
        Document document = getDocument();
        if (max < document.getLength()
            && Character.isLetterOrDigit(document.getText(max, 1).charAt(0))) {
            return result;
        }
        content = document.getText(0, min);
    } catch (BadLocationException exc) {
        throw new IllegalStateException(String.format("Impossible error: %s", exc));
    }

    // Find where the label starts
    int start = min;
    while (start > 0 && Character.isLetterOrDigit(content.charAt(start - 1))) {
        start--;
    }
    if (start < min) {
        // Identify the root of the word to be completed
        String root = content.substring(start);
        SortedSet<String> tailSet = RealCellEditor.this.labels.tailSet(root);
        if (!tailSet.isEmpty()) {
            Iterator<String> iter = tailSet.iterator();
            String nextCompletion = iter.next();
            while (nextCompletion.startsWith(root)) {
                result.add(nextCompletion.substring(min - start));
                nextCompletion = iter.next();
            }
        }
    }
    return result;
}
 
Example 20
Project: ZooKeeper   File: WriteLock.java   View Source Code Vote up 4 votes
/**
 * the command that is run and retried for actually 
 * obtaining the lock
 * @return if the command was successful or not
 */
public boolean execute() throws KeeperException, InterruptedException {
    do {
        if (id == null) {
            long sessionId = zookeeper.getSessionId();
            String prefix = "x-" + sessionId + "-";
            // lets try look up the current ID if we failed 
            // in the middle of creating the znode
            findPrefixInChildren(prefix, zookeeper, dir);
            idName = new ZNodeName(id);
        }
        if (id != null) {
            List<String> names = zookeeper.getChildren(dir, false);
            if (names.isEmpty()) {
                LOG.warn("No children in: " + dir + " when we've just " +
                "created one! Lets recreate it...");
                // lets force the recreation of the id
                id = null;
            } else {
                // lets sort them explicitly (though they do seem to come back in order ususally :)
                SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
                for (String name : names) {
                    sortedNames.add(new ZNodeName(dir + "/" + name));
                }
                ownerId = sortedNames.first().getName();
                SortedSet<ZNodeName> lessThanMe = sortedNames.headSet(idName);
                if (!lessThanMe.isEmpty()) {
                    ZNodeName lastChildName = lessThanMe.last();
                    lastChildId = lastChildName.getName();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("watching less than me node: " + lastChildId);
                    }
                    Stat stat = zookeeper.exists(lastChildId, new LockWatcher());
                    if (stat != null) {
                        return Boolean.FALSE;
                    } else {
                        LOG.warn("Could not find the" +
                        		" stats for less than me: " + lastChildName.getName());
                    }
                } else {
                    if (isOwner()) {
                        if (callback != null) {
                            callback.lockAcquired();
                        }
                        return Boolean.TRUE;
                    }
                }
            }
        }
    }
    while (id == null);
    return Boolean.FALSE;
}