Example usage for java.util NavigableMap navigableKeySet

List of usage examples for java.util NavigableMap navigableKeySet

Introduction

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

Prototype

NavigableSet<K> navigableKeySet();

Source Link

Document

Returns a NavigableSet view of the keys contained in this map.

Usage

From source file:Main.java

public static void main(String[] args) {
    NavigableMap<Integer, String> map = new TreeMap<Integer, String>();
    map.put(2, "two");
    map.put(1, "one");
    map.put(3, "three");
    System.out.println(map.navigableKeySet() + "\n");

}

From source file:Main.java

public static void main(String args[]) {
    Calendar now = Calendar.getInstance();
    Locale locale = Locale.getDefault();

    Map<String, Integer> names = now.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.LONG, locale);
    NavigableMap<String, Integer> nav = new TreeMap<String, Integer>(names);
    System.out.printf("Whole list:%n%s%n", nav);
    System.out.printf("Map before Sunday: %s%n", nav.navigableKeySet());
}

From source file:edu.umd.honghongie.BooleanRetrievalHBase.java

private Set<Integer> fetchDocumentSet(String term) throws IOException {
    Set<Integer> set = new TreeSet<Integer>();

    Get get = new Get(Bytes.toBytes(term));
    Result result = index.get(get);
    NavigableMap<byte[], byte[]> indexmap = result.getFamilyMap(BooleanRetrievalHBase.CF);
    // get out all column qualifier for a row
    for (byte[] key : indexmap.navigableKeySet()) {
        int docid = Bytes.toInt(key);
        set.add(docid);/* w ww .j  a va  2 s. co m*/
    }

    return set;
}

From source file:com.smartitengineering.cms.spi.impl.type.ContentTypeObjectConverter.java

@Override
public PersistentContentType rowsToObject(Result startRow, ExecutorService executorService) {
    try {// w w  w.j a  v  a  2 s .  c  o  m
        PersistableContentType contentType = SmartContentSPI.getInstance().getPersistableDomainFactory()
                .createPersistableContentType();
        PersistentContentType persistentContentType = new PersistentContentType();
        /*
         * Simple fields
         */
        persistentContentType.setMutableContentType(contentType);
        persistentContentType.setVersion(0l);
        logger.info("::::::::::::::::::::: Converting rowId to ContentTypeId :::::::::::::::::::::");
        contentType.setContentTypeID(getInfoProvider().getIdFromRowId(startRow.getRow()));
        if (logger.isInfoEnabled()) {
            logger.info(new StringBuilder("ContentTypeId ").append(contentType.getContentTypeID()).toString());
        }
        Map<byte[], byte[]> simpleValues = startRow.getFamilyMap(FAMILY_SIMPLE);
        byte[] displayName = simpleValues.remove(CELL_DISPLAY_NAME);
        if (displayName != null) {
            logger.debug("Set display name of the content type!");
            contentType.setDisplayName(Bytes.toString(displayName));
        }
        byte[] primaryFieldName = simpleValues.remove(CELL_PRIMARY_FIELD_NAME);
        if (primaryFieldName != null) {
            final String toString = Bytes.toString(primaryFieldName);
            if (logger.isDebugEnabled()) {
                logger.debug("Set primary field name of the content type!" + toString);
            }
            contentType.setPrimaryFieldName(toString);
        }
        byte[] defTyoe = simpleValues.remove(CELL_DEF_TYPE);
        if (defTyoe != null) {
            final String toString = Bytes.toString(defTyoe);
            if (logger.isDebugEnabled()) {
                logger.debug("Set primary field name of the content type!" + toString);
            }
            contentType.setDefinitionType(ContentType.DefinitionType.valueOf(toString));
        }
        contentType.setEntityTagValue(Bytes.toString(simpleValues.remove(CELL_ENTITY_TAG)));
        logger.debug("Setting creation and last modified date");
        contentType.setCreationDate(Utils.toDate(simpleValues.remove(CELL_CREATION_DATE)));
        contentType.setLastModifiedDate(Utils.toDate(simpleValues.remove(CELL_LAST_MODIFIED_DATE)));
        final byte[] parentId = simpleValues.remove(CELL_PARENT_ID);
        if (parentId != null) {
            logger.debug("Setting parent id");
            contentType.setParent(getInfoProvider().getIdFromRowId(parentId));
        }
        if (!simpleValues.isEmpty()) {
            String displayNamesPrefix = new StringBuilder(CELL_PARAMETERIZED_DISPLAY_NAME_PREFIX).append(':')
                    .toString();
            final byte[] toBytes = Bytes.toBytes(CELL_PARAMETERIZED_DISPLAY_NAME_PREFIX);
            for (Entry<byte[], byte[]> entry : simpleValues.entrySet()) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Extra simple fields Key " + Bytes.toString(entry.getKey()) + " "
                            + Bytes.startsWith(entry.getKey(), toBytes));
                    logger.debug("Extra simple fields Value " + Bytes.toString(entry.getValue()));
                }
                if (Bytes.startsWith(entry.getKey(), toBytes)) {
                    String paramKey = Bytes.toString(entry.getKey()).substring(displayNamesPrefix.length());
                    String paramVal = Bytes.toString(entry.getValue());
                    contentType.getMutableParameterizedDisplayNames().put(paramKey, paramVal);
                }
            }
        }
        if (logger.isDebugEnabled()) {
            final FastDateFormat formatter = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT;
            logger.debug(String.format("Creation date is %s and last modified date is %s",
                    formatter.format(contentType.getCreationDate()),
                    formatter.format(contentType.getLastModifiedDate())));
            logger.debug(String.format("Id is %s and parent id is %s",
                    contentType.getContentTypeID().toString(), ObjectUtils.toString(contentType.getParent())));
        }
        /*
         * Content status
         */
        logger.debug("Form statuses");
        NavigableMap<byte[], byte[]> statusMap = startRow.getFamilyMap(FAMILY_STATUSES);
        int index = 0;
        for (byte[] statusName : statusMap.navigableKeySet()) {
            final String statusNameStr = Bytes.toString(statusName);
            if (logger.isDebugEnabled()) {
                logger.debug(new StringBuilder("Forming content status for ").append(statusNameStr).toString());
            }
            //Value not required as both are the same for status
            MutableContentStatus contentStatus = SmartContentAPI.getInstance().getContentTypeLoader()
                    .createMutableContentStatus();
            contentStatus.setContentTypeID(contentType.getContentTypeID());
            contentStatus.setId(++index);
            contentStatus.setName(statusNameStr);
            contentType.getMutableStatuses().add(contentStatus);
        }
        /*
         * Representations
         */
        logger.debug("Form representations!");
        NavigableMap<byte[], byte[]> representationMap = startRow.getFamilyMap(FAMILY_REPRESENTATIONS);
        Map<String, MutableRepresentationDef> reps = new HashMap<String, MutableRepresentationDef>();
        for (byte[] keyBytes : representationMap.navigableKeySet()) {
            final String key = Bytes.toString(keyBytes);
            if (logger.isDebugEnabled()) {
                logger.debug(new StringBuilder("Work with key ").append(key).toString());
            }
            final int indexOfFirstColon = key.indexOf(':');
            final String repName = key.substring(0, indexOfFirstColon);
            final byte[] qualifier = Bytes.toBytes(key.substring(indexOfFirstColon + 1));
            if (logger.isDebugEnabled()) {
                logger.debug(new StringBuilder("Representation name ").append(repName).toString());
                logger.debug(new StringBuilder("Representation qualifier ").append(Bytes.toString(qualifier))
                        .toString());
            }
            MutableRepresentationDef representationDef = reps.get(repName);
            if (representationDef == null) {
                logger.debug("Creating new representation def and putting to map");
                representationDef = SmartContentAPI.getInstance().getContentTypeLoader()
                        .createMutableRepresentationDef();
                reps.put(repName, representationDef);
                representationDef.setName(repName);
            }
            final byte[] value = representationMap.get(keyBytes);
            fillResourceDef(qualifier, representationDef, value);
        }
        contentType.getMutableRepresentationDefs().addAll(reps.values());
        /*
         * Content Co-Processors
         */
        logger.debug("Form Content Co-Processors!");
        NavigableMap<byte[], byte[]> ccpMap = startRow.getFamilyMap(FAMILY_CCP);
        Map<String, MutableContentCoProcessorDef> ccps = new HashMap<String, MutableContentCoProcessorDef>();
        for (byte[] keyBytes : ccpMap.navigableKeySet()) {
            final String key = Bytes.toString(keyBytes);
            if (logger.isDebugEnabled()) {
                logger.debug(new StringBuilder("CCP Work with key ").append(key).toString());
            }
            final int indexOfFirstColon = key.indexOf(':');
            final String ccpName = key.substring(0, indexOfFirstColon);
            final byte[] qualifier = Bytes.toBytes(key.substring(indexOfFirstColon + 1));
            if (logger.isDebugEnabled()) {
                logger.debug(new StringBuilder("CCP name ").append(ccpName).toString());
                logger.debug(new StringBuilder("CCP qualifier ").append(Bytes.toString(qualifier)).toString());
            }
            MutableContentCoProcessorDef ccpDef = ccps.get(ccpName);
            if (ccpDef == null) {
                logger.debug("Creating new content co processor def and putting to map");
                ccpDef = SmartContentAPI.getInstance().getContentTypeLoader()
                        .createMutableContentCoProcessorDef();
                ccps.put(ccpName, ccpDef);
                ccpDef.setName(ccpName);
            }
            final byte[] value = ccpMap.get(keyBytes);
            if (Arrays.equals(qualifier, CELL_CCP_PHASE)) {
                ccpDef.setPhase(ContentType.ContentProcessingPhase.valueOf(Bytes.toString(value)));
            } else if (Arrays.equals(qualifier, CELL_CCP_PRIORITY)) {
                ccpDef.setPriority(Bytes.toInt(value));
            } else {
                fillResourceDef(qualifier, ccpDef, value);
            }
        }
        List<MutableContentCoProcessorDef> ccpDefs = new ArrayList<MutableContentCoProcessorDef>(ccps.values());
        Collections.sort(ccpDefs, new Comparator<ContentCoProcessorDef>() {

            public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) {
                return o1.getPriority() - o2.getPriority();
            }
        });
        for (MutableContentCoProcessorDef ccpDef : ccpDefs) {
            contentType.addContentCoProcessorDef(ccpDef);
        }
        /*
         * Fields
         */
        NavigableMap<byte[], byte[]> fieldMap = startRow.getFamilyMap(FAMILY_FIELDS);
        //From a map of all cells form a map of cells by field name
        Map<String, Map<String, byte[]>> fieldsByName = new LinkedHashMap<String, Map<String, byte[]>>();
        Utils.organizeByPrefix(fieldMap, fieldsByName, ':');
        for (String fieldName : fieldsByName.keySet()) {
            final MutableFieldDef fieldDef = SmartContentAPI.getInstance().getContentTypeLoader()
                    .createMutableFieldDef();
            final Map<String, byte[]> fieldCells = fieldsByName.get(fieldName);
            populateFieldDef(fieldDef, fieldName, fieldCells);
            contentType.getMutableFieldDefs().add(fieldDef);
        }
        /*
         * Variants of content type
         */
        Map<byte[], byte[]> variants = startRow.getFamilyMap(FAMILY_TYPE_REPRESENTATIONS);
        if (variants != null && !variants.isEmpty()) {
            final Map<MediaType, String> variantMap = new HashMap<MediaType, String>(variants.size());
            for (byte[] mediaType : variants.keySet()) {
                variantMap.put(MediaType.fromString(Bytes.toString(mediaType)),
                        Bytes.toString(variants.get(mediaType)));
            }
            contentType.setRepresentations(variantMap);
            contentType.setFromPersistentStorage(true);
        }
        return persistentContentType;
    } catch (Exception ex) {
        logger.warn("Error converting result to content type, throwing exception...", ex);
        throw new RuntimeException(ex);
    }
}

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

/**
 * Lists changes. Next page token is the ID of the last change listed.
 *///  ww w  . ja v a 2 s  .c  o m
@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

@SuppressWarnings("ModifyingCollectionWithItself")
public void testNavigableKeySet_viewPut() {
    K[] keys = getSortedKeys();/*from  www  .  j  a  va 2 s. c om*/
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();
    map.put(keys[0], values[0]);

    Set<K> keySet = map.navigableKeySet();
    assertEquals(1, keySet.size());
    map.put(keys[1], values[1]);
    assertEquals(2, keySet.size());

    try {
        keySet.add(keys[2]);
        fail();
    } catch (Exception e) {
        // java.util.NavigableMap.navigableKeySet() does not support add
    }
    try {
        keySet.addAll(keySet);
        fail();
    } catch (Exception e) {
        // java.util.NavigableMap.navigableKeySet() does not support addAll
    }
}

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

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

    Set<K> keySet = map.navigableKeySet();
    assertEquals(2, keySet.size());
    map.remove(keys[1]);
    assertEquals(1, keySet.size());

    map.put(keys[1], values[1]);
    keySet.remove(keys[0]);
    assertEquals(1, map.size());
    assertEquals(1, keySet.size());
    assertEquals(keys[1], keySet.iterator().next());

    keySet.clear();
    _assertEmpty(map);
}

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

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

    Set<K> keySet = map.navigableKeySet();
    _assertEquals(keySet, map.navigableKeySet());

    map.put(keys[1], values[1]);
    map.put(keys[2], values[2]);
    _assertEquals(map.navigableKeySet(), keySet);
    _assertEquals(keySet, keySet);

    try {
        keySet.add(keys[3]);
        fail("should throw UnsupportedOperationException");
    } catch (UnsupportedOperationException expected) {
    }
    try {
        keySet.add(null);
        fail("should throw UnsupportedOperationException");
    } catch (UnsupportedOperationException expected) {
    }
    try {
        keySet.addAll(null);
        fail("should throw NullPointerException");
    } catch (NullPointerException expected) {
    }
    Collection<K> collection = new ArrayList<K>();
    keySet.addAll(collection);
    try {
        collection.add(keys[3]);
        keySet.addAll(collection);
        fail("should throw UnsupportedOperationException");
    } catch (UnsupportedOperationException expected) {
    }

    Iterator<K> iter = keySet.iterator();
    iter.next();
    iter.remove();
    assertFalse(map.containsKey(keys[0]));

    collection = new ArrayList<K>();
    collection.add(keys[2]);
    keySet.retainAll(collection);
    assertEquals(1, map.size());
    assertTrue(keySet.contains(keys[2]));

    keySet.removeAll(collection);
    _assertEmpty(map);

    map.put(keys[0], values[0]);
    assertEquals(1, map.size());
    assertTrue(keySet.contains(keys[0]));

    keySet.clear();
    _assertEmpty(map);
}

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

@SuppressWarnings("unchecked")
public void testNavigableKeySet_iterator() {
    NavigableMap<K, V> map = createNavigableMap();
    map.putAll(makeFullMap());/*  w  ww. ja  v  a 2  s. c  o m*/
    resetFull();
    ArrayList<K> keys = new ArrayList<K>();
    for (Object key : getSampleKeys()) {
        keys.add((K) key);
    }
    Comparator<? super K> cmp = ((TreeMap<K, V>) map).comparator();
    Collections.sort(keys, cmp);
    Iterator<K> it = map.navigableKeySet().iterator();
    for (K key : keys) {
        assertTrue(it.hasNext());
        K rem = it.next();
        it.remove();
        assertEquals(key, rem);
    }
    try {
        it.next();
        fail("should throw NoSuchElementException");
    } catch (NoSuchElementException expected) {
    }
    _assertEmpty(map);
}

From source file:org.apache.hadoop.hbase.coprocessor.TestCoprocessorEndpoint.java

@Test
public void testCoprocessorService() throws Throwable {
    HTable table = new HTable(util.getConfiguration(), TEST_TABLE);
    NavigableMap<HRegionInfo, ServerName> regions = table.getRegionLocations();

    final TestProtos.EchoRequestProto request = TestProtos.EchoRequestProto.newBuilder().setMessage("hello")
            .build();//from w  ww .  ja v a 2 s.com
    final Map<byte[], String> results = Collections
            .synchronizedMap(new TreeMap<byte[], String>(Bytes.BYTES_COMPARATOR));
    try {
        // scan: for all regions
        final RpcController controller = new ServerRpcController();
        table.coprocessorService(TestRpcServiceProtos.TestProtobufRpcProto.class, ROWS[0],
                ROWS[ROWS.length - 1],
                new Batch.Call<TestRpcServiceProtos.TestProtobufRpcProto, TestProtos.EchoResponseProto>() {
                    public TestProtos.EchoResponseProto call(TestRpcServiceProtos.TestProtobufRpcProto instance)
                            throws IOException {
                        LOG.debug("Default response is " + TestProtos.EchoRequestProto.getDefaultInstance());
                        BlockingRpcCallback<TestProtos.EchoResponseProto> callback = new BlockingRpcCallback<TestProtos.EchoResponseProto>();
                        instance.echo(controller, request, callback);
                        TestProtos.EchoResponseProto response = callback.get();
                        LOG.debug("Batch.Call returning result " + response);
                        return response;
                    }
                }, new Batch.Callback<TestProtos.EchoResponseProto>() {
                    public void update(byte[] region, byte[] row, TestProtos.EchoResponseProto result) {
                        assertNotNull(result);
                        assertEquals("hello", result.getMessage());
                        results.put(region, result.getMessage());
                    }
                });
        for (Map.Entry<byte[], String> e : results.entrySet()) {
            LOG.info("Got value " + e.getValue() + " for region " + Bytes.toStringBinary(e.getKey()));
        }
        assertEquals(3, results.size());
        for (HRegionInfo info : regions.navigableKeySet()) {
            LOG.info("Region info is " + info.getRegionNameAsString());
            assertTrue(results.containsKey(info.getRegionName()));
        }
        results.clear();

        // scan: for region 2 and region 3
        table.coprocessorService(TestRpcServiceProtos.TestProtobufRpcProto.class, ROWS[rowSeperator1],
                ROWS[ROWS.length - 1],
                new Batch.Call<TestRpcServiceProtos.TestProtobufRpcProto, TestProtos.EchoResponseProto>() {
                    public TestProtos.EchoResponseProto call(TestRpcServiceProtos.TestProtobufRpcProto instance)
                            throws IOException {
                        LOG.debug("Default response is " + TestProtos.EchoRequestProto.getDefaultInstance());
                        BlockingRpcCallback<TestProtos.EchoResponseProto> callback = new BlockingRpcCallback<TestProtos.EchoResponseProto>();
                        instance.echo(controller, request, callback);
                        TestProtos.EchoResponseProto response = callback.get();
                        LOG.debug("Batch.Call returning result " + response);
                        return response;
                    }
                }, new Batch.Callback<TestProtos.EchoResponseProto>() {
                    public void update(byte[] region, byte[] row, TestProtos.EchoResponseProto result) {
                        assertNotNull(result);
                        assertEquals("hello", result.getMessage());
                        results.put(region, result.getMessage());
                    }
                });
        for (Map.Entry<byte[], String> e : results.entrySet()) {
            LOG.info("Got value " + e.getValue() + " for region " + Bytes.toStringBinary(e.getKey()));
        }
        assertEquals(2, results.size());
    } finally {
        table.close();
    }
}