Java 类java.util.AbstractMap 实例源码

项目:firebase-admin-java    文件:ArraySortedMap.java   
private Iterator<Map.Entry<K, V>> iterator(final int pos, final boolean reverse) {
  return new Iterator<Map.Entry<K, V>>() {
    int currentPos = pos;

    @Override
    public boolean hasNext() {
      return reverse ? currentPos >= 0 : currentPos < keys.length;
    }

    @Override
    public Map.Entry<K, V> next() {
      final K key = keys[currentPos];
      final V value = values[currentPos];
      currentPos = reverse ? currentPos - 1 : currentPos + 1;
      return new AbstractMap.SimpleImmutableEntry<>(key, value);
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException("Can't remove elements from ImmutableSortedMap");
    }
  };
}
项目:joal    文件:BitTorrentClientConfigTest.java   
@Test
public void shouldBuildClient() {
    final String query = "info_hash={infohash}&peer_id={peerid}&supportcrypto=1&port={port}&azudp={port}&uploaded={uploaded}&downloaded={downloaded}&left={left}&corrupt=0&event={event}&numwant={numwant}&no_peer_id=1&compact=1&key={key}&azver=3";
    final List<BitTorrentClientConfig.HttpHeader> requestHeaders = Arrays.asList(
            new HttpHeader("User-Agent", "Azureus 5.7.5.0;{os};1.8.0_66"),
            new HttpHeader("Connection", "close"),
            new HttpHeader("Accept-Encoding", "gzip"),
            new HttpHeader("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
    );

    final PeerIdGenerator peerIdGenerator = PeerIdGeneratorTest.createDefault();
    final KeyGenerator keyGenerator = KeyGeneratorTest.createDefault();
    final BitTorrentClientConfig config = new BitTorrentClientConfig(peerIdGenerator, query, keyGenerator, defaultUrlEncoder, requestHeaders, 200, 0);

    final BitTorrentClient client = config.createClient();
    assertThat(client.getHeaders()).isEqualTo(requestHeaders.stream()
            .map(header -> new AbstractMap.SimpleEntry<>(header.getName(), header.getValue()))
            .collect(Collectors.toList())
    );
    assertThat(client.getQuery()).isEqualTo(query);
    //noinspection OptionalGetWithoutIsPresent
    assertThat(client.getKey(null, RequestEvent.STARTED).get()).isEqualTo(keyGenerator.getKey(null, RequestEvent.STARTED));
    assertThat(client.getPeerId(null, RequestEvent.STARTED)).isEqualTo(peerIdGenerator.getPeerId(null, RequestEvent.STARTED));
    assertThat(client.getNumwant(RequestEvent.STARTED)).isEqualTo(200);
}
项目:openjdk-jdk10    文件:ConcurrentSkipListMap.java   
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
    if (action == null) throw new NullPointerException();
    Comparator<? super K> cmp = comparator;
    K f = fence;
    Node<K,V> e = current;
    current = null;
    for (; e != null; e = e.next) {
        K k; Object v;
        if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
            break;
        if ((v = e.value) != null && v != e) {
            @SuppressWarnings("unchecked") V vv = (V)v;
            action.accept
                (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
        }
    }
}
项目:incubator-netbeans    文件:ModesSubModel.java   
public Set<ModeStructureSnapshot.SlidingModeSnapshot> createSlidingModeSnapshots() {
    Set<ModeStructureSnapshot.SlidingModeSnapshot> result = 
            new HashSet<ModeStructureSnapshot.SlidingModeSnapshot>();
    for (Map.Entry<ModeImpl, String> curEntry: slidingModes2Sides.entrySet()) {
        final ModeImpl key = curEntry.getKey();
        AbstractMap<TopComponent, Integer> lazy = new AbstractMap<TopComponent, Integer>() {
            Map<TopComponent, Integer> delegate;
            @Override
            public Set<Entry<TopComponent, Integer>> entrySet() {
                if (delegate == null) {
                    delegate = getSlideInSizes(key);
                }
                return delegate.entrySet();
            }
        };

         result.add(new ModeStructureSnapshot.SlidingModeSnapshot(
                curEntry.getKey(), curEntry.getValue(), lazy
        ));
    }
    return result;
}
项目:JRediClients    文件:CommandAsyncService.java   
private <T> T tryHandleReference0(T o) {
    if (o instanceof RedissonReference) {
        return fromReference(o);
    } else if (o instanceof ScoredEntry && ((ScoredEntry) o).getValue() instanceof RedissonReference) {
        ScoredEntry<?> se = ((ScoredEntry<?>) o);
        return (T) new ScoredEntry(se.getScore(), fromReference(se.getValue()));
    } else if (o instanceof ScanObjectEntry) {
        ScanObjectEntry keyScan = (ScanObjectEntry) o;
        Object obj = tryHandleReference0(keyScan.getObj());
        return obj != keyScan.getObj() ? (T) new ScanObjectEntry(keyScan.getBuf(), obj) : o;
    } else if (o instanceof Map.Entry) {
        Map.Entry old = (Map.Entry) o;
        Object key = tryHandleReference0(old.getKey());
        Object value = tryHandleReference0(old.getValue());
        return value != old.getValue() || key != old.getKey()
                ? (T) new AbstractMap.SimpleEntry(key, value)
                : o;
    } else {
        return o;
    }
}
项目:openjdk-jdk10    文件:ResponderIdTests.java   
@Override
public Map.Entry<Boolean, String> runTest() {
    Boolean pass = Boolean.FALSE;
    String message = null;
    try {
        ResponderId ridByKeyIdBytes =
                new ResponderId(INV_EXPLICIT_TAG_KEY_ID);
        throw new RuntimeException("Expected IOException not thrown");
    } catch (IOException ioe) {
        // Make sure it's the IOException we're looking for
        if (ioe.getMessage().contains("Invalid ResponderId content")) {
            pass = Boolean.TRUE;
        } else {
            ioe.printStackTrace(System.out);
            message = ioe.getClass().getName();
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        message = e.getClass().getName();
    }

    return new AbstractMap.SimpleEntry<>(pass, message);
}
项目:JRediClients    文件:RedissonMapTest.java   
@Test
public void testStringCodec() {
    Config config = createConfig();
    config.setCodec(StringCodec.INSTANCE);
    RedissonClient redisson = Redisson.create(config);

    RMap<String, String> rmap = redisson.getMap("TestRMap01");
    rmap.put("A", "1");
    rmap.put("B", "2");

    Iterator<Map.Entry<String, String>> iterator = rmap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, String> next = iterator.next();
        assertThat(next).isIn(new AbstractMap.SimpleEntry("A", "1"), new AbstractMap.SimpleEntry("B", "2"));
    }

    redisson.shutdown();
}
项目:jdk8u-jdk    文件:ConcurrentSkipListMap.java   
/**
 * Submap version of ConcurrentSkipListMap.getNearEntry
 */
Map.Entry<K,V> getNearEntry(K key, int rel) {
    Comparator<? super K> cmp = m.comparator;
    if (isDescending) { // adjust relation for direction
        if ((rel & LT) == 0)
            rel |= LT;
        else
            rel &= ~LT;
    }
    if (tooLow(key, cmp))
        return ((rel & LT) != 0) ? null : lowestEntry();
    if (tooHigh(key, cmp))
        return ((rel & LT) != 0) ? highestEntry() : null;
    for (;;) {
        Node<K,V> n = m.findNear(key, rel, cmp);
        if (n == null || !inBounds(n.key, cmp))
            return null;
        K k = n.key;
        V v = n.getValidValue();
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}
项目:airgram    文件:MessageObject.java   
public CharSequence replaceWithLink(CharSequence source, String param, ArrayList<Integer> uids, AbstractMap<Integer, TLRPC.User> usersDict) {
    int start = TextUtils.indexOf(source, param);
    if (start >= 0) {
        SpannableStringBuilder names = new SpannableStringBuilder("");
        for (int a = 0; a < uids.size(); a++) {
            TLRPC.User user = null;
            if (usersDict != null) {
                user = usersDict.get(uids.get(a));
            }
            if (user == null) {
                user = MessagesController.getInstance().getUser(uids.get(a));
            }
            if (user != null) {
                String name = UserObject.getUserName(user);
                start = names.length();
                if (names.length() != 0) {
                    names.append(", ");
                }
                names.append(name);
                names.setSpan(new URLSpanNoUnderlineBold("" + user.id), start, start + name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return TextUtils.replace(source, new String[]{param}, new CharSequence[]{names});
    }
    return source;
}
项目:openjdk-jdk10    文件:ConcurrentSkipListMap.java   
/**
 * Submap version of ConcurrentSkipListMap.getNearEntry.
 */
Map.Entry<K,V> getNearEntry(K key, int rel) {
    Comparator<? super K> cmp = m.comparator;
    if (isDescending) { // adjust relation for direction
        if ((rel & LT) == 0)
            rel |= LT;
        else
            rel &= ~LT;
    }
    if (tooLow(key, cmp))
        return ((rel & LT) != 0) ? null : lowestEntry();
    if (tooHigh(key, cmp))
        return ((rel & LT) != 0) ? highestEntry() : null;
    for (;;) {
        Node<K,V> n = m.findNear(key, rel, cmp);
        if (n == null || !inBounds(n.key, cmp))
            return null;
        K k = n.key;
        V v = n.getValidValue();
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}
项目:elasticsearch_my    文件:JvmGcMonitorServiceSettingsTests.java   
public void testMissingSetting() throws InterruptedException {
    String collector = randomAsciiOfLength(5);
    Set<AbstractMap.SimpleEntry<String, String>> entries = new HashSet<>();
    entries.add(new AbstractMap.SimpleEntry<>("monitor.jvm.gc.collector." + collector + ".warn", randomPositiveTimeValue()));
    entries.add(new AbstractMap.SimpleEntry<>("monitor.jvm.gc.collector." + collector + ".info", randomPositiveTimeValue()));
    entries.add(new AbstractMap.SimpleEntry<>("monitor.jvm.gc.collector." + collector + ".debug", randomPositiveTimeValue()));
    Settings.Builder builder = Settings.builder();

    // drop a random setting or two
    for (@SuppressWarnings("unchecked") AbstractMap.SimpleEntry<String, String> entry : randomSubsetOf(randomIntBetween(1, 2), entries.toArray(new AbstractMap.SimpleEntry[0]))) {
        builder.put(entry.getKey(), entry.getValue());
    }

    // we should get an exception that a setting is missing
    execute(builder.build(), (command, interval, name) -> null, e -> {
        assertThat(e, instanceOf(IllegalArgumentException.class));
        assertThat(e.getMessage(), containsString("missing gc_threshold for [monitor.jvm.gc.collector." + collector + "."));
    }, true, null);
}
项目:VillagerTrades    文件:VillagerRegistryHelper.java   
public static List<Map.Entry<Integer, String>> getProfessionIdsAndNamesSortedById()
{
    List<Map.Entry<Integer, String>> professions = new ArrayList<Map.Entry<Integer, String>>();

    for (VillagerRegistry.VillagerProfession profession : ForgeRegistries.VILLAGER_PROFESSIONS.getValues())
    {
        @SuppressWarnings("deprecation")
        int id = VillagerRegistry.getId(profession);
        String name = profession.getRegistryName().toString();
        professions.add(new AbstractMap.SimpleEntry<Integer, String>(id, name));
    }

    Collections.sort(professions, new Comparator<Map.Entry<Integer, String>>()
    {
        @Override
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2)
        {
            return o1.getKey() - o2.getKey();
        }
    });

    return professions;

}
项目:Supreme-Bot    文件:SQLUtil.java   
public static final <T> List<Map.Entry<Field, SQLField>> getFields(Class<? extends T> clazz, FieldType fieldType) {
    if (clazz == null || !clazz.isAnnotationPresent(SQLTable.class) || fieldType == null) {
        return new ArrayList<>();
    }
    return Arrays.asList(clazz.getFields()).stream().filter((field) -> field.isAnnotationPresent(SQLField.class)).map((field) -> new AbstractMap.SimpleEntry<>(field, field.getAnnotation(SQLField.class))).filter((field) -> {
        switch (fieldType) {
            case NONE:
                return false;
            case SEND:
                return field.getValue().send();
            case RECEIVE:
                return field.getValue().receive();
            case REMOVE:
                return field.getValue().primaryKey();
            case ALL:
                return true;
            default:
                return false;
        }
    }).sorted((field_1, field_2) -> field_1.getValue().index() - field_2.getValue().index()).collect(Collectors.toList());
}
项目:fpc    文件:Notifier.java   
/**
  * Issue a DPN Availability Notification
  * @param dpnAvailability - DPN
  */
 static public void issueDpnAvailabilityNotification(DpnAvailability dpnAvailability){
    for(ClientIdentifier clientId : FpcServiceImpl.clientIdList){
        Long notificationId = NotificationInfo.next();
         Notify notif = new NotifyBuilder()
                 .setNotificationId(new NotificationId(notificationId))
                 .setTimestamp(BigInteger.valueOf(System.currentTimeMillis()))
                 .setValue(dpnAvailability)
                 .build();
         String streamString = fpcCodecUtils.notificationToJsonString(Notify.class,
        (DataObject) notif,
        true);
         streamString = streamString.replace("\n", "");
         streamString = "event:application/json;/notification\ndata:"+streamString+"\n";

         try {
    NotificationService.blockingQueue.put(new AbstractMap.SimpleEntry<String,String>(clientId.getInt64().toString(),streamString));
} catch (InterruptedException e) {
    ErrorLog.logError(e.getLocalizedMessage(),e.getStackTrace());
}
    }
 }
项目:googles-monorepo-demo    文件:MapTestSuiteBuilderTests.java   
private static Test testsForHashMapNullValuesForbidden() {
  return wrappedHashMapTests(new WrappedHashMapGenerator() {
    @Override Map<String, String> wrap(final HashMap<String, String> map) {
      if (map.containsValue(null)) {
        throw new NullPointerException();
      }
      return new AbstractMap<String, String>() {
        @Override public Set<Map.Entry<String, String>> entrySet() {
          return map.entrySet();
        }
        @Override public String put(String key, String value) {
          checkNotNull(value);
          return map.put(key, value);
        }
      };
    }
  }, "HashMap w/out null values", ALLOWS_NULL_KEYS);
}
项目:hashsdn-controller    文件:HardcodedModuleFactoriesResolver.java   
public HardcodedModuleFactoriesResolver(final BundleContext bundleContext, final ModuleFactory... list) {
    this.factories = new HashMap<>(list.length);
    for (ModuleFactory moduleFactory : list) {
        String moduleName = moduleFactory.getImplementationName();
        if (moduleName == null || moduleName.isEmpty()) {
            throw new IllegalStateException("Invalid implementation name for " + moduleFactory);
        }
        Map.Entry<ModuleFactory, BundleContext> conflicting = factories.get(moduleName);
        if (conflicting == null) {
            factories.put(moduleName, new AbstractMap.SimpleEntry<>(moduleFactory, bundleContext));
        } else {
            throw new IllegalArgumentException(String.format(
                    "Module name is not unique. Found two conflicting factories with same name '%s':\n\t%s\n\t%s\n",
                    moduleName, conflicting.getKey(), moduleFactory));
        }
    }
}
项目:jdk8u-jdk    文件:ConcurrentSkipListMap.java   
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
    if (action == null) throw new NullPointerException();
    Comparator<? super K> cmp = comparator;
    K f = fence;
    Node<K,V> e = current;
    current = null;
    for (; e != null; e = e.next) {
        K k; Object v;
        if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
            break;
        if ((v = e.value) != null && v != e) {
            @SuppressWarnings("unchecked") V vv = (V)v;
            action.accept
                (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
        }
    }
}
项目:openjdk-jdk10    文件:ConcurrentHashMap.java   
/**
 * Helper method for EntrySetView.removeIf.
 */
boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
    if (function == null) throw new NullPointerException();
    Node<K,V>[] t;
    boolean removed = false;
    if ((t = table) != null) {
        Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
        for (Node<K,V> p; (p = it.advance()) != null; ) {
            K k = p.key;
            V v = p.val;
            Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
            if (function.test(e) && replaceNode(k, null, v) != null)
                removed = true;
        }
    }
    return removed;
}
项目:guava-mock    文件:MapTestSuiteBuilderTests.java   
private static Test testsForHashMapNullValuesForbidden() {
  return wrappedHashMapTests(new WrappedHashMapGenerator() {
    @Override Map<String, String> wrap(final HashMap<String, String> map) {
      if (map.containsValue(null)) {
        throw new NullPointerException();
      }
      return new AbstractMap<String, String>() {
        @Override public Set<Map.Entry<String, String>> entrySet() {
          return map.entrySet();
        }
        @Override public String put(String key, String value) {
          checkNotNull(value);
          return map.put(key, value);
        }
      };
    }
  }, "HashMap w/out null values", ALLOWS_NULL_KEYS);
}
项目:QuantTester    文件:SinYeeBarInputStream.java   
Map<String, Map.Entry<Integer, Integer>[]> getAvailableContracts() throws IOException {
    Map<String, Map.Entry<Integer, Integer>[]> available_contracts = new HashMap<>();
    short contract_num = readShort();
    for (int i = 0; i < contract_num; i++) {
        byte strlen = (byte) read();
        byte[] contract_name_bytes = new byte[strlen];
        read(contract_name_bytes, 0, strlen);
        String contract_name = new String(contract_name_bytes);

        skip(29 - strlen); // ����Unicode���contract_name

        @SuppressWarnings("unchecked")
        Map.Entry<Integer, Integer>[] offset_nums = new Map.Entry[8];
        for (int j = 0; j < 8; j++) {
            offset_nums[j] = new AbstractMap.SimpleEntry<>(readInt(), readInt());
        }
        available_contracts.put(contract_name, offset_nums);
    }
    return available_contracts;
}
项目:swblocks-decisiontree    文件:DecisionTreeRuleTest.java   
@Test
public void testRuleDuplicateOutputCheck() {
    final DecisionTreeRule rule = new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input1", "input2"), Collections.singletonMap("outputDriver", "result"), null,
            null);
    assertTrue(rule.isDuplicateOutputData(new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input1", "input2"), Collections.singletonMap("outputDriver", "result"), null,
            null)));
    assertTrue(rule.isDuplicateOutputData(new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input3", "input4"), Collections.singletonMap("outputDriver", "result"), null,
            null)));
    assertFalse(rule.isDuplicateOutputData(null));
    assertFalse(rule.isDuplicateOutputData(new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input3", "input4"), Collections.singletonMap("outputDriver", "result1"), null,
            null)));
    assertFalse(rule.isDuplicateOutputData(new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input3", "input4"), Collections.singletonMap("outputDriver1", "result1"), null,
            null)));
    assertFalse(rule.isDuplicateOutputData(
            new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(), getInputDriverArray("input3", "input4"),
                    Stream.of(new AbstractMap.SimpleEntry<>("outputDriver", "result1"),
                            new AbstractMap.SimpleEntry<>("outputDriver2", "result2"))
                            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,
                                    AbstractMap.SimpleEntry::getValue)), null, null)));
}
项目:collectors-utils    文件:MaxEntryValueByCountingTest.java   
@Test
public void should_return_a_correct_map_for_max_entry_value_by_counting_on_correct_stream() {

    // Given
    Map<Integer, Stream<String>> map = new HashMap<>();
    map.put(1, Stream.of("one", "two", "three"));
    map.put(2, Stream.of("one", "two", "two", "three"));
    map.put(3, Stream.of("one", "two", "two", "three", "three", "three"));
    Stream<Map.Entry<Integer, Stream<String>>> entries =
            FunctionsUtils.<Integer, Stream<String>>toStreamOfEntries().apply(map);

    Collector<Map.Entry<Integer, Stream<String>>, ?, Map<Integer, Map.Entry<String, Long>>> collector =
            CollectorsUtils.maxEntryValueByCounting();

    // When
    Map<Integer, Map.Entry<String, Long>> collect = entries.collect(collector);

    // Then
    assertThat(collect.size()).isEqualTo(3);
    assertThat(collect.get(1)).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("one", 1L));
    assertThat(collect.get(2)).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("two", 2L));
    assertThat(collect.get(3)).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("three", 3L));
}
项目:collectors-utils    文件:GroupingByAndMaxByTest.java   
@Test
public void should_return_the_result_for_groupingBySelf_and_max_by_value_on_a_non_empty_stream() {

    // Given
    Stream<String> strings = Stream.of("one", "one", "two", "two", "two");

    Collector<String, ?, Optional<Map.Entry<String, Long>>> collector =
            CollectorsUtils.groupingBySelfAndMaxByValue(
                    counting()
            );

    // When
    Optional<Map.Entry<String, Long>> result = strings.collect(collector);

    // Then
    assertThat(result.isPresent()).isTrue();
    assertThat(result.get()).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("two", 3L));
}
项目:HCFCore    文件:KitsCommand.java   
public void onEnable() {
    if(config.get("kits") != null) {
        cooldowns = (HashMap<UUID, Map<String, Long>>) config.get("kits");
    }
    Bukkit.getScheduler().scheduleSyncRepeatingTask(hcf, new Runnable() {
        public void run() {
            if(cooldowns.size() > 0) {
                for(UUID uuid : cooldowns.keySet()) {
                    for(String strings : cooldowns.get(uuid).keySet()) {
                        if(cooldowns.get(uuid).get(strings) <= 0L) {
                            cooldowns.get(uuid).remove(strings);
                        } else {
                            cooldowns.put(uuid, (Map<String, Long>) new AbstractMap.SimpleEntry<String, Long>(strings, cooldowns.get(uuid).get(strings) - 1000L));
                        }
                    }
                }
            }
        }
    }, 20L, 20L);
}
项目:openjdk-jdk10    文件:ConcurrentSkipListMap.java   
/**
 * Removes first entry; returns its snapshot.
 * @return null if empty, else snapshot of first entry
 */
private Map.Entry<K,V> doRemoveFirstEntry() {
    for (Node<K,V> b, n;;) {
        if ((n = (b = head.node).next) == null)
            return null;
        Node<K,V> f = n.next;
        if (n != b.next)
            continue;
        Object v = n.value;
        if (v == null) {
            n.helpDelete(b, f);
            continue;
        }
        if (!n.casValue(v, null))
            continue;
        if (!n.appendMarker(f) || !b.casNext(n, f))
            findFirst(); // retry
        clearIndexToFirst();
        @SuppressWarnings("unchecked") V vv = (V)v;
        return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, vv);
    }
}
项目:joal    文件:TorrentPersistentRefreshPeerIdGeneratorTest.java   
@Test
public void shouldConsiderEntryEvictableIfOlderThanTwoHours() {
    final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
    final TorrentPersistentRefreshPeerIdGenerator generator = new TorrentPersistentRefreshPeerIdGenerator(algo, false);

    final AccessAwarePeerId oldKey = Mockito.mock(AccessAwarePeerId.class);
    Mockito.when(oldKey.getLastAccess()).thenReturn(LocalDateTime.now().minus(120, ChronoUnit.MINUTES));
    Mockito.when(oldKey.getPeerId()).thenReturn("-BT-C-");
    assertThat(generator.shouldEvictEntry(new AbstractMap.SimpleEntry<>(Mockito.mock(MockedTorrent.class), oldKey))).isTrue();
}
项目:Lagerta    文件:SubscriberConsumer.java   
@SuppressWarnings("unchecked")
@Override public Map.Entry<List<IgniteBiTuple<String, ?>>, List<Object>> apply(Long txId) {
    TransactionWrapper currentTx = buffer.get(txId);
    List<IgniteBiTuple<String, ?>> keys = currentTx.metadata().getCompositeKeys();
    List<Object> values = (List<Object>)serializer.deserialize(currentTx.data());
    return new AbstractMap.SimpleImmutableEntry<>(keys, values);
}
项目:OpenJSharp    文件:ConcurrentSkipListMap.java   
Map.Entry<K,V> removeLowest() {
    Comparator<? super K> cmp = m.comparator;
    for (;;) {
        Node<K,V> n = loNode(cmp);
        if (n == null)
            return null;
        K k = n.key;
        if (!inBounds(k, cmp))
            return null;
        V v = m.doRemove(k, null);
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}
项目:openjdk-jdk10    文件:ResponderIdTests.java   
@Override
public Map.Entry<Boolean, String> runTest() {
    Boolean pass = Boolean.FALSE;
    String message = null;
    try {
        respByName = new ResponderId(cert.getSubjectX500Principal());
        pass = Boolean.TRUE;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        message = e.getClass().getName();
    }

    return new AbstractMap.SimpleEntry<>(pass, message);
}
项目:fpc    文件:Notifier.java   
/**
 * Issues a Configuration Result over the Northbound over the NotificationPublishService
 * @param clientId - Client Identifier
 * @param opid - Operation Identifier
 * @param status - Operation Status
 * @param rt - Result Type
 * @param issueInternal - indicates if an internal framework notification should also occur
 * @param causeValue - cause value returned from DPN
 */
static public void issueConfigResult(
        ClientIdentifier clientId,
        OpIdentifier opid,
        OpStatus status,
        ResultType rt,
        boolean issueInternal,
        Short causeValue) {
    Long notificationId = NotificationInfo.next();

    ConfigResultNotification result = new ConfigResultNotificationBuilder()
            .setNotificationId(new NotificationId(notificationId))
            .setTimestamp(BigInteger.valueOf(System.currentTimeMillis()))
            .setValue(new ConfigResultBuilder()
                    .setOpId(opid)
                    .setOpStatus(status)
                    .setResultType(rt)
                    .setCauseValue(Long.valueOf(causeValue))
                    .build())
            .build();
    try {
        String streamString = fpcCodecUtils.notificationToJsonString(Notify.class,
                (DataObject) result,
                true);
        streamString = streamString.replace("\n","");
        streamString = "event:application/json;/notification\ndata:"+streamString+"\n";
        NotificationService.blockingQueue.put(new AbstractMap.SimpleEntry<String,String>(clientId.getInt64().toString(),streamString));
        if (issueInternal &&
                (notificationService != null)) {
            notificationService.putNotification(result);
        }
    } catch (InterruptedException e) {
        LOG.warn("Notification Service Interruption occurred while sending a Read Notification");
        ErrorLog.logError(e.getStackTrace());
    } catch (Exception ee) {
        ErrorLog.logError("Notifier Exception:   "+ee.getClass().getName()+" : "+ee.getLocalizedMessage(),ee.getStackTrace());
    }
}
项目:Abacus-Lightweight-Stream-API    文件:EntryStream.java   
public static <K, V> EntryStream<K, V> zip(final K[] keys, final V[] values) {
    final BiFunction<K, V, Map.Entry<K, V>> zipFunction = new BiFunction<K, V, Map.Entry<K, V>>() {
        @Override
        public Entry<K, V> apply(K k, V v) {
            return new AbstractMap.SimpleImmutableEntry<>(k, v);
        }
    };

    final Function<Map.Entry<K, V>, Map.Entry<K, V>> mapper = Fn.identity();

    return Stream.zip(keys, values, zipFunction).mapToEntry(mapper);
}
项目:java-web-servlet-filter    文件:HttpServletRequestExtractAdapter.java   
@Override
public Map.Entry<K, V> next() {
    if (mapEntry == null || (!listIterator.hasNext() && mapIterator.hasNext())) {
        mapEntry = mapIterator.next();
        listIterator = mapEntry.getValue().iterator();
    }

    if (listIterator.hasNext()) {
        return new AbstractMap.SimpleImmutableEntry<>(mapEntry.getKey(), listIterator.next());
    } else {
        return new AbstractMap.SimpleImmutableEntry<>(mapEntry.getKey(), null);
    }
}
项目:traccar-service    文件:JsonGeocoder.java   
@Override
public void getAddress(
        final AddressFormat format, final double latitude,
        final double longitude, final ReverseGeocoderCallback callback) {

    if (cache != null) {
        String cachedAddress = cache.get(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude));
        if (cachedAddress != null) {
            callback.onSuccess(cachedAddress);
            return;
        }
    }

    Context.getAsyncHttpClient().prepareGet(String.format(url, latitude, longitude))
            .execute(new AsyncCompletionHandler() {
        @Override
        public Object onCompleted(Response response) throws Exception {
            try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) {
                Address address = parseAddress(reader.readObject());
                if (address != null) {
                    String formattedAddress = format.format(address);
                    if (cache != null) {
                        cache.put(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude), formattedAddress);
                    }
                    callback.onSuccess(formattedAddress);
                } else {
                    callback.onFailure(new GeocoderException("Empty address"));
                }
            }
            return null;
        }

        @Override
        public void onThrowable(Throwable t) {
            callback.onFailure(t);
        }
    });
}
项目:Abacus-Lightweight-Stream-API    文件:EntryStream.java   
public <KK, VV> EntryStream<KK, VV> map(final Function<? super K, KK> keyMapper, final Function<? super V, VV> valueMapper) {
    final Function<Map.Entry<K, V>, Map.Entry<KK, VV>> mapper = new Function<Map.Entry<K, V>, Map.Entry<KK, VV>>() {
        @Override
        public Entry<KK, VV> apply(Entry<K, V> t) {
            return new AbstractMap.SimpleImmutableEntry<>(keyMapper.apply(t.getKey()), valueMapper.apply(t.getValue()));
        }
    };

    return map(mapper);
}
项目:Abacus-Lightweight-Stream-API    文件:EntryStream.java   
public <KK> EntryStream<KK, V> flatMapKey(final Function<? super K, Stream<KK>> keyMapper) {
    final Function<Map.Entry<K, V>, Stream<Map.Entry<KK, V>>> mapper2 = new Function<Map.Entry<K, V>, Stream<Map.Entry<KK, V>>>() {
        @Override
        public Stream<Entry<KK, V>> apply(final Map.Entry<K, V> e) {
            return keyMapper.apply(e.getKey()).map(new Function<KK, Map.Entry<KK, V>>() {
                @Override
                public Map.Entry<KK, V> apply(KK kk) {
                    return new AbstractMap.SimpleImmutableEntry<>(kk, e.getValue());
                }
            });
        }
    };

    return flatMap(mapper2);
}
项目:QuantTester    文件:Portfolio.java   
@Deprecated
public float getBalance(float price) {
    AbstractMap.SimpleEntry<String, Float> latestMarket = new AbstractMap.SimpleEntry<String, Float>("common", price);
    @SuppressWarnings("unchecked")
    AbstractMap.SimpleEntry<String, Float>[] latestMarkets = new AbstractMap.SimpleEntry[1];
    latestMarkets[0] = latestMarket;
    return getBalance(latestMarkets);
}
项目:Lagerta    文件:AbstractIgniteCommitterUnitTest.java   
private static Map.Entry<List<IgniteBiTuple<String, List<Object>>>, List<List<Object>>> tx(
    Map.Entry<String, Object>... pairs
) {
    List<Object> keys = new ArrayList<>(pairs.length);
    List<Object> values = new ArrayList<>(pairs.length);

    for (Map.Entry<String, ?> pair : pairs) {
        keys.add(pair.getKey());
        values.add(pair.getValue());
    }
    IgniteBiTuple<String, List<Object>> cacheToKeys = new IgniteBiTuple<>(CACHE_NAME, keys);

    return new AbstractMap.SimpleImmutableEntry<>(Collections.singletonList(cacheToKeys),
        Collections.singletonList(values));
}
项目:OpenJSharp    文件:EditDistance.java   
/**
 * Computes the edit distance between two strings.
 *
 * <p>
 * The complexity is O(nm) where n=a.length() and m=b.length().
 */
public static int editDistance( String a, String b ) {
    // let's check cache
    AbstractMap.SimpleEntry<String,String> entry = new AbstractMap.SimpleEntry<String, String>(a, b); // using this class to avoid creation of my own which will handle PAIR of values
    Integer result = null;
    if (CACHE.containsKey(entry))
        result = CACHE.get(entry); // looks like we have it

    if (result == null) {
        result = new EditDistance(a, b).calc();
        CACHE.put(entry, result); // cache the result
    }
    return result;
}
项目:dremio-oss    文件:NamespaceServiceImpl.java   
@Override
public Iterable<Map.Entry<NamespaceKey, NameSpaceContainer>> find(FindByCondition condition) {
  return Iterables.transform(namespace.find(condition), new Function<Map.Entry<byte[], NameSpaceContainer>, Map.Entry<NamespaceKey, NameSpaceContainer>>() {
    @Override
    public Map.Entry<NamespaceKey, NameSpaceContainer> apply(Map.Entry<byte[], NameSpaceContainer> input) {
      return new AbstractMap.SimpleEntry<>(new NamespaceKey(input.getValue().getFullPathList()), input.getValue());
    }
  });
}
项目:openjdk-jdk10    文件:ConcurrentSkipListMap.java   
Map.Entry<K,V> removeLowest() {
    Comparator<? super K> cmp = m.comparator;
    for (;;) {
        Node<K,V> n = loNode(cmp);
        if (n == null)
            return null;
        K k = n.key;
        if (!inBounds(k, cmp))
            return null;
        V v = m.doRemove(k, null);
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}