java.util.NavigableMap Java Examples

The following examples show how to use java.util.NavigableMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HBaseLogByRowkeyReader.java    From eagle with Apache License 2.0 6 votes vote down vote up
private InternalLog buildLog(Result result) {
    final InternalLog log = new InternalLog();
    final byte[] rowkey = result.getRow();
    log.setEncodedRowkey(EagleBase64Wrapper.encodeByteArray2URLSafeString(rowkey));
    long timestamp = ByteUtil.bytesToLong(rowkey, 4);
    timestamp = Long.MAX_VALUE - timestamp;
    log.setTimestamp(timestamp);
    Map<String, byte[]> qualifierValues = new HashMap<String, byte[]>();
    log.setQualifierValues(qualifierValues);
    NavigableMap<byte[], byte[]> map = result.getFamilyMap(this.columnFamily.getBytes());
    if (map == null) {
        throw new NoSuchRowException(EagleBase64Wrapper.encodeByteArray2URLSafeString(rowkey));
    }
    for (Map.Entry<byte[], byte[]> entry : map.entrySet()) {
        byte[] qualifier = entry.getKey();
        byte[] value = entry.getValue();
        qualifierValues.put(new String(qualifier), value);
    }
    return log;
}
 
Example #2
Source File: ArrayStoreConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public NavigableMap<String, IndexableField> encode(LuceneContext context, String path, Field field, LuceneStore annotation, Type type, Object instance) {
    NavigableMap<String, IndexableField> indexables = new TreeMap<>();
    Class<?> componentClass = null;
    Type componentType = null;
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
        componentType = genericArrayType.getGenericComponentType();
        componentClass = TypeUtility.getRawType(componentType, null);
    } else {
        Class<?> clazz = TypeUtility.getRawType(type, null);
        componentType = clazz.getComponentType();
        componentClass = clazz.getComponentType();
    }
    Specification specification = Specification.getSpecification(componentClass);
    StoreConverter converter = context.getStoreConverter(specification);
    int size = Array.getLength(instance);
    IndexableField indexable = new StoredField(path + ".size", size);
    indexables.put(path + ".size", indexable);
    for (int index = 0; index < size; index++) {
        Object element = Array.get(instance, index);
        indexables.putAll(converter.encode(context, path + "[" + index + "]", field, annotation, componentType, element));
    }
    return indexables;
}
 
Example #3
Source File: StorageUtils.java    From amodeus with GNU General Public License v2.0 6 votes vote down vote up
/** @return {@link NavigableMap} to with {@link Integer} and {@link File} for
 *         the first available iteration. */
public NavigableMap<Integer, File> getFirstAvailableIteration() {
    if (!directory.isDirectory()) { // no simobj directory
        System.out.println("no files found");
        return Collections.emptyNavigableMap();
    }

    File[] files = Stream.of(directory.listFiles()).sorted().toArray(File[]::new);

    if (files.length == 0) {
        System.out.println("no files found");
        return Collections.emptyNavigableMap();
    }

    File lastIter = files[files.length - 1];
    System.out.println("loading last Iter = " + lastIter);
    return getFrom(lastIter);
}
 
Example #4
Source File: TreeSubMapTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testDescendingSubMapContents2() {
    NavigableMap map = dmap5();
    SortedMap sm = map.subMap(m2, m3);
    assertEquals(1, sm.size());
    assertEquals(m2, sm.firstKey());
    assertEquals(m2, sm.lastKey());
    assertFalse(sm.containsKey(m1));
    assertTrue(sm.containsKey(m2));
    assertFalse(sm.containsKey(m3));
    assertFalse(sm.containsKey(m4));
    assertFalse(sm.containsKey(m5));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(m2, k);
    assertFalse(i.hasNext());
    Iterator j = sm.keySet().iterator();
    j.next();
    j.remove();
    assertFalse(map.containsKey(m2));
    assertEquals(4, map.size());
    assertEquals(0, sm.size());
    assertTrue(sm.isEmpty());
    assertSame(sm.remove(m3), null);
    assertEquals(4, map.size());
}
 
Example #5
Source File: EmptyNavigableMap.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testTailMapRanges(String description, NavigableMap navigableMap) {
    NavigableMap subMap = navigableMap.tailMap(BigInteger.ONE, true);

    // same subset
    subMap.tailMap(BigInteger.ONE, true);

    // slightly smaller
    NavigableMap ns = subMap.tailMap(BigInteger.ONE, false);

    // slight exapansion
    assertThrows(() -> {
        ns.tailMap(BigInteger.ONE, true);
    },
        IllegalArgumentException.class,
        description + ": Expansion should not be allowed");

    // much smaller
    subMap.tailMap(isDescending(subMap) ? BigInteger.ZERO : BigInteger.TEN, false);
}
 
Example #6
Source File: EmptyNavigableMap.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testheadMapRanges(String description, NavigableMap navigableMap) {
    NavigableMap subMap = navigableMap.headMap(BigInteger.ONE, true);

    // same subset
    subMap.headMap(BigInteger.ONE, true);

    // slightly smaller
    NavigableMap ns = subMap.headMap(BigInteger.ONE, false);

    // slight exapansion
    assertThrows(() -> {
        ns.headMap(BigInteger.ONE, true);
    },
        IllegalArgumentException.class,
        description + ": Expansion should not be allowed");

    // much smaller
    subMap.headMap(isDescending(subMap) ? BigInteger.TEN : BigInteger.ZERO, true);
}
 
Example #7
Source File: TestCellUtil.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Was overflowing if 100k or so lists of cellscanners to return.
 */
@Test
public void testCreateCellScannerOverflow() throws IOException {
  consume(doCreateCellScanner(1, 1), 1);
  consume(doCreateCellScanner(3, 0), 0);
  consume(doCreateCellScanner(3, 3), 3 * 3);
  consume(doCreateCellScanner(0, 1), 0);
  // Do big number. See HBASE-11813 for why.
  final int hundredK = 100000;
  consume(doCreateCellScanner(hundredK, 0), 0);
  consume(doCreateCellArray(1), 1);
  consume(doCreateCellArray(0), 0);
  consume(doCreateCellArray(3), 3);
  List<CellScannable> cells = new ArrayList<>(hundredK);
  for (int i = 0; i < hundredK; i++) {
    cells.add(new TestCellScannable(1));
  }
  consume(CellUtil.createCellScanner(cells), hundredK);
  NavigableMap<byte [], List<Cell>> m = new TreeMap<>(Bytes.BYTES_COMPARATOR);
  List<Cell> cellArray = new ArrayList<>(hundredK);
  for (int i = 0; i < hundredK; i++) {
    cellArray.add(new TestCell(i));
  }
  m.put(new byte [] {'f'}, cellArray);
  consume(CellUtil.createCellScanner(m), hundredK);
}
 
Example #8
Source File: DataSourceTable.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void writeSourceInfo(NavigableMap<DataKey, DataValue> map, OutputStream outStream)
    throws IOException {
  int sourceNumber = 0;
  LinkedList<DataSource> sourceQueue =
      map.values()
          .stream()
          .map(VALUE_TO_SOURCE)
          .collect(Collectors.toCollection(LinkedList::new));
  while (!sourceQueue.isEmpty()) {
    DataSource source = sourceQueue.pop();
    if (!sourceTable.containsKey(source)) {
      sourceTable.put(source, sourceNumber);
      ++sourceNumber;
      sourceQueue.addAll(source.overrides());
    }
  }
  for (DataSource dataSource : sourceTable.keySet()) {
    ProtoSource.newBuilder()
        .setFilename(dataSource.getPath().toString())
        .addAllOverwritten(sourcesToIds(dataSource.overrides()))
        .build()
        .writeDelimitedTo(outStream);
  }
}
 
Example #9
Source File: LogDataAdapter.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<Map<String, String>> handleQueryResult(Object result, DataStoreMsg msg,
        DataStoreConnection connection) {

    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    Map<String, String> map = null;
    for (NavigableMap<byte[], byte[]> entrys : (List<NavigableMap<byte[], byte[]>>) result) {
        map = new HashMap<String, String>();
        for (Entry<byte[], byte[]> entry : entrys.entrySet()) {
            map.put(new String(entry.getKey()), new String(entry.getValue()));
        }
        list.add(map);
    }
    return list;
}
 
Example #10
Source File: EmptyNavigableMap.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testSubMapRanges(String description, NavigableMap navigableMap) {
    Object first = isDescending(navigableMap) ? BigInteger.TEN : BigInteger.ZERO;
    Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;

    NavigableMap subMap = navigableMap.subMap(first, true, last, true);

    // same subset
    subMap.subMap(first, true, last, true);

    // slightly smaller
    NavigableMap ns = subMap.subMap(first, false, last, false);
    // slight exapansion
    assertThrows(() -> {
        ns.subMap(first, true, last, true);
    },
        IllegalArgumentException.class,
        description + ": Expansion should not be allowed");

    // much smaller
    subMap.subMap(first, false, BigInteger.ONE, false);
}
 
Example #11
Source File: NoFileSortedOplog.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@Override
public SortedIterator<ByteBuffer> scan(
    byte[] from, boolean fromInclusive, 
    byte[] to, boolean toInclusive,
    boolean ascending,
    MetadataFilter filter) {

  if (filter == null || filter.accept(metadata.get(filter.getName()))) {
    NavigableMap<byte[],byte[]> subset = ascending ? data.get() : data.get().descendingMap();
    if (from == null && to == null) {
      // we're good
    } else if (from == null) {
      subset = subset.headMap(to, toInclusive);
    } else if (to == null) {
      subset = subset.tailMap(from, fromInclusive);
    } else {
      subset = subset.subMap(from, fromInclusive, to, toInclusive);
    }
    return new BufferIterator(subset.entrySet().iterator());
  }
  return new BufferIterator(Collections.<byte[], byte[]>emptyMap().entrySet().iterator());
}
 
Example #12
Source File: Maps.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Returns a view of the portion of {@code map} whose keys are contained by {@code range}.
 *
 * <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely
 * {@link NavigableMap#subMap(Object, boolean, Object, boolean) subMap()},
 * {@link NavigableMap#tailMap(Object, boolean) tailMap()}, and
 * {@link NavigableMap#headMap(Object, boolean) headMap()}) to actually construct the view.
 * Consult these methods for a full description of the returned view's behavior.
 *
 * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
 * ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a
 * {@link Comparator}, which can violate the natural ordering. Using this method (or in general
 * using {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined
 * behavior.
 *
 * @since 20.0
 */

@Beta
@GwtIncompatible // NavigableMap
public static <K extends Comparable<? super K>, V> NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) {
  if (map.comparator() != null && map.comparator() != Ordering.natural()
      && range.hasLowerBound()
      && range.hasUpperBound()) {
    checkArgument(map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0, "map is using a custom comparator which is inconsistent with the natural ordering.");
  }
  if (range.hasLowerBound() && range.hasUpperBound()) {
    return map.subMap(
      range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED,
      range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
  } else if (range.hasLowerBound()) {
    return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
  } else if (range.hasUpperBound()) {
    return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
  }
  return checkNotNull(map);
}
 
Example #13
Source File: EmptyNavigableMap.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testSubMapRanges(String description, NavigableMap navigableMap) {
    Object first = isDescending(navigableMap) ? BigInteger.TEN : BigInteger.ZERO;
    Object last = (BigInteger.ZERO == first) ? BigInteger.TEN : BigInteger.ZERO;

    NavigableMap subMap = navigableMap.subMap(first, true, last, true);

    // same subset
    subMap.subMap(first, true, last, true);

    // slightly smaller
    NavigableMap ns = subMap.subMap(first, false, last, false);
    // slight exapansion
    assertThrows(() -> {
        ns.subMap(first, true, last, true);
    },
        IllegalArgumentException.class,
        description + ": Expansion should not be allowed");

    // much smaller
    subMap.subMap(first, false, BigInteger.ONE, false);
}
 
Example #14
Source File: CodeFoldingSideBar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Sets outlines of all children to 'active'. Assuming yFrom and yTo are from-to Y-coordinates of the parent
 * fold, it finds all nested folds (folds, which are in between yFrom and yTo) and changes their in/out lines
 * as active.
 * The method returns Y start coordinate of the 1st child found.
 * 
 * @param infos fold infos collected so far
 * @param yFrom upper Y-coordinate of the parent fold
 * @param yTo lower Y-coordinate of the parent fold
 * @param level level of the parent fold
 * @return Y-coordinate of the 1st child.
 */
private int markDeepChildrenActive(NavigableMap<Integer, PaintInfo> infos, int yFrom, int yTo, int level) {
    int result = Integer.MAX_VALUE;
    Map<Integer, PaintInfo> m = infos.subMap(yFrom, yTo);
    for (Map.Entry<Integer, PaintInfo> me : m.entrySet()) {
        PaintInfo pi = me.getValue();
        int y = pi.getPaintY();
        if (y > yFrom && y < yTo) {
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.log(Level.FINEST, "Marking chind as active: {0}", pi);
            }
            pi.markActive(false, true, true);
            if (y < result) {
                y = result;
            }
        }
    }
    return result;
}
 
Example #15
Source File: BeaconBlocksByRangeMessageHandler.java    From teku with Apache License 2.0 6 votes vote down vote up
RequestState(
    final UnsignedLong startSlot,
    final UnsignedLong step,
    final UnsignedLong count,
    final UnsignedLong headSlot,
    final NavigableMap<UnsignedLong, Bytes32> knownBlockRoots,
    final ResponseCallback<SignedBeaconBlock> callback) {
  this.currentSlot = startSlot;
  this.knownBlockRoots = knownBlockRoots;
  // Minus 1 to account for sending the block at startSlot.
  // We only decrement this when moving to the next slot but we're already at the first slot
  this.remainingBlocks = count.minus(ONE);
  this.step = step;
  this.headSlot = headSlot;
  this.callback = callback;
}
 
Example #16
Source File: ConcurrentSkipListMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Submaps of submaps subdivide correctly
 */
public void testRecursiveSubMaps() throws Exception {
    int mapSize = expensiveTests ? 1000 : 100;
    Class cl = ConcurrentSkipListMap.class;
    NavigableMap<Integer, Integer> map = newMap(cl);
    bs = new BitSet(mapSize);

    populate(map, mapSize);
    check(map,                 0, mapSize - 1, true);
    check(map.descendingMap(), 0, mapSize - 1, false);

    mutateMap(map, 0, mapSize - 1);
    check(map,                 0, mapSize - 1, true);
    check(map.descendingMap(), 0, mapSize - 1, false);

    bashSubMap(map.subMap(0, true, mapSize, false),
               0, mapSize - 1, true);
}
 
Example #17
Source File: ConcurrentSkipListMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testSubMapContents2() {
    ConcurrentSkipListMap map = map5();
    NavigableMap sm = map.subMap(two, true, three, false);
    assertEquals(1, sm.size());
    assertEquals(two, sm.firstKey());
    assertEquals(two, sm.lastKey());
    assertFalse(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertFalse(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    assertFalse(i.hasNext());
    Iterator r = sm.descendingKeySet().iterator();
    k = (Integer)(r.next());
    assertEquals(two, k);
    assertFalse(r.hasNext());

    Iterator j = sm.keySet().iterator();
    j.next();
    j.remove();
    assertFalse(map.containsKey(two));
    assertEquals(4, map.size());
    assertEquals(0, sm.size());
    assertTrue(sm.isEmpty());
    assertSame(sm.remove(three), null);
    assertEquals(4, map.size());
}
 
Example #18
Source File: EmptyNavigableMap.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests that the comparator is {@code null}.
 */
@Test(dataProvider = "NavigableMap<?,?>", dataProviderClass = EmptyNavigableMap.class)
public void testComparatorIsNull(String description, NavigableMap<?,?> navigableMap) {
    Comparator comparator = navigableMap.comparator();

    assertTrue(comparator == null || comparator == Collections.reverseOrder(), description + ": Comparator (" + comparator + ") is not null.");
}
 
Example #19
Source File: TzdbZoneRulesProvider.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
@Override
protected NavigableMap<String, ZoneRules> provideVersions(String zoneId) {
    TreeMap<String, ZoneRules> map = new TreeMap<>();
    ZoneRules rules = getRules(zoneId, false);
    if (rules != null) {
        map.put(versionId, rules);
    }
    return map;
}
 
Example #20
Source File: MapCreatorImpl.java    From boon with Apache License 2.0 5 votes vote down vote up
@Override
public NavigableMap createNavigableMap( Class<?> keyType ) {
    if ( keyType == String.class ) {
        return new JavaUtilNavigableMap();
    } else {
        return new JavaUtilNavigableMap();
    }
}
 
Example #21
Source File: TreeSubMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * subMap returns map with keys in requested range
 */
public void testSubMapContents() {
    NavigableMap map = map5();
    SortedMap sm = map.subMap(two, four);
    assertEquals(two, sm.firstKey());
    assertEquals(three, sm.lastKey());
    assertEquals(2, sm.size());
    assertFalse(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertTrue(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    k = (Integer)(i.next());
    assertEquals(three, k);
    assertFalse(i.hasNext());
    Iterator j = sm.keySet().iterator();
    j.next();
    j.remove();
    assertFalse(map.containsKey(two));
    assertEquals(4, map.size());
    assertEquals(1, sm.size());
    assertEquals(three, sm.firstKey());
    assertEquals(three, sm.lastKey());
    assertEquals("C", sm.remove(three));
    assertTrue(sm.isEmpty());
    assertEquals(3, map.size());
}
 
Example #22
Source File: IndexedTreeMap.java    From IslamicLibraryAndroid with GNU General Public License v3.0 5 votes vote down vote up
public NavigableMap<K, V> tailMap(@NonNull K fromKey, boolean inclusive) {
    if (!inRange(fromKey, inclusive))
        throw new IllegalArgumentException("fromKey out of range");
    return new DescendingSubMap(m,
            fromStart, lo, loInclusive,
            false, fromKey, inclusive);
}
 
Example #23
Source File: TreeSubMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps with same contents are equal
 */
public void testEquals() {
    NavigableMap map1 = map5();
    NavigableMap map2 = map5();
    assertEquals(map1, map2);
    assertEquals(map2, map1);
    map1.clear();
    assertFalse(map1.equals(map2));
    assertFalse(map2.equals(map1));
}
 
Example #24
Source File: TreeSubMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Maps with same contents are equal
 */
public void testEquals() {
    NavigableMap map1 = map5();
    NavigableMap map2 = map5();
    assertEquals(map1, map2);
    assertEquals(map2, map1);
    map1.clear();
    assertFalse(map1.equals(map2));
    assertFalse(map2.equals(map1));
}
 
Example #25
Source File: WALUtil.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Write a flush marker indicating a start / abort or a complete of a region flush
 * <p/>
 * This write is for internal use only. Not for external client consumption.
 */
public static WALKeyImpl writeFlushMarker(WAL wal, NavigableMap<byte[], Integer> replicationScope,
  RegionInfo hri, final FlushDescriptor f, boolean sync, MultiVersionConcurrencyControl mvcc)
  throws IOException {
  WALKeyImpl walKey = doFullMarkerAppendTransaction(wal, replicationScope, hri,
    WALEdit.createFlushWALEdit(hri, f), mvcc, null, sync);
  if (LOG.isTraceEnabled()) {
    LOG.trace("Appended flush marker " + TextFormat.shortDebugString(f));
  }
  return walKey;
}
 
Example #26
Source File: ValidationRules.java    From hadoop-arch-book with Apache License 2.0 5 votes vote down vote up
public static ValidationRules buildValidationRules(NavigableMap<byte[], byte[]> familyMap) throws Exception {

      if (familyMap != null) {
        byte[] bytes = familyMap.get(HBaseTableMetaModel.validationRulesRowKey);

        return new ValidationRules(Bytes.toString(bytes));
      } else {
        LOG.warn("No Validation Rules Found in HBase");
        return new ValidationRules();
      }
    }
 
Example #27
Source File: SnapshotCodecV4.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
@Override
protected NavigableMap<Long, TransactionManager.InProgressTx> decodeInProgress(BinaryDecoder decoder)
    throws IOException {

  int size = decoder.readInt();
  NavigableMap<Long, TransactionManager.InProgressTx> inProgress = Maps.newTreeMap();
  while (size != 0) { // zero denotes end of list as per AVRO spec
    for (int remaining = size; remaining > 0; --remaining) {
      long txId = decoder.readLong();
      long expiration = decoder.readLong();
      long visibilityUpperBound = decoder.readLong();
      int txTypeIdx = decoder.readInt();
      TransactionManager.InProgressType txType;
      try {
        txType = TransactionManager.InProgressType.values()[txTypeIdx];
      } catch (ArrayIndexOutOfBoundsException e) {
        throw new IOException("Type enum ordinal value is out of range: " + txTypeIdx);
      }
      // read checkpoint tx IDs
      int checkpointPointerSize = decoder.readInt();
      LongArrayList checkpointPointers = new LongArrayList(checkpointPointerSize);
      while (checkpointPointerSize != 0) {
        for (int checkpointRemaining = checkpointPointerSize; checkpointRemaining > 0; --checkpointRemaining) {
          checkpointPointers.add(decoder.readLong());
        }
        checkpointPointerSize = decoder.readInt();
      }
      inProgress.put(txId,
          new TransactionManager.InProgressTx(visibilityUpperBound, expiration, txType, checkpointPointers));
    }
    size = decoder.readInt();
  }
  return inProgress;
}
 
Example #28
Source File: CollectionFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create the most appropriate map for the given map type.
 * <p><strong>Warning</strong>: Since the parameterized type {@code K}
 * is not bound to the supplied {@code keyType}, type safety cannot be
 * guaranteed if the desired {@code mapType} is {@link EnumMap}. In such
 * scenarios, the caller is responsible for ensuring that the {@code keyType}
 * is an enum type matching type {@code K}. As an alternative, the caller
 * may wish to treat the return value as a raw map or map keyed by
 * {@link Object}. Similarly, type safety cannot be enforced if the
 * desired {@code mapType} is {@link MultiValueMap}.
 * @param mapType the desired type of the target map; never {@code null}
 * @param keyType the map's key type, or {@code null} if unknown
 * (note: only relevant for {@link EnumMap} creation)
 * @param capacity the initial capacity
 * @return a new map instance
 * @since 4.1.3
 * @see java.util.LinkedHashMap
 * @see java.util.TreeMap
 * @see org.springframework.util.LinkedMultiValueMap
 * @see java.util.EnumMap
 * @throws IllegalArgumentException if the supplied {@code mapType} is
 * {@code null}; or if the desired {@code mapType} is {@link EnumMap} and
 * the supplied {@code keyType} is not a subtype of {@link Enum}
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public static <K, V> Map<K, V> createMap(Class<?> mapType, Class<?> keyType, int capacity) {
	Assert.notNull(mapType, "Map type must not be null");
	if (mapType.isInterface()) {
		if (Map.class == mapType) {
			return new LinkedHashMap<K, V>(capacity);
		}
		else if (SortedMap.class == mapType || NavigableMap.class == mapType) {
			return new TreeMap<K, V>();
		}
		else if (MultiValueMap.class == mapType) {
			return new LinkedMultiValueMap();
		}
		else {
			throw new IllegalArgumentException("Unsupported Map interface: " + mapType.getName());
		}
	}
	else if (EnumMap.class == mapType) {
		Assert.notNull(keyType, "Cannot create EnumMap for unknown key type");
		return new EnumMap(asEnumType(keyType));
	}
	else {
		if (!Map.class.isAssignableFrom(mapType)) {
			throw new IllegalArgumentException("Unsupported Map type: " + mapType.getName());
		}
		try {
			return (Map<K, V>) mapType.newInstance();
		}
		catch (Throwable ex) {
			throw new IllegalArgumentException("Could not instantiate Map type: " + mapType.getName(), ex);
		}
	}
}
 
Example #29
Source File: UserSettingsClient.java    From metron with Apache License 2.0 5 votes vote down vote up
public Map<String, String> getAllUserSettings(Result result) {
  if (result == null) {
    return new HashMap<>();
  }
  NavigableMap<byte[], byte[]> columns = result.getFamilyMap(cf);
  if(columns == null || columns.size() == 0) {
    return new HashMap<>();
  }
  Map<String, String> userSettingsMap = new HashMap<>();
  for(Map.Entry<byte[], byte[]> column: columns.entrySet()) {
    userSettingsMap.put(new String(column.getKey(), StandardCharsets.UTF_8), new String(column.getValue(), StandardCharsets.UTF_8));
  }
  return userSettingsMap;
}
 
Example #30
Source File: TreeRangeSet.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private SubRangeSetRangesByLowerBound(
    Range<Cut<C>> lowerBoundWindow,
    Range<C> restriction,
    NavigableMap<Cut<C>, Range<C>> rangesByLowerBound) {
  this.lowerBoundWindow = checkNotNull(lowerBoundWindow);
  this.restriction = checkNotNull(restriction);
  this.rangesByLowerBound = checkNotNull(rangesByLowerBound);
  this.rangesByUpperBound = new RangesByUpperBound<C>(rangesByLowerBound);
}