Example usage for java.util NavigableMap containsKey

List of usage examples for java.util NavigableMap containsKey

Introduction

In this page you can find the example usage for java.util NavigableMap containsKey.

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:de.hybris.platform.acceleratorcms.services.impl.RankingCMSRestrictionService.java

@Override
public Collection<AbstractPageModel> evaluatePages(final Collection<AbstractPageModel> pages,
        final RestrictionData data) {
    final NavigableMap<Integer, List<AbstractPageModel>> allowedPages = new TreeMap<>();

    final Collection<AbstractPageModel> defaultPages = getDefaultPages(pages);
    for (final AbstractPageModel page : pages) {
        if (defaultPages.contains(page)) {
            continue;
        }//w  w  w  .  j a va2 s . c o m

        final List<AbstractRestrictionModel> restrictions = page.getRestrictions();
        if (restrictions == null || restrictions.isEmpty()) {
            LOG.debug("Page [" + page.getName()
                    + "] is not default page and contains no restrictions. Skipping this page.");
        } else {
            LOG.debug("Evaluating restrictions for page [" + page.getName() + "].");
            final boolean onlyOneRestrictionMustApply = page.isOnlyOneRestrictionMustApply();
            final boolean allowed = evaluate(restrictions, data, onlyOneRestrictionMustApply);
            if (allowed) {
                LOG.debug("Adding page [" + page.getName() + "] to allowed pages");
                final Integer countOfMatchingRestrictions = Integer
                        .valueOf(onlyOneRestrictionMustApply ? 1 : restrictions.size());

                if (allowedPages.containsKey(countOfMatchingRestrictions)) {
                    // Add to existing list
                    allowedPages.get(countOfMatchingRestrictions).add(page);
                } else {
                    // Add a new entry
                    final List<AbstractPageModel> list = new ArrayList<>();
                    list.add(page);
                    allowedPages.put(countOfMatchingRestrictions, list);
                }
            }
        }
    }

    final List<AbstractPageModel> result = new ArrayList<>();

    if (MapUtils.isNotEmpty(allowedPages)) {
        // Take the highest match count
        result.addAll(allowedPages.lastEntry().getValue());
    } else {
        if (defaultPages.size() > 1) {
            LOG.warn(createMoreThanOneDefaultPageWarning(defaultPages));
        }
        if (CollectionUtils.isNotEmpty(defaultPages)) {
            LOG.debug("Returning default page");
            result.add(defaultPages.iterator().next());
        }
    }

    return result;
}

From source file:com.ngdata.sep.impl.fork.ForkedReplicationSource.java

/**
 * We only want KVs that are scoped other than local
 * @param edit The KV to check for replication
 *//*from  w  w  w .  ja  va 2s.  c o m*/
protected void removeNonReplicableEdits(WALEdit edit) {
    NavigableMap<byte[], Integer> scopes = edit.getScopes();
    List<KeyValue> kvs = edit.getKeyValues();
    for (int i = edit.size() - 1; i >= 0; i--) {
        KeyValue kv = kvs.get(i);
        // The scope will be null or empty if
        // there's nothing to replicate in that WALEdit
        if (scopes == null || !scopes.containsKey(kv.getFamily())) {
            kvs.remove(i);
        }
    }
}

From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java

@SuppressWarnings("unchecked")
public <T> T objectFrom(final Result result, final Class<T> hBasePersistanceClass) {
    if (!annotatedClassToAnnotatedHBaseRowKey.containsKey(hBasePersistanceClass)) {
        throw new IllegalArgumentException(
                "Class passed to objectFrom(final Result result, final Class<T> hBasePersistanceClass) must be a correct HBase persistable class! If this class is annotaed with @HBasePersistance please see startup errors for why it might have been excluded. ");
    }/*from   w  w w. j a  v  a2 s  .c  o m*/
    if (result.isEmpty()) {
        return null;
    }
    /*
     * Create new instance of our target class
     */
    final T type = Whitebox.newInstance(hBasePersistanceClass);
    final NavigableMap<byte[], NavigableMap<byte[], byte[]>> columnFamilyResultMap = result.getNoVersionMap();
    /*
     * Map results to fields annotated with @HBaseField
     */
    for (final Field field : annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethod
            .get(hBasePersistanceClass).keySet()) {
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, type,
                TypeHandler.getTypedValue(field.getType(),
                        columnFamilyResultMap.get(columnFamilyNameFromHBaseFieldAnnotatedField(field))
                                .remove(Bytes.toBytes(field.getName()))));
    }
    /*
     * Map results to fields annotated with @HBaseObjectField
     */
    for (final Field field : annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethod
            .get(hBasePersistanceClass).keySet()) {
        ReflectionUtils.makeAccessible(field);
        try {
            /*
             * We may purposely not want to populate certain fields by not including the column family
             */
            final byte[] columnFamily = columnFamilyNameFromHBaseObjectFieldAnnotatedField(field);
            if (columnFamilyResultMap.containsKey(columnFamily)) {
                ReflectionUtils.setField(field, type,
                        field.getAnnotation(HBaseObjectField.class).serializationStategy().deserialize(
                                columnFamilyResultMap.get(columnFamily).remove(Bytes.toBytes(field.getName())),
                                field));
            }
        } catch (Exception e) {
            /*
             *  We serialized this we should be able to de-serialize it. Did the serialization change?
             *  
             *  TODO: store serialization type so we can better guarantee de-serialization
             */
            LOG.error("Could not deserialize " + field.getName() + " for family map name: "
                    + columnFamilyNameFromHBaseObjectFieldAnnotatedField(field)
                    + " Did the serialization (KRYO/JSON) OR field type change from when you serialized the object?",
                    e);
        }
    }
    /*
     * Map results to fields annotated with @HBaseMapField
     */
    mapFieldBlock: {
        if (annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod
                .get(hBasePersistanceClass) != null) {
            final Field field = annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod
                    .get(hBasePersistanceClass).keySet().iterator().next();
            Map<String, String> map;
            if (field.getType().equals(Map.class)) {
                /*
                 *  If the object just calls for a Map give them a TreeMap();
                 */
                map = new TreeMap<String, String>();
            } else {
                /*
                 *  else try to create an instance of the Map class they are using
                 */
                try {
                    map = (Map<String, String>) Whitebox.getConstructor(field.getType())
                            .newInstance((Object[]) null);
                } catch (Exception e) {
                    /*
                     *  Done our best to guard against this but still possible
                     */
                    LOG.error("Could not create new instance of map.", e);
                    break mapFieldBlock;
                }
            }
            for (final Entry<byte[], byte[]> entry : columnFamilyResultMap
                    .get(columnFamilyNameFromHBaseMapFieldAnnotatedField(field)).entrySet()) {
                map.put(Bytes.toString(entry.getKey()), Bytes.toString(entry.getValue()));
            }
            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, type, map);
        }
    }

    return type;

}

From source file:com.google.cloud.dns.testing.LocalDnsHelper.java

/**
 * Lists changes. Next page token is the ID of the last change listed.
 *///www. j  a  va  2 s . c om
@VisibleForTesting
Response listChanges(String projectId, String zoneName, String query) {
    Map<String, Object> options = OptionParsers.parseListChangesOptions(query);
    Response response = checkListOptions(options);
    if (response != null) {
        return response;
    }
    ZoneContainer zoneContainer = findZone(projectId, zoneName);
    if (zoneContainer == null) {
        return Error.NOT_FOUND.response(
                String.format("The 'parameters.managedZone' resource named '%s' does not exist", zoneName));
    }
    // take a sorted snapshot of the current change list
    NavigableMap<Integer, Change> changes = new TreeMap<>();
    for (Change c : zoneContainer.changes()) {
        if (c.getId() != null) {
            changes.put(Integer.valueOf(c.getId()), c);
        }
    }
    String[] fields = (String[]) options.get("fields");
    String sortOrder = (String) options.get("sortOrder");
    String pageToken = (String) options.get("pageToken");
    Integer maxResults = options.get("maxResults") == null ? null
            : Integer.valueOf((String) options.get("maxResults"));
    // as the only supported field is change sequence, we are not reading sortBy
    NavigableSet<Integer> keys;
    if ("descending".equals(sortOrder)) {
        keys = changes.descendingKeySet();
    } else {
        keys = changes.navigableKeySet();
    }
    Integer from = null;
    try {
        from = Integer.valueOf(pageToken);
    } catch (NumberFormatException ex) {
        // ignore page token
    }
    keys = from != null ? keys.tailSet(from, false) : keys;
    NavigableMap<Integer, Change> fragment = from != null && changes.containsKey(from)
            ? changes.tailMap(from, false)
            : changes;
    boolean sizeReached = false;
    boolean hasMorePages = false;
    LinkedList<String> serializedResults = new LinkedList<>();
    String lastChangeId = null;
    for (Integer key : keys) {
        Change change = fragment.get(key);
        if (sizeReached) {
            // we do not add this, just note that there would be more and there should be a token
            hasMorePages = true;
            break;
        } else {
            lastChangeId = change.getId();
            try {
                serializedResults.addLast(jsonFactory.toString(OptionParsers.extractFields(change, fields)));
            } catch (IOException e) {
                return Error.INTERNAL_ERROR.response(
                        String.format("Error when serializing change %s in managed zone %s in project %s",
                                lastChangeId, zoneName, projectId));
            }
        }
        sizeReached = maxResults != null && maxResults.equals(serializedResults.size());
    }
    boolean includePageToken = hasMorePages
            && (fields == null || Arrays.asList(fields).contains("nextPageToken"));
    return toListResponse(serializedResults, "changes", lastChangeId, includePageToken);
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testDescendingMap() {
    K[] keys = getSortedKeys();//from   w  w  w . j  a v a 2s. c o  m
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);

    NavigableMap<K, V> descendingMap = map.descendingMap();
    _assertEquals(descendingMap, map.descendingMap());

    map.put(keys[1], values[1]);
    _assertEquals(map, descendingMap.descendingMap());
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());

    descendingMap.put(keys[2], values[2]);
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());
    _assertEquals(map.entrySet(), descendingMap.descendingMap().entrySet());

    descendingMap.remove(keys[1]);
    _assertEquals(reverseCollection(map.entrySet()), descendingMap.entrySet());

    descendingMap.clear();
    assertEquals(0, descendingMap.size());
    assertEquals(0, map.size());

    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[2], values[2]);
    assertEquals(3, descendingMap.size());

    NavigableMap<K, V> headMap = descendingMap.headMap(keys[1], false);
    assertEquals(1, headMap.size());
    assertTrue(headMap.containsKey(keys[2]));

    NavigableMap<K, V> subMap = descendingMap.subMap(keys[2], true, keys[1], true);
    assertEquals(2, subMap.size());
    assertTrue(subMap.containsKey(keys[1]));
    assertTrue(subMap.containsKey(keys[2]));

    NavigableMap<K, V> tailMap = descendingMap.tailMap(keys[1], false);
    assertEquals(1, tailMap.size());
    assertTrue(tailMap.containsKey(keys[0]));
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testRemoveLjava_lang_Object() {
    K[] keys = getSortedKeys();/*w w w .  j a  v a2 s . c om*/
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    for (int i = 0; i < keys.length; i++) {
        map.put(keys[i], values[i]);
    }

    map.remove(keys[2]);
    assertTrue(!map.containsKey(keys[2]));
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testSubMap_viewPutRemove() {
    K[] keys = getSortedKeys();/*  w  w  w.j  ava 2s  .com*/
    V[] values = getSortedValues();

    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[3], values[3]);

    NavigableMap<K, V> subMap = map.subMap(keys[1], true, keys[3], true);
    try {
        subMap.put(keys[0], values[0]);
        fail();
    } catch (IllegalArgumentException e) {
        // must not insert value outside the range
    }
    assertFalse(subMap.containsKey(keys[0]));
    assertNull(subMap.remove(keys[0]));
    assertTrue(map.containsKey(keys[0]));
    assertEquals(2, subMap.size());
    assertEquals(3, map.size());

    subMap.put(keys[2], values[2]);
    assertEquals(3, subMap.size());
    assertEquals(4, map.size());
    assertTrue(map.containsKey(keys[2]));
    assertTrue(subMap.containsKey(keys[2]));

    subMap.remove(keys[2]);
    assertFalse(map.containsKey(keys[2]));
    assertFalse(subMap.containsKey(keys[2]));

    subMap.clear();
    assertEquals(0, subMap.size());
    assertEquals(1, map.size());
    assertTrue(map.containsKey(keys[0]));
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testHeadMap_viewPutRemove() {
    K[] keys = getSortedKeys();/*from  w  w w.  ja va2  s.co  m*/
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);
    map.put(keys[2], values[2]);
    map.put(keys[3], values[3]);

    NavigableMap<K, V> headMap = map.headMap(keys[2], true);
    try {
        headMap.put(keys[3], values[3]);
        fail();
    } catch (IllegalArgumentException e) {
        // must not insert value outside the range
    }
    headMap.remove(keys[3]);
    assertEquals(2, headMap.size());
    assertEquals(3, map.size());
    assertTrue(map.containsKey(keys[3]));

    headMap.put(keys[1], values[1]);
    assertEquals(3, headMap.size());
    assertEquals(4, map.size());
    assertTrue(map.containsKey(keys[1]));
    assertTrue(headMap.containsKey(keys[1]));

    headMap.remove(keys[1]);
    assertFalse(map.containsKey(keys[1]));
    assertFalse(headMap.containsKey(keys[1]));

    headMap.clear();
    assertEquals(0, headMap.size());
    assertEquals(1, map.size());
    assertTrue(map.containsKey(keys[3]));
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testTailMap_viewPutRemove() {
    K[] keys = getSortedKeys();// ww w .  j a  v a 2  s .  com
    V[] values = getSortedValues();

    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);
    map.put(keys[1], values[1]);
    map.put(keys[3], values[3]);

    NavigableMap<K, V> tailMap = map.tailMap(keys[1], true);
    try {
        tailMap.put(keys[0], values[0]);
        fail();
    } catch (IllegalArgumentException e) {
        // must not insert value outside the range
    }
    tailMap.remove(keys[0]);
    assertEquals(2, tailMap.size());
    assertEquals(3, map.size());
    assertTrue(map.containsKey(keys[0]));

    tailMap.put(keys[2], values[2]);
    assertEquals(3, tailMap.size());
    assertEquals(4, map.size());
    assertTrue(map.containsKey(keys[2]));
    assertTrue(tailMap.containsKey(keys[2]));

    tailMap.remove(keys[2]);
    assertFalse(map.containsKey(keys[2]));
    assertFalse(tailMap.containsKey(keys[2]));

    tailMap.clear();
    assertEquals(0, tailMap.size());
    assertEquals(1, map.size());
    assertTrue(map.containsKey(keys[0]));
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testSubMap_iterator() {
    K[] keys = getSortedKeys();//from   w ww .j a  v  a  2s . co m
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    for (int i = 0; i < keys.length; i++) {
        map.put(keys[i], values[i]);
    }

    assertEquals(keys.length, map.size());

    Map<K, V> subMap = map.subMap(getLessThanMinimumKey(), keys[3]);
    assertEquals(3, subMap.size());

    Set<Map.Entry<K, V>> entrySet = subMap.entrySet();
    assertEquals(3, entrySet.size());
    Iterator<Entry<K, V>> it = entrySet.iterator();
    while (it.hasNext()) {
        Entry<K, V> entry = it.next();
        assertTrue(map.containsKey(entry.getKey()));
        assertTrue(map.containsValue(entry.getValue()));
    }
    try {
        it.next();
        fail("should throw NoSuchElementException");
    } catch (NoSuchElementException expected) {
    }

    Set<K> keySet = subMap.keySet();
    assertEquals(3, keySet.size());
    for (K key : keySet) {
        assertTrue(map.containsKey(key));
    }
}