Example usage for java.util SortedSet isEmpty

List of usage examples for java.util SortedSet isEmpty

Introduction

In this page you can find the example usage for java.util SortedSet isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this set contains no elements.

Usage

From source file:org.apache.hadoop.hbase.regionserver.DefaultMemStore.java

private boolean walkForwardInSingleRow(final SortedSet<KeyValue> set, final KeyValue firstOnRow,
        final GetClosestRowBeforeTracker state) {
    boolean foundCandidate = false;
    SortedSet<KeyValue> tail = set.tailSet(firstOnRow);
    if (tail.isEmpty())
        return foundCandidate;
    for (Iterator<KeyValue> i = tail.iterator(); i.hasNext();) {
        KeyValue kv = i.next();/* www . ja  v  a 2 s .com*/
        // Did we go beyond the target row? If so break.
        if (state.isTooFar(kv, firstOnRow))
            break;
        if (state.isExpired(kv)) {
            i.remove();
            continue;
        }
        // If we added something, this row is a contender. break.
        if (state.handle(kv)) {
            foundCandidate = true;
            break;
        }
    }
    return foundCandidate;
}

From source file:org.geoserver.taskmanager.external.impl.S3FileServiceImpl.java

@Override
public FileReference getVersioned(String filePath) {
    int index = filePath.indexOf(PLACEHOLDER_VERSION);
    if (index < 0) {
        return new FileReferenceImpl(this, filePath, filePath);
    }//from  w ww.  j a  v  a  2s  . co  m

    SortedSet<Integer> set = new TreeSet<Integer>();
    Pattern pattern = Pattern
            .compile(Pattern.quote(filePath).replace(FileService.PLACEHOLDER_VERSION, "\\E(.*)\\Q"));

    ObjectListing listing = getS3Client().listObjects(rootFolder, filePath.substring(0, index));
    for (S3ObjectSummary summary : listing.getObjectSummaries()) {
        Matcher matcher = pattern.matcher(summary.getKey());
        if (matcher.matches()) {
            try {
                set.add(Integer.parseInt(matcher.group(1)));
            } catch (NumberFormatException e) {
                LOGGER.log(Level.WARNING, "could not parse version in versioned file " + summary.getKey(), e);
            }
        }
    }
    int last = set.isEmpty() ? 0 : set.last();
    return new FileReferenceImpl(this, filePath.replace(FileService.PLACEHOLDER_VERSION, last + ""),
            filePath.replace(FileService.PLACEHOLDER_VERSION, (last + 1) + ""));
}

From source file:org.apache.hadoop.hbase.regionserver.DefaultMemStore.java

/**
 * Only used by tests. TODO: Remove//w w  w .j  a  v a 2  s .c o m
 *
 * Given the specs of a column, update it, first by inserting a new record,
 * then removing the old one.  Since there is only 1 KeyValue involved, the memstoreTS
 * will be set to 0, thus ensuring that they instantly appear to anyone. The underlying
 * store will ensure that the insert/delete each are atomic. A scanner/reader will either
 * get the new value, or the old value and all readers will eventually only see the new
 * value after the old was removed.
 *
 * @param row
 * @param family
 * @param qualifier
 * @param newValue
 * @param now
 * @return  Timestamp
 */
public long updateColumnValue(byte[] row, byte[] family, byte[] qualifier, long newValue, long now) {
    KeyValue firstKv = KeyValueUtil.createFirstOnRow(row, family, qualifier);
    // Is there a KeyValue in 'snapshot' with the same TS? If so, upgrade the timestamp a bit.
    SortedSet<KeyValue> snSs = snapshot.tailSet(firstKv);
    if (!snSs.isEmpty()) {
        KeyValue snKv = snSs.first();
        // is there a matching KV in the snapshot?
        if (CellUtil.matchingRow(snKv, firstKv) && CellUtil.matchingQualifier(snKv, firstKv)) {
            if (snKv.getTimestamp() == now) {
                // poop,
                now += 1;
            }
        }
    }

    // logic here: the new ts MUST be at least 'now'. But it could be larger if necessary.
    // But the timestamp should also be max(now, mostRecentTsInMemstore)

    // so we cant add the new KV w/o knowing what's there already, but we also
    // want to take this chance to delete some kvs. So two loops (sad)

    SortedSet<KeyValue> ss = kvset.tailSet(firstKv);
    for (KeyValue kv : ss) {
        // if this isnt the row we are interested in, then bail:
        if (!CellUtil.matchingColumn(kv, family, qualifier) || !CellUtil.matchingRow(kv, firstKv)) {
            break; // rows dont match, bail.
        }

        // if the qualifier matches and it's a put, just RM it out of the kvset.
        if (kv.getTypeByte() == KeyValue.Type.Put.getCode() && kv.getTimestamp() > now
                && CellUtil.matchingQualifier(firstKv, kv)) {
            now = kv.getTimestamp();
        }
    }

    // create or update (upsert) a new KeyValue with
    // 'now' and a 0 memstoreTS == immediately visible
    List<Cell> cells = new ArrayList<Cell>(1);
    cells.add(new KeyValue(row, family, qualifier, now, Bytes.toBytes(newValue)));
    return upsert(cells, 1L);
}

From source file:org.silverpeas.components.whitepages.control.WhitePagesSessionController.java

public SortedSet<SearchField> getSearchFields() throws WhitePagesException {
    SortedSet<SearchField> fields = WhitePageServiceProvider.getWhitePagesService()
            .getSearchFields(getComponentId());
    if (!fields.isEmpty()) {
        PublicationTemplate template = null;
        Map<String, String> domainProperties = null;
        try {//w ww  . j av a2 s.  com
            RecordTemplate recordTemplate = null;
            for (SearchField field : fields) {
                if (field.getFieldId().startsWith(SearchFieldsType.XML.getLabelType())) {
                    if (template == null) {
                        template = getTemplate(getComponentId());
                        recordTemplate = template.getRecordTemplate();
                    }
                    field.setLabel(
                            recordTemplate.getFieldTemplate(field.getFieldName()).getLabel(getLanguage()));
                } else if (field.getFieldId().startsWith(SearchFieldsType.LDAP.getLabelType())) {
                    if (domainProperties == null) {
                        domainProperties = getDomainProperties();
                    }
                    field.setLabel(domainProperties.get(field.getFieldName()));
                } else if (field.getFieldId().startsWith(SearchFieldsType.USER.getLabelType())) {
                    if ("name".equals(field.getFieldName())) {
                        field.setLabel(ResourceLocator.getGeneralLocalizationBundle(getLanguage())
                                .getString("GML.lastName"));
                    } else if ("surname".equals(field.getFieldName())) {
                        field.setLabel(ResourceLocator.getGeneralLocalizationBundle(getLanguage())
                                .getString("GML.surname"));
                    } else if ("email".equals(field.getFieldName())) {
                        field.setLabel(ResourceLocator.getGeneralLocalizationBundle(getLanguage())
                                .getString("GML.eMail"));
                    }
                }
            }
        } catch (Exception e) {
            SilverTrace.error("whitePages", "WhitePagesSessionController.getSearchFields",
                    "whitePages.CANT_GET_XML_FIELDS", e);
        }
    }
    return fields;
}

From source file:com.cloudera.whirr.cm.CmServerClusterInstance.java

@SuppressWarnings("unchecked")
public static Map<String, Map<String, Map<String, String>>> getClusterConfiguration(
        final Configuration configuration, SortedSet<String> mounts) throws IOException {

    Map<String, Map<String, Map<String, String>>> clusterConfiguration = new HashMap<String, Map<String, Map<String, String>>>();

    Iterator<String> keys = configuration.getKeys();
    while (keys.hasNext()) {
        String key = keys.next();
        if (key.startsWith(CONFIG_WHIRR_CM_CONFIG_PREFIX)) {
            String[] keyTokens = getClusterConfigurationKeyTokens(clusterConfiguration, key,
                    CONFIG_WHIRR_CM_CONFIG_PREFIX);
            clusterConfiguration.get(keyTokens[0]).get(keyTokens[1]).put(keyTokens[2],
                    configuration.getString(key));
        }/*from ww  w  .j  av a2 s . c  o  m*/
    }

    keys = configuration.getKeys();
    while (keys.hasNext()) {
        final String key = keys.next();
        if (key.startsWith(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX)) {
            String[] keyTokens = getClusterConfigurationKeyTokens(clusterConfiguration, key,
                    CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX);
            if (configuration.getString(
                    CONFIG_WHIRR_CM_CONFIG_PREFIX + keyTokens[1].toLowerCase() + "." + keyTokens[2]) == null) {
                if ((keyTokens[2].endsWith(CONFIG_CM_DIR_SUFFIX_LIST)
                        || keyTokens[2].endsWith(CONFIG_CM_DIR_SUFFIX_PLURAL)) && !mounts.isEmpty()) {
                    clusterConfiguration.get(keyTokens[0]).get(keyTokens[1]).put(keyTokens[2], Joiner.on(',')
                            .join(Lists.transform(Lists.newArrayList(mounts), new Function<String, String>() {
                                @Override
                                public String apply(String input) {
                                    return input + configuration.getString(key);
                                }
                            })));
                } else {
                    clusterConfiguration.get(keyTokens[0]).get(keyTokens[1]).put(keyTokens[2],
                            (mounts.isEmpty() ? configuration.getString(CONFIG_WHIRR_INTERNAL_DATA_DIRS_DEFAULT)
                                    : mounts.iterator().next()) + configuration.getString(key));
                }
            }
        }
    }

    keys = configuration.getKeys();
    while (keys.hasNext()) {
        final String key = keys.next();
        if (key.startsWith(CONFIG_WHIRR_CM_CONFIG_PREFIX) && key.endsWith(CONFIG_CM_DB_SUFFIX_TYPE)) {
            String[] keyTokens = getClusterConfigurationKeyTokens(clusterConfiguration, key,
                    CONFIG_WHIRR_CM_CONFIG_PREFIX);
            if (configuration.getString(key) != null && configuration.getString(key).length() == 0) {
                clusterConfiguration.get(keyTokens[0]).get(keyTokens[1]).put(keyTokens[2],
                        configuration.getString(CONFIG_WHIRR_DB_TYPE));
                if (configuration
                        .getString(key.replace(CONFIG_CM_DB_SUFFIX_TYPE, CONFIG_CM_DB_SUFFIX_PORT)) != null
                        && configuration
                                .getString(key.replace(CONFIG_CM_DB_SUFFIX_TYPE, CONFIG_CM_DB_SUFFIX_PORT))
                                .length() == 0) {
                    clusterConfiguration.get(keyTokens[0]).get(keyTokens[1]).put(
                            keyTokens[2].replace(CONFIG_CM_DB_SUFFIX_TYPE, CONFIG_CM_DB_SUFFIX_PORT),
                            configuration.getString(CONFIG_WHIRR_INTERNAL_PORTS_DB_PREFIX
                                    + configuration.getString(CONFIG_WHIRR_DB_TYPE)));
                } else if (configuration
                        .getString(key.replace(CONFIG_CM_DB_SUFFIX_TYPE, CONFIG_CM_DB_SUFFIX_HOST)) != null
                        && !configuration
                                .getString(key.replace(CONFIG_CM_DB_SUFFIX_TYPE, CONFIG_CM_DB_SUFFIX_HOST))
                                .contains(":")) {
                    clusterConfiguration.get(keyTokens[0]).get(keyTokens[1]).put(
                            keyTokens[2].replace(CONFIG_CM_DB_SUFFIX_TYPE, CONFIG_CM_DB_SUFFIX_HOST),
                            configuration
                                    .getString(key.replace(CONFIG_CM_DB_SUFFIX_TYPE, CONFIG_CM_DB_SUFFIX_HOST))
                                    + ":" + configuration.getString(CONFIG_WHIRR_INTERNAL_PORTS_DB_PREFIX
                                            + configuration.getString(CONFIG_WHIRR_DB_TYPE)));
                }
            }
        }
    }

    if (clusterConfiguration.get(CM_API_BASE_VERSION) == null) {
        clusterConfiguration.put(CM_API_BASE_VERSION, new HashMap<String, Map<String, String>>());
    }
    if (clusterConfiguration.get(CM_API_BASE_VERSION).get(CmServerServiceType.CLUSTER.getId()) == null) {
        clusterConfiguration.get(CM_API_BASE_VERSION).put(CmServerServiceType.CLUSTER.getId(),
                new HashMap<String, String>());
    }

    if (clusterConfiguration.get(CM_API_BASE_VERSION).get(CmServerServiceType.CLUSTER.getId())
            .get(CONFIG_CM_LICENSE_PROVIDED) == null) {
        if (Utils.urlForURI(configuration.getString(CONFIG_WHIRR_CM_LICENSE_URI)) != null) {
            clusterConfiguration.get(CM_API_BASE_VERSION).get(CmServerServiceType.CLUSTER.getId())
                    .put(CONFIG_CM_LICENSE_PROVIDED, Boolean.TRUE.toString());
        } else {
            clusterConfiguration.get(CM_API_BASE_VERSION).get(CmServerServiceType.CLUSTER.getId())
                    .put(CONFIG_CM_LICENSE_PROVIDED, Boolean.FALSE.toString());
        }
    }

    if (clusterConfiguration.get(CM_API_BASE_VERSION).get(CmServerServiceType.CLUSTER.getId())
            .get(CONFIG_CM_LICENSE_PROVIDED).equals(Boolean.TRUE.toString())) {
        if (clusterConfiguration.get(CM_API_BASE_VERSION)
                .get(CmServerServiceType.MAPREDUCE_TASK_TRACKER.getId()) == null) {
            clusterConfiguration.get(CM_API_BASE_VERSION)
                    .put(CmServerServiceType.MAPREDUCE_TASK_TRACKER.getId(), new HashMap<String, String>());
        }
        clusterConfiguration.get(CM_API_BASE_VERSION).get(CmServerServiceType.MAPREDUCE_TASK_TRACKER.getId())
                .put(CONFIG_CM_TASKTRACKER_INSTRUMENTATION, "org.apache.hadoop.mapred.TaskTrackerCmonInst");
    }

    return clusterConfiguration;

}

From source file:net.big_oh.algorithms.search.informed.astar.AStarSearch.java

public AStarSearchResult<SearchNodeType> doSearch(SearchNodeType startNode) {

    Duration searchDuration = new Duration();

    // create priority queue
    SortedSet<SearchNodeType> prioritySet = new TreeSet<SearchNodeType>(new Comparator<SearchNodeType>() {

        public int compare(SearchNodeType o1, SearchNodeType o2) {
            switch (searchType) {
            case MIN:
                return Double.compare(getF(o1), getF(o2));
            case MAX:
                return -1 * Double.compare(getF(o1), getF(o2));
            default:
                throw new RuntimeException("Unexpected search type: " + searchType);
            }/*from  w w w.  j ava 2  s . c  om*/
        }

    });

    // enqueue the start node
    prioritySet.add(startNode);

    // declare tracking member variables
    int numSearchNodesGenerated = 0;
    int numSearchNodesConsidered = 0;
    int maxPossibleBranchingFactor = 1;

    // search for a goal state
    SearchNodeType goalNode = null;
    while (!prioritySet.isEmpty()) {

        // Remove the best candidate node from the queue
        SearchNodeType candidateSearchNode = prioritySet.first();
        prioritySet.remove(candidateSearchNode);
        numSearchNodesConsidered++;

        // get the next search node candidates
        Collection<SearchNodeType> nextSearchNodes = nextNodesGenerator.getNextSearchNodes(candidateSearchNode);

        // do some record keeping
        numSearchNodesGenerated += nextSearchNodes.size();
        maxPossibleBranchingFactor = Math.max(maxPossibleBranchingFactor, nextSearchNodes.size());

        if (candidateSearchNode.isGoalState()) {
            // sanity check
            assert (nextSearchNodes.isEmpty());

            // found an optimal solution
            goalNode = candidateSearchNode;
            break;
        } else {
            // enqueue all next search nodes
            Duration enqueueDuration = new Duration();

            prioritySet.addAll(nextSearchNodes);

            if (logger.isDebugEnabled()) {
                logger.debug("Enqueued " + nextSearchNodes.size() + " A* search nodes in "
                        + enqueueDuration.stop() + " milliseconds.");
            }
        }

    }

    // return the search results
    AStarSearchResult<SearchNodeType> results = new AStarSearchResult<SearchNodeType>(goalNode,
            numSearchNodesGenerated, calculateEffectiveBranchingFactor(goalNode.getNodeDepth(),
                    numSearchNodesConsidered, maxPossibleBranchingFactor));

    logger.debug("Completed an A* search in " + searchDuration.stop() + " milliseconds.");
    logger.debug("Number of nodes generated: " + results.getNumSearchNodesGenerated());
    logger.debug("Depth of goal node: " + results.getGoalNode().getNodeDepth());
    logger.debug("Effective branching factor: " + results.getEfectiveBranchingFactor());

    return results;

}

From source file:org.jahia.services.render.RenderService.java

private Template addTemplate(Resource resource, RenderContext renderContext, String templateName,
        Set<String> installedModules, String type) throws RepositoryException {
    SortedSet<Template> templates = new TreeSet<Template>(TEMPLATE_PRIORITY_COMPARATOR);
    for (String s : installedModules) {
        JahiaTemplatesPackage pack = templateManagerService.getTemplatePackageById(s);
        if (pack != null) {
            JCRNodeWrapper templateNode = resource.getNode().getSession()
                    .getNode("/modules/" + s + "/" + pack.getVersion());
            templates.addAll(addTemplates(resource, renderContext, templateName, templateNode, type));
        }/*w w w.  java  2  s . c o m*/
    }
    return templates.isEmpty() ? null : templates.last();
}

From source file:net.pms.dlna.protocolinfo.PanasonicDmpProfiles.java

/**
 * Tries to parse {@code dmpProfilesString} and adds the resulting
 * {@link ProtocolInfo} instances to the {@link Set} of type
 * {@link PanasonicDmpProfileType} in {@code deviceProtocolInfo}.
 *
 * @param dmpProfilesString a space separated string of format profile
 *            representations whose presence is to be ensured.
 * @return {@code true} if the {@link Set} of {@link ProtocolInfo} in
 *         {@code deviceProtocolInfo} changed as a result of the call.
 *         Returns {@code false} this already contains the specified
 *         elements.//from   w ww. jav  a 2  s.c  o m
 */
public boolean add(String dmpProfilesString) {
    if (StringUtils.isBlank(dmpProfilesString)) {
        return false;
    }

    dmpProfilesString = dmpProfilesString.replaceFirst("\\s*X-PANASONIC-DMP-Profile:\\s*", "").trim();
    String[] elements = dmpProfilesString.trim().split("\\s+");

    SortedSet<ProtocolInfo> protocolInfoSet = new TreeSet<>();
    for (String element : elements) {
        try {
            ProtocolInfo protocolInfo = dmpProfileToProtocolInfo(element);
            if (protocolInfo != null) {
                protocolInfoSet.add(protocolInfo);
            }
        } catch (ParseException e) {
            LOGGER.warn("Unable to parse protocolInfo from \"{}\", this profile will not be registered: {}",
                    element, e.getMessage());
            LOGGER.trace("", e);
        }
    }
    boolean result = false;
    if (!protocolInfoSet.isEmpty()) {
        result = deviceProtocolInfo.addAll(PANASONIC_DMP, protocolInfoSet);
    }

    populated |= result;
    return result;
}

From source file:com.github.FraggedNoob.GitLabTransfer.GitlabRelatedData.java

/**
 * List all the issue notes in this instance.
 *///  ww w  .  j a  v a2 s.  c om
public void listAllIssuesNotes() {
    if (!issues.isEmpty()) {
        // issues and notes
        System.out.println("Project Issues:");
        for (GitlabIssue i : issues) {
            System.out.printf("IID=%d, Title=%s\n", i.getIid(), i.getTitle());
            SortedSet<GitlabNote> noteset = issueNotes.get(i.getIid());
            if ((noteset == null) || (noteset.isEmpty())) {
                System.out.printf("\t (no notes)\n");
            } else {
                System.out.printf("\t [%d notes]\n", noteset.size());
            }
        }
    }
}

From source file:com.silverpeas.whitePages.control.WhitePagesSessionController.java

public Set<String> getSearchFieldIds() throws UtilException, WhitePagesException {
    Set<String> ids = new HashSet<String>();
    SortedSet<SearchField> searchFields = getSearchFields();
    if (searchFields != null && !searchFields.isEmpty()) {
        for (SearchField field : searchFields) {
            ids.add(field.getFieldId());
        }// ww  w . ja  v a  2s.  c  om
    }
    return ids;
}