Java Code Examples for java.util.concurrent.ConcurrentMap

The following are top voted examples for showing how to use java.util.concurrent.ConcurrentMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: q-mail   File: Storage.java   Source Code and License 6 votes vote down vote up
void doInTransaction(Runnable dbWork) {
    ConcurrentMap<String, String> newStorage = new ConcurrentHashMap<String, String>();
    newStorage.putAll(storage);
    workingStorage.set(newStorage);

    SQLiteDatabase mDb = openDB();
    workingDB.set(mDb);

    List<String> changedKeys = new ArrayList<String>();
    workingChangedKeys.set(changedKeys);

    mDb.beginTransaction();
    try {
        dbWork.run();
        mDb.setTransactionSuccessful();
        storage = newStorage;
    } finally {
        workingDB.remove();
        workingStorage.remove();
        workingChangedKeys.remove();
        mDb.endTransaction();
        mDb.close();
    }
}
 
Example 2
Project: powsybl-core   File: MapDbAppStorage.java   Source Code and License 6 votes vote down vote up
private <P extends AbstractPoint, C extends ArrayChunk<P, C>, T extends TimeSeries<P, T>>
    List<T> getTimeSeries(String nodeId, Set<String> timeSeriesNames, int version,
                          ConcurrentMap<TimeSeriesChunkKey, C> map, BiFunction<TimeSeriesMetadata, List<C>, T> constr) {
    UUID nodeUuid = checkNodeId(nodeId);
    Objects.requireNonNull(timeSeriesNames);
    TimeSeriesIndex.checkVersion(version);
    Objects.requireNonNull(map);
    Objects.requireNonNull(constr);
    List<T> timeSeriesList = new ArrayList<>();
    for (String timeSeriesName : timeSeriesNames) {
        TimeSeriesMetadata metadata = timeSeriesMetadataMap.get(new NamedLink(nodeUuid, timeSeriesName));
        if (metadata == null) {
            throw createTimeSeriesNotFoundAtNode(timeSeriesName, nodeUuid);
        }
        List<C> chunks = getChunks(nodeUuid, version, timeSeriesName, metadata, map);
        if (!chunks.isEmpty()) {
            timeSeriesList.add(constr.apply(metadata, chunks));
        }
    }
    return timeSeriesList;
}
 
Example 3
Project: dubbo2   File: ConsumerServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findServicesByApplication(String application) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY);
    if(consumerUrls == null || application == null || application.length() == 0) return ret;
    
    for(Map.Entry<String, Map<Long, URL>> e1 : consumerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for(Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            if(application.equals(u.getParameter(Constants.APPLICATION_KEY))) {
                ret.add(e1.getKey());
                break;
            }
        }
    }
    
    return ret;
}
 
Example 4
Project: dubbocloud   File: ConsumerServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findServicesByApplication(String application) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY);
    if(consumerUrls == null || application == null || application.length() == 0) return ret;
    
    for(Map.Entry<String, Map<Long, URL>> e1 : consumerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for(Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            if(application.equals(u.getParameter(Constants.APPLICATION_KEY))) {
                ret.add(e1.getKey());
                break;
            }
        }
    }
    
    return ret;
}
 
Example 5
Project: vertx-zero   File: Dual.java   Source Code and License 6 votes vote down vote up
private static ConcurrentMap<Object, JsonObject> mapZip(
        final JsonArray sources,
        final String field
) {
    final ConcurrentMap<Object, JsonObject> resultMap =
            new ConcurrentHashMap<>();
    Observable.fromIterable(sources)
            .map(item -> (JsonObject) item)
            .subscribe(item -> {
                if (item.containsKey(field)) {
                    final Object value = item.getValue(field);
                    if (null != value) {
                        resultMap.put(value, item);
                    }
                }
            });
    return resultMap;
}
 
Example 6
Project: googles-monorepo-demo   File: ConcurrentHashMultisetTest.java   Source Code and License 6 votes vote down vote up
public void testSerializationWithMapMaker_preservesIdentityKeyEquivalence() {
  ConcurrentMap<String, AtomicInteger> map =
      new MapMaker().keyEquivalence(Equivalence.identity()).makeMap();

  ConcurrentHashMultiset<String> multiset = ConcurrentHashMultiset.create(map);
  multiset = reserializeAndAssert(multiset);

  String s1 = new String("a");
  String s2 = new String("a");
  assertEquals(s1, s2); // Stating the obvious.
  assertTrue(s1 != s2); // Stating the obvious.

  multiset.add(s1);
  assertTrue(multiset.contains(s1));
  assertFalse(multiset.contains(s2));
  assertEquals(1, multiset.count(s1));
  assertEquals(0, multiset.count(s2));
}
 
Example 7
Project: diorite-configs-java8   File: YamlCollectionCreator.java   Source Code and License 6 votes vote down vote up
static void putAllCollections(Map<Class<?>, IntFunction<?>> map, Map<Class<?>, Function<?, ?>> unmodMap)
{
    safePut(map, ArrayList.class, ArrayList::new);
    safePut(map, HashSet.class, LinkedHashSet::new);
    safePut(map, Properties.class, x -> new Properties());
    safePut(map, Hashtable.class, Hashtable::new);

    safePut(map, Collection.class, ArrayList::new);
    safePut(map, Set.class, LinkedHashSet::new);
    safePut(map, List.class, ArrayList::new);
    safePut(map, SortedSet.class, x -> new TreeSet<>());
    safePut(map, Queue.class, x -> new ConcurrentLinkedQueue<>());
    safePut(map, Deque.class, x -> new ConcurrentLinkedDeque<>());
    safePut(map, BlockingQueue.class, x -> new LinkedBlockingQueue<>());
    safePut(map, BlockingDeque.class, x -> new LinkedBlockingDeque<>());


    safePut(map, HashMap.class, LinkedHashMap::new);
    safePut(map, LinkedHashMap.class, LinkedHashMap::new);
    safePut(map, ConcurrentHashMap.class, ConcurrentHashMap::new);

    safePut(map, Map.class, LinkedHashMap::new);
    safePut(map, ConcurrentMap.class, x -> new ConcurrentSkipListMap<>());
    safePut(map, ConcurrentNavigableMap.class, x -> new ConcurrentSkipListMap<>());
    safePut(map, SortedMap.class, i -> new TreeMap<>());
}
 
Example 8
Project: myfaces-trinidad   File: FileSystemStyleCache.java   Source Code and License 6 votes vote down vote up
private Entry _getEntry(
  StyleContext context,
  StyleSheetDocument document,
  ConcurrentMap<Key, Future<Entry>> cache,
  Key key,
  boolean checkModified
  )
{
  Future<Entry> f = cache.get(key);
  Entry entry = _getEntryFromFuture(context, document, cache, key, f);
  if ((entry != null) && !_validateEntry(entry, checkModified))
  {
    // atomically remove the key from the cache if it currently points to the entry
    cache.remove(key, f);
    entry = null;
  }
  
  return entry;
}
 
Example 9
Project: dubbo2   File: ProviderServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findApplicationsByServiceName(String service) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(null == providerUrls) return ret;
    
    Map<Long, URL> value = providerUrls.get(service);
    if(value == null){
    	return ret;
    }
    for(Map.Entry<Long, URL> e2 : value.entrySet()) {
        URL u = e2.getValue();
        String app = u.getParameter(Constants.APPLICATION_KEY);
        if(app != null) ret.add(app);
    }
    
    return ret;
}
 
Example 10
Project: verify-hub   File: SamlEngineModule.java   Source Code and License 6 votes vote down vote up
@Provides
private AuthnRequestToIdaRequestFromRelyingPartyTransformer getAuthnRequestAuthnRequestFromRelyingPartyTransformer(
        @Named("authnRequestKeyStore") SigningKeyStore signingKeyStore,
        IdaKeyStore decryptionKeyStore,
        SamlConfiguration samlConfiguration,
        ConcurrentMap<AuthnRequestIdKey, DateTime> duplicateIds,
        SamlDuplicateRequestValidationConfiguration duplicateRequestValidationConfiguration,
        SamlAuthnRequestValidityDurationConfiguration authnRequestValidityDurationConfiguration
) {
    return hubTransformersFactory.getAuthnRequestToAuthnRequestFromTransactionTransformer(
            samlConfiguration.getExpectedDestinationHost(),
            signingKeyStore,
            decryptionKeyStore,
            duplicateIds,
            duplicateRequestValidationConfiguration,
            authnRequestValidityDurationConfiguration
    );
}
 
Example 11
Project: vertx-zero   File: ZeroApiWorker.java   Source Code and License 6 votes vote down vote up
private ConcurrentMap<Flag, Set<String>> calculateServices(
        final ConcurrentMap<String, Record> services) {
    // Read new services.
    final Set<String> populated = new HashSet<>();
    Observable.fromIterable(services.keySet())
            .subscribe(populated::add);

    // Existed = Yes, Populated = No
    final Set<String> deleted = new HashSet<>(REGISTRITIONS.keySet());
    deleted.removeAll(populated);

    // Existed = Yes, Populated = Yes
    final Set<String> updated = new HashSet<>(REGISTRITIONS.keySet());
    updated.retainAll(populated);

    // Existed = No, Populated = Yes
    final Set<String> added = new HashSet<>(populated);
    added.removeAll(REGISTRITIONS.keySet());

    // Mapping data
    final ConcurrentMap<Flag, Set<String>> result = new ConcurrentHashMap<>();
    result.put(Flag.DELETE, deleted);
    result.put(Flag.NEW, added);
    result.put(Flag.UPDATE, updated);
    return result;
}
 
Example 12
Project: github-test   File: ProviderServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findApplicationsByServiceName(String service) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if (null == providerUrls) return ret;

    Map<Long, URL> value = providerUrls.get(service);
    if (value == null) {
        return ret;
    }
    for (Map.Entry<Long, URL> e2 : value.entrySet()) {
        URL u = e2.getValue();
        String app = u.getParameter(Constants.APPLICATION_KEY);
        if (app != null) ret.add(app);
    }

    return ret;
}
 
Example 13
Project: myfaces-trinidad   File: ConcurrentMapTestCase.java   Source Code and License 6 votes vote down vote up
public void testReplace()
{
  ConcurrentMap<String, Object> cache = createMap();
  _putTwo(cache);
  Object val = cache.replace(C_STR, ONE);
  assertNull(val);
  assertEquals("Replace operation did not work as expected.", 2, cache.size());
  assertEquals(ONE, cache.get(A_STR));
  assertEquals(TWO, cache.get(B_STR));

  val = cache.replace(A_STR, "aaaString");
  assertEquals(ONE, val);
  assertEquals("Replace operation did not work as expected.", 2, cache.size());
  assertEquals("aaaString", cache.get(A_STR));

  boolean bool = cache.replace(B_STR, "bb", "newValue");
  assertFalse(bool);
  assertEquals("Replace operation did not work as expected.", 2, cache.size());
  assertEquals(TWO, cache.get(B_STR));

  bool = cache.replace(B_STR, TWO, "newValue");
  assertTrue(bool);
  assertEquals("Replace operation did not work as expected.", 2, cache.size());
  assertEquals("newValue", cache.get(B_STR));
}
 
Example 14
Project: JRediClients   File: RedissonConcurrentMapTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSingleReplace_SingleInstance() throws InterruptedException {
    final String name = "testSingleReplace_SingleInstance";

    ConcurrentMap<String, String> map = BaseTest.createInstance().getMap(name);
    map.put("1", "0");

    testSingleInstanceConcurrency(100, r -> {
        ConcurrentMap<String, String> map1 = r.getMap(name);
        map1.replace("1", "3");
    });

    ConcurrentMap<String, String> testMap = BaseTest.createInstance().getMap(name);
    Assert.assertEquals("3", testMap.get("1"));

    assertMapSize(1, name);
}
 
Example 15
Project: JRediClients   File: RedissonConcurrentMapTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSinglePutIfAbsent_SingleInstance() throws InterruptedException {
    final String name = "testSinglePutIfAbsent_SingleInstance";

    ConcurrentMap<String, String> map = BaseTest.createInstance().getMap(name);
    map.putIfAbsent("1", "0");
    testSingleInstanceConcurrency(100, r -> {
        ConcurrentMap<String, String> map1 = r.getMap(name);
        map1.putIfAbsent("1", "1");
    });

    ConcurrentMap<String, String> testMap = BaseTest.createInstance().getMap(name);
    Assert.assertEquals("0", testMap.get("1"));

    assertMapSize(1, name);
}
 
Example 16
Project: myfaces-trinidad   File: SkinStyleProvider.java   Source Code and License 6 votes vote down vote up
private static ConcurrentMap<ProviderKey, StyleProvider> _getProviders()
{
  ConcurrentMap<String, Object> appMap = 
    RequestContext.getCurrentInstance().getApplicationScopedConcurrentMap();

  ConcurrentMap<ProviderKey, StyleProvider> styleProviders =
    (ConcurrentMap<ProviderKey, StyleProvider>)appMap.get(_SKIN_PROVIDERS_KEY);

  if (styleProviders == null)
  {
    styleProviders = _createProvidersCache();

    ConcurrentMap<ProviderKey, StyleProvider> oldStyleProviders =
      (ConcurrentMap<ProviderKey, StyleProvider>)appMap.putIfAbsent(_SKIN_PROVIDERS_KEY, styleProviders);

    if (oldStyleProviders != null)
      styleProviders = oldStyleProviders;
  }

  return styleProviders;
}
 
Example 17
Project: github-test   File: ConsumerServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findServicesByApplication(String application) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY);
    if (consumerUrls == null || application == null || application.length() == 0) return ret;

    for (Map.Entry<String, Map<Long, URL>> e1 : consumerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for (Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            if (application.equals(u.getParameter(Constants.APPLICATION_KEY))) {
                ret.add(e1.getKey());
                break;
            }
        }
    }

    return ret;
}
 
Example 18
Project: dubbox-hystrix   File: ProviderServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findServicesByAddress(String address) {
    List<String> ret = new ArrayList<String>();
    
    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(providerUrls == null || address == null || address.length() == 0) return ret;
    
    for(Map.Entry<String, Map<Long, URL>> e1 : providerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for(Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            if(address.equals(u.getAddress())) {
                ret.add(e1.getKey());
                break;
            }
        }
    }
    
    return ret;
}
 
Example 19
Project: dubbox-hystrix   File: ProviderServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findMethodsByService(String service) {
    List<String> ret = new ArrayList<String>();

    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(providerUrls == null || service == null || service.length() == 0) return ret;
    
    Map<Long, URL> providers = providerUrls.get(service);
    if(null == providers || providers.isEmpty()) return ret;
    
    Entry<Long, URL> p = providers.entrySet().iterator().next();
    String value = p.getValue().getParameter("methods");
    if (value == null || value.length() == 0) {
        return ret;
    }
    String[] methods = value.split(ParseUtils.METHOD_SPLIT);
    if (methods == null || methods.length == 0) {
        return ret;
    }
    
    for(String m : methods) {
        ret.add(m);
    }
    return ret;
}
 
Example 20
Project: myfaces-trinidad   File: SessionChangeManager.java   Source Code and License 6 votes vote down vote up
/**
 * Apply the attribute changes for this component
 * @param context
 * @param component
 */
protected void applySimpleComponentChanges(FacesContext context, UIComponent component)
{
  // Simple component changes always use logical scoped ids because they are consistent across
  // all phases including tag execution
  String scopedId = ComponentUtils.getLogicalScopedIdForComponent(component, context.getViewRoot());
  
  ConcurrentMap<String, AttributeComponentChange> attributeCmponentChanges = _attrChanges.get(scopedId);
  
  if (attributeCmponentChanges != null)
  {
    for (ComponentChange change : attributeCmponentChanges.values())
    {
      change.changeComponent(component);
    }
  }
}
 
Example 21
Project: V8LogScanner   File: RgxOpManager.java   Source Code and License 6 votes vote down vote up
public static RegExp anyMatch(String input, ConcurrentMap<RegExp, Pattern> eventPatterns) {

        RegExp foundEvent = null;

        Matcher matcher;
        Set<RegExp> keys = eventPatterns.keySet();
        for (RegExp event : keys) {
            Pattern pattern = eventPatterns.get(event);
            matcher = pattern.matcher(input);
            if (matcher.find()) {
                foundEvent = event;
                break;
            }
        }
        return foundEvent;
    }
 
Example 22
Project: EatDubbo   File: ConsumerServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findApplications() {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY);
    if(consumerUrls == null) return ret;
    
    for(Map.Entry<String, Map<Long, URL>> e1 : consumerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for(Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            String app = u.getParameter(Constants.APPLICATION_KEY);
            if(app != null) ret.add(app);
        }
    }
    
    return ret;
}
 
Example 23
Project: EatDubbo   File: ConsumerServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findApplicationsByServiceName(String service) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY);
    if(consumerUrls == null) return ret;
    
    Map<Long, URL> value = consumerUrls.get(service);
    if(value == null){
    	return ret;
    }
    for(Map.Entry<Long, URL> e2 : value.entrySet()) {
        URL u = e2.getValue();
        String app = u.getParameter(Constants.APPLICATION_KEY);
        if(app != null) ret.add(app);
    }
    
    return ret;
}
 
Example 24
Project: ditb   File: RegionCoprocessorHost.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor
 * @param impl the coprocessor instance
 * @param priority chaining priority
 */
public RegionEnvironment(final Coprocessor impl, final int priority,
    final int seq, final Configuration conf, final Region region,
    final RegionServerServices services, final ConcurrentMap<String, Object> sharedData) {
  super(impl, priority, seq, conf);
  this.region = region;
  this.rsServices = services;
  this.sharedData = sharedData;
  // Pick which version of the WAL related events we'll call.
  // This way we avoid calling the new version on older RegionObservers so
  // we can maintain binary compatibility.
  // See notes in javadoc for RegionObserver
  useLegacyPre = useLegacyMethod(impl.getClass(), "preWALRestore", ObserverContext.class,
      HRegionInfo.class, WALKey.class, WALEdit.class);
  useLegacyPost = useLegacyMethod(impl.getClass(), "postWALRestore", ObserverContext.class,
      HRegionInfo.class, WALKey.class, WALEdit.class);
}
 
Example 25
Project: EatDubbo   File: ProviderServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findApplicationsByServiceName(String service) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(null == providerUrls) return ret;
    
    Map<Long, URL> value = providerUrls.get(service);
    if(value == null){
    	return ret;
    }
    for(Map.Entry<Long, URL> e2 : value.entrySet()) {
        URL u = e2.getValue();
        String app = u.getParameter(Constants.APPLICATION_KEY);
        if(app != null) ret.add(app);
    }
    
    return ret;
}
 
Example 26
Project: github-test   File: ConsumerServiceImpl.java   Source Code and License 6 votes vote down vote up
public List<String> findApplicationsByServiceName(String service) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY);
    if (consumerUrls == null) return ret;

    Map<Long, URL> value = consumerUrls.get(service);
    if (value == null) {
        return ret;
    }
    for (Map.Entry<Long, URL> e2 : value.entrySet()) {
        URL u = e2.getValue();
        String app = u.getParameter(Constants.APPLICATION_KEY);
        if (app != null) ret.add(app);
    }

    return ret;
}
 
Example 27
Project: V8LogScanner   File: HeapOp.java   Source Code and License 6 votes vote down vote up
private ConcurrentMap<String, List<String>> mapLogs(ArrayList<String> sourceCol, String filename) {

        ConcurrentMap<String, List<String>> mapResults = null;

        if (groupType == GroupTypes.BY_PROPS) {
            mapResults = sourceCol
                    .parallelStream()
                    .unordered()
                    .filter(n -> RgxOpManager.anyMatch(n, eventPatterns, integerFilters, integerCompTypes))
                    .collect(Collectors.groupingByConcurrent(input -> {
                                return RgxOpManager.getEventProperty(input, eventPatterns, cleanPropsRgx, groupPropsRgx);
                            }
                    ));
        } else if (groupType == GroupTypes.BY_FILE_NAMES) {
            mapResults = sourceCol
                    .parallelStream()
                    .unordered()
                    .filter(n -> RgxOpManager.anyMatch(n, eventPatterns, integerFilters, integerCompTypes))
                    .collect(Collectors.groupingByConcurrent(n -> filename));
        }

        return mapResults;
    }
 
Example 28
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: ConsumerOffsetManager.java   Source Code and License 6 votes vote down vote up
public Set<String> whichGroupByTopic(final String topic) {
    Set<String> groups = new HashSet<String>();

    Iterator<Entry<String, ConcurrentMap<Integer, Long>>> it = this.offsetTable.entrySet().iterator();
    while (it.hasNext()) {
        Entry<String, ConcurrentMap<Integer, Long>> next = it.next();
        String topicAtGroup = next.getKey();
        String[] arrays = topicAtGroup.split(TOPIC_GROUP_SEPARATOR);
        if (arrays.length == 2) {
            if (topic.equals(arrays[0])) {
                groups.add(arrays[1]);
            }
        }
    }

    return groups;
}
 
Example 29
Project: googles-monorepo-demo   File: CacheTesting.java   Source Code and License 6 votes vote down vote up
static void checkEmpty(ConcurrentMap<?, ?> map) {
  checkEmpty(map.keySet());
  checkEmpty(map.values());
  checkEmpty(map.entrySet());
  assertEquals(ImmutableMap.of(), map);
  assertEquals(ImmutableMap.of().hashCode(), map.hashCode());
  assertEquals(ImmutableMap.of().toString(), map.toString());

  if (map instanceof LocalCache) {
    LocalCache<?, ?> cchm = (LocalCache<?, ?>) map;

    checkValidState(cchm);
    assertTrue(cchm.isEmpty());
    assertEquals(0, cchm.size());
    for (LocalCache.Segment<?, ?> segment : cchm.segments) {
      assertEquals(0, segment.count);
      assertEquals(0, segmentSize(segment));
      assertTrue(segment.writeQueue.isEmpty());
      assertTrue(segment.accessQueue.isEmpty());
    }
  }
}
 
Example 30
Project: ditb   File: SequenceIdAccounting.java   Source Code and License 5 votes vote down vote up
/**
 * We've been passed a new sequenceid for the region. Set it as highest seen for this region and
 * if we are to record oldest, or lowest sequenceids, save it as oldest seen if nothing
 * currently older.
 * @param encodedRegionName
 * @param families
 * @param sequenceid
 * @param lowest Whether to keep running account of oldest sequence id.
 */
void update(byte[] encodedRegionName, Set<byte[]> families, long sequenceid,
    final boolean lowest) {
  Long l = Long.valueOf(sequenceid);
  this.highestSequenceIds.put(encodedRegionName, l);
  if (lowest) {
    ConcurrentMap<byte[], Long> m = getOrCreateLowestSequenceIds(encodedRegionName);
    for (byte[] familyName : families) {
      m.putIfAbsent(familyName, l);
    }
  }
}
 
Example 31
Project: myfaces-trinidad   File: LRUCopyOnWriteArrayMapTest.java   Source Code and License 5 votes vote down vote up
public void testEvictionAtMiddleInsertAtTail()
{
  ConcurrentMap<String, Object> cache = createMap();
  _putThree(cache, A_STR, B_STR, C_STR);

  cache.get(A_STR);
  cache.get(C_STR);

  cache.put(D_STR, FOUR);
  assertOldestEvicted(cache, B_STR);
  assertContains(cache, A_STR, C_STR, D_STR);
}
 
Example 32
Project: myfaces-trinidad   File: FileSystemStyleCache.java   Source Code and License 5 votes vote down vote up
public Entry(
  List<String> uris,
  Styles styles,
  ConcurrentMap<String, Icon> icons,
  ConcurrentMap<Object, Object> skinProperties)
{
  this.uris = uris;
  this.styles = styles;
  this.icons = icons;
  this.skinProperties = skinProperties;
}
 
Example 33
Project: gemini.blueprint   File: BlueprintEditorRegistrar.java   Source Code and License 5 votes vote down vote up
public void registerCustomEditors(PropertyEditorRegistry registry) {
	// Date
	registry.registerCustomEditor(Date.class, new DateEditor());
	// Collection concrete types
	registry.registerCustomEditor(Stack.class, new BlueprintCustomCollectionEditor(Stack.class));
	registry.registerCustomEditor(Vector.class, new BlueprintCustomCollectionEditor(Vector.class));

	// Spring creates a LinkedHashSet for Collection, RFC mandates an ArrayList
	// reinitialize default editors
	registry.registerCustomEditor(Collection.class, new BlueprintCustomCollectionEditor(Collection.class));
	registry.registerCustomEditor(Set.class, new BlueprintCustomCollectionEditor(Set.class));
	registry.registerCustomEditor(SortedSet.class, new BlueprintCustomCollectionEditor(SortedSet.class));
	registry.registerCustomEditor(List.class, new BlueprintCustomCollectionEditor(List.class));
	registry.registerCustomEditor(SortedMap.class, new CustomMapEditor(SortedMap.class));

	registry.registerCustomEditor(HashSet.class, new BlueprintCustomCollectionEditor(HashSet.class));
	registry.registerCustomEditor(LinkedHashSet.class, new BlueprintCustomCollectionEditor(LinkedHashSet.class));
	registry.registerCustomEditor(TreeSet.class, new BlueprintCustomCollectionEditor(TreeSet.class));

	registry.registerCustomEditor(ArrayList.class, new BlueprintCustomCollectionEditor(ArrayList.class));
	registry.registerCustomEditor(LinkedList.class, new BlueprintCustomCollectionEditor(LinkedList.class));

	// Map concrete types
	registry.registerCustomEditor(HashMap.class, new CustomMapEditor(HashMap.class));
	registry.registerCustomEditor(LinkedHashMap.class, new CustomMapEditor(LinkedHashMap.class));
	registry.registerCustomEditor(Hashtable.class, new CustomMapEditor(Hashtable.class));
	registry.registerCustomEditor(TreeMap.class, new CustomMapEditor(TreeMap.class));
	registry.registerCustomEditor(Properties.class, new PropertiesEditor());

	// JDK 5 types
	registry.registerCustomEditor(ConcurrentMap.class, new CustomMapEditor(ConcurrentHashMap.class));
	registry.registerCustomEditor(ConcurrentHashMap.class, new CustomMapEditor(ConcurrentHashMap.class));
	registry.registerCustomEditor(Queue.class, new BlueprintCustomCollectionEditor(LinkedList.class));

	// Legacy types
	registry.registerCustomEditor(Dictionary.class, new CustomMapEditor(Hashtable.class));
}
 
Example 34
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: DefaultMessageStore.java   Source Code and License 5 votes vote down vote up
public ConsumeQueue findConsumeQueue(String topic, int queueId) {
    ConcurrentMap<Integer, ConsumeQueue> map = consumeQueueTable.get(topic);
    if (null == map) {
        ConcurrentMap<Integer, ConsumeQueue> newMap = new ConcurrentHashMap<Integer, ConsumeQueue>(128);
        ConcurrentMap<Integer, ConsumeQueue> oldMap = consumeQueueTable.putIfAbsent(topic, newMap);
        if (oldMap != null) {
            map = oldMap;
        } else {
            map = newMap;
        }
    }

    ConsumeQueue logic = map.get(queueId);
    if (null == logic) {
        ConsumeQueue newLogic = new ConsumeQueue(//
            topic, //
            queueId, //
            StorePathConfigHelper.getStorePathConsumeQueue(this.messageStoreConfig.getStorePathRootDir()), //
            this.getMessageStoreConfig().getMapedFileSizeConsumeQueue(), //
            this);
        ConsumeQueue oldLogic = map.putIfAbsent(queueId, newLogic);
        if (oldLogic != null) {
            logic = oldLogic;
        } else {
            logic = newLogic;
        }
    }

    return logic;
}
 
Example 35
Project: monarch   File: RegisterInterestTracker.java   Source Code and License 5 votes vote down vote up
/**
 * Return keys of interest for a given region. The keys in this Map are the full names of the
 * regions. The values are instances of RegionInterestEntry.
 *
 * @param interestType the type to return
 * @return the map
 */
public ConcurrentMap getRegionToInterestsMap(int interestType, boolean isDurable,
    boolean receiveUpdatesAsInvalidates) {
  FailoverInterestList fil =
      this.fils[getInterestLookupIndex(isDurable, receiveUpdatesAsInvalidates)];

  ConcurrentMap mapOfInterest = null;

  switch (interestType) {
    case InterestType.KEY:
      mapOfInterest = fil.keysOfInterest;
      break;
    case InterestType.REGULAR_EXPRESSION:
      mapOfInterest = fil.regexOfInterest;
      break;
    case InterestType.FILTER_CLASS:
      mapOfInterest = fil.filtersOfInterest;
      break;
    case InterestType.CQ:
      mapOfInterest = fil.cqsOfInterest;
      break;
    case InterestType.OQL_QUERY:
      mapOfInterest = fil.queriesOfInterest;
      break;
    default:
      throw new InternalGemFireError("Unknown interestType");
  }
  return mapOfInterest;
}
 
Example 36
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: ConsumerOffsetManager.java   Source Code and License 5 votes vote down vote up
private boolean offsetBehindMuchThanData(final String topic, ConcurrentMap<Integer, Long> table) {
    Iterator<Entry<Integer, Long>> it = table.entrySet().iterator();
    boolean result = !table.isEmpty();

    while (it.hasNext() && result) {
        Entry<Integer, Long> next = it.next();
        long minOffsetInStore = this.brokerController.getMessageStore().getMinOffsetInQueue(topic, next.getKey());
        long offsetInPersist = next.getValue();
        result = offsetInPersist <= minOffsetInStore;
    }

    return result;
}
 
Example 37
Project: sstore-soft   File: MapMakerInternalMap.java   Source Code and License 5 votes vote down vote up
SerializationProxy(Strength keyStrength, Strength valueStrength,
    Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence,
    long expireAfterWriteNanos, long expireAfterAccessNanos, int maximumSize,
    int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener,
    ConcurrentMap<K, V> delegate) {
  super(keyStrength, valueStrength, keyEquivalence, valueEquivalence, expireAfterWriteNanos,
      expireAfterAccessNanos, maximumSize, concurrencyLevel, removalListener, delegate);
}
 
Example 38
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: DefaultMessageStore.java   Source Code and License 5 votes vote down vote up
private void doFlush(int retryTimes) {
    /**
     * 变量含义:如果大于0,则标识这次刷盘必须刷多少个page,如果=0,则有多少刷多少
     */
    int flushConsumeQueueLeastPages = DefaultMessageStore.this.getMessageStoreConfig().getFlushConsumeQueueLeastPages();

    if (retryTimes == RETRY_TIMES_OVER) {
        flushConsumeQueueLeastPages = 0;
    }

    long logicsMsgTimestamp = 0;

    // 定时刷盘
    int flushConsumeQueueThoroughInterval = DefaultMessageStore.this.getMessageStoreConfig().getFlushConsumeQueueThoroughInterval();
    long currentTimeMillis = System.currentTimeMillis();
    if (currentTimeMillis >= (this.lastFlushTimestamp + flushConsumeQueueThoroughInterval)) {
        this.lastFlushTimestamp = currentTimeMillis;
        flushConsumeQueueLeastPages = 0;
        logicsMsgTimestamp = DefaultMessageStore.this.getStoreCheckpoint().getLogicsMsgTimestamp();
    }

    ConcurrentMap<String, ConcurrentMap<Integer, ConsumeQueue>> tables = DefaultMessageStore.this.consumeQueueTable;

    for (ConcurrentMap<Integer, ConsumeQueue> maps : tables.values()) {
        for (ConsumeQueue cq : maps.values()) {
            boolean result = false;
            for (int i = 0; i < retryTimes && !result; i++) {
                result = cq.flush(flushConsumeQueueLeastPages);
            }
        }
    }

    if (0 == flushConsumeQueueLeastPages) {
        if (logicsMsgTimestamp > 0) {
            DefaultMessageStore.this.getStoreCheckpoint().setLogicsMsgTimestamp(logicsMsgTimestamp);
        }
        DefaultMessageStore.this.getStoreCheckpoint().flush();
    }
}
 
Example 39
Project: JRediClients   File: RedissonMapCacheTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testReplaceOldValueFail() {
    ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMapCache("simple");
    map.put(new SimpleKey("1"), new SimpleValue("2"));

    boolean res = map.replace(new SimpleKey("1"), new SimpleValue("43"), new SimpleValue("31"));
    Assert.assertFalse(res);

    SimpleValue val1 = map.get(new SimpleKey("1"));
    Assert.assertEquals("2", val1.getValue());
}
 
Example 40
Project: googles-monorepo-demo   File: BenchmarkHelpers.java   Source Code and License 5 votes vote down vote up
@Override
<K, V> Map<K, V> create(Map<K, V> map) {
  ConcurrentMap<K, V> newMap = new MapMaker().weakValues().makeMap();
  checkState(newMap instanceof MapMakerInternalMap);
  newMap.putAll(map);
  return newMap;
}
 
Example 41
Project: vertx-zero   File: WallInquirer.java   Source Code and License 5 votes vote down vote up
/**
 * @param wallClses
 * @param keysRef
 * @return
 */
private JsonObject verify(final Set<Class<?>> wallClses,
                          final ConcurrentMap<String, Class<?>> keysRef) {
    /** Wall duplicated **/
    final Set<String> hashs = new HashSet<>();
    Observable.fromIterable(wallClses)
            .filter(Objects::nonNull)
            .map(item -> {
                final Annotation annotation = item.getAnnotation(Wall.class);
                // Add configuration key into keys;
                keysRef.put(Instance.invoke(annotation, "value"), item);
                return this.hashPath(annotation);
            }).subscribe(hashs::add);
    
    // Duplicated adding.
    Fn.flingUp(hashs.size() != wallClses.size(), LOGGER,
            WallDuplicatedException.class, getClass(),
            wallClses.stream().map(Class::getName).collect(Collectors.toSet()));

    /** Shared key does not existing **/
    final JsonObject config = NODE.read();
    Fn.flingUp(!config.containsKey(KEY), LOGGER,
            DynamicKeyMissingException.class, getClass(),
            KEY, config);

    /** Wall key missing **/
    final JsonObject hitted = config.getJsonObject(KEY);
    for (final String key : keysRef.keySet()) {
        Fn.flingUp(null == hitted || !hitted.containsKey(key), LOGGER,
                WallKeyMissingException.class, getClass(),
                key, keysRef.get(key));
    }
    return hitted;
}
 
Example 42
Project: guava-mock   File: ConcurrentHashMultiset.java   Source Code and License 5 votes vote down vote up
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
  stream.defaultReadObject();
  @SuppressWarnings("unchecked") // reading data stored by writeObject
  ConcurrentMap<E, Integer> deserializedCountMap =
      (ConcurrentMap<E, Integer>) stream.readObject();
  FieldSettersHolder.COUNT_MAP_FIELD_SETTER.set(this, deserializedCountMap);
}
 
Example 43
Project: dubbox-hystrix   File: AbstractZookeeperClient.java   Source Code and License 5 votes vote down vote up
public List<String> addChildListener(String path, final ChildListener listener) {
	ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
	if (listeners == null) {
		childListeners.putIfAbsent(path, new ConcurrentHashMap<ChildListener, TargetChildListener>());
		listeners = childListeners.get(path);
	}
	TargetChildListener targetListener = listeners.get(listener);
	if (targetListener == null) {
		listeners.putIfAbsent(listener, createTargetChildListener(path, listener));
		targetListener = listeners.get(listener);
	}
	return addTargetChildListener(path, targetListener);
}
 
Example 44
Project: monarch   File: ReferenceCountHelperImplTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void getReferenceCountInfoTestHook(
    ConcurrentMap<Long, List<RefCountChangeInfo>> stacktraces, long address) {
  List<RefCountChangeInfo> updatedList =
      new ArrayList<RefCountChangeInfo>(stacktraces.get(address));
  RefCountChangeInfo rcci = new RefCountChangeInfo(false, 0, "TestOwner");
  updatedList.add(rcci);
  stacktraces.put(address, updatedList);
}
 
Example 45
Project: zlikun-jee-design-pattern   File: Singleton3Test.java   Source Code and License 5 votes vote down vote up
@Test
public void test_multi() {

    // 使用ConcurrentHashMap代替HashSet(内部使用HashMap,不适用于并发),以应用于并发条件下
    final ConcurrentMap<Singleton3 ,Boolean> map = new ConcurrentHashMap<>() ;
    ExecutorService exec = Executors.newFixedThreadPool(400) ;

    // 约定一个执行时间(模拟并发,原因是类比较简单,初始化速度太快,无法真实再现并发情况)
    final long moment = System.currentTimeMillis() + 1000 ;
    for (int i = 0; i < 1000; i++) {
        exec.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // 到约定时间后再执行(构成并发)
                    if (moment < System.currentTimeMillis()) {
                        map.put(Singleton3.getInstance() ,Boolean.TRUE) ;
                        break;
                    }
                }
            }
        });
    }

    exec.shutdown();
    while (!exec.isTerminated()) ;

    // 如果元素个数为1,表示未生成不同实例
    Assert.assertEquals(1 ,map.size());
}
 
Example 46
Project: starcor.xul   File: XulCacheRecycle.java   Source Code and License 5 votes vote down vote up
public XulCacheModel recycle(ConcurrentMap<String, XulCacheModel> caches) {
    XulCacheModel cache = null;
    for (XulRecycleStrategy strategy : _strategies) {
        cache = strategy.findRecycledCache(caches.values());
        if (cache != null) {
            caches.remove(cache.getKey());
            break;
        }
    }

    return cache;
}
 
Example 47
Project: JRediClients   File: RedissonMapTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testReplaceOldValueSuccess() {
    ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
    map.put(new SimpleKey("1"), new SimpleValue("2"));

    boolean res = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3"));
    Assert.assertTrue(res);

    boolean res1 = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3"));
    Assert.assertFalse(res1);

    SimpleValue val1 = map.get(new SimpleKey("1"));
    Assert.assertEquals("3", val1.getValue());
}
 
Example 48
Project: JRediClients   File: RedissonMapTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPutIfAbsent() throws Exception {
    ConcurrentMap<SimpleKey, SimpleValue> map = redisson.getMap("simple");
    SimpleKey key = new SimpleKey("1");
    SimpleValue value = new SimpleValue("2");
    map.put(key, value);
    Assert.assertEquals(value, map.putIfAbsent(key, new SimpleValue("3")));
    Assert.assertEquals(value, map.get(key));

    SimpleKey key1 = new SimpleKey("2");
    SimpleValue value1 = new SimpleValue("4");
    Assert.assertNull(map.putIfAbsent(key1, value1));
    Assert.assertEquals(value1, map.get(key1));
}
 
Example 49
Project: manifold   File: ReflectUtil.java   Source Code and License 5 votes vote down vote up
private static void addRawMethodToCache( Class cls, Method m )
{
  ConcurrentMap<String, ConcurrentHashSet<Method>> methodsByName = _methodsByName.get( cls );
  if( methodsByName == null )
  {
    _methodsByName.put( cls, methodsByName = new ConcurrentHashMap<>() );
  }
  ConcurrentHashSet<Method> methods = methodsByName.get( m.getName() );
  if( methods == null )
  {
    methodsByName.put( m.getName(), methods = new ConcurrentHashSet<>( 2 ) );
  }
  methods.add( m );
}
 
Example 50
Project: openjdk-jdk10   File: Thread.java   Source Code and License 5 votes vote down vote up
/**
 * Removes from the specified map any keys that have been enqueued
 * on the specified reference queue.
 */
static void processQueue(ReferenceQueue<Class<?>> queue,
                         ConcurrentMap<? extends
                         WeakReference<Class<?>>, ?> map)
{
    Reference<? extends Class<?>> ref;
    while((ref = queue.poll()) != null) {
        map.remove(ref);
    }
}
 
Example 51
Project: dubbox-hystrix   File: ConsumerServiceImpl.java   Source Code and License 5 votes vote down vote up
public List<String> findAddressesByService(String service) {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY);
    if(null == consumerUrls) return ret;
    
    for(Map.Entry<Long, URL> e2 : consumerUrls.get(service).entrySet()) {
        URL u = e2.getValue();
        String app = u.getAddress();
        if(app != null) ret.add(app);
    }
    
    return ret;
}
 
Example 52
Project: Indra   File: RelatednessWorker.java   Source Code and License 5 votes vote down vote up
public RelatednessWorker(Map<AnalyzedPair, VectorPair> vectorPairs, List<AnalyzedPair> sortedPairs, int from,
                         int to, boolean sparse, ConcurrentMap<TextPair, ScoredTextPair> output) {
    this.vectorPairs = vectorPairs;
    this.sortedPairs = sortedPairs;
    this.from = from;
    this.to = to;
    this.sparse = sparse;
    this.output = output;
}
 
Example 53
Project: dubbocloud   File: RpcStatus.java   Source Code and License 5 votes vote down vote up
/**
 * 
 * @param url
 */
public static void removeStatus(URL url, String methodName) {
    String uri = url.toIdentityString();
    ConcurrentMap<String, RpcStatus> map = METHOD_STATISTICS.get(uri);
    if (map != null) {
        map.remove(methodName);
    }
}
 
Example 54
Project: RxBusLib   File: BusTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testRegisterNull() {
    StringCatcher catcher = null;
    bus.register(catcher);
    ConcurrentMap<EventType, SubscriberEvent> subscriptions = bus.getSubscriptions();
    assertEquals(0, subscriptions.size());
}
 
Example 55
Project: coon   File: AbstractZkTransporter.java   Source Code and License 5 votes vote down vote up
@Override
public void removeChildListener(String path, ChildListener listener) {
	ConcurrentMap<ChildListener, TargetChildListener> listeners = childListeners.get(path);
	if (listeners != null) {
		TargetChildListener targetListener = listeners.remove(listener);
		if (targetListener != null) {
			removeTargetChildListener(path, targetListener);
		}
	}
}
 
Example 56
Project: V8LogScanner   File: UserScanOp.java   Source Code and License 5 votes vote down vote up
public void execute(List<String> logFiles) {

        calc.start();

        saveProcessingInfo("\n*START OWN RGX LOG SCANNING...");

        resetResult();

        pattern = Pattern.compile(rgxExp, Pattern.DOTALL);

        ConcurrentMap<String, List<String>> rgxResult = new ConcurrentHashMap<>();

        for (String logFile : logFiles) {
            ArrayList<String> mapLogs = new ArrayList<>();
            try (RgxReader reader = new RgxReader(logFile, Constants.logsCharset, Constants.logEventsCount)) {

                ArrayList<String> readResult;

                while (reader.next()) {
                    readResult = reader.getResult();

                    inSize += readResult.size();
                    mapLogs.addAll(filterLogs(readResult));
                    outSize += mapLogs.size();
                    totalEvents += mapLogs.size();
                }

                if (mapLogs.size() > 0) {
                    rgxResult.put(logFile, mapLogs);
                }
            } catch (IOException e) {
                ExcpReporting.LogError(this.getClass(), e);
            }
            saveProcessingInfo(String.format("in: %s, out: %s, %s", inSize, outSize, logFile));
            inSize = 0;
            outSize = 0;
        }
        selector.setResult(rgxResult);
        calc.end();
    }
 
Example 57
Project: athena   File: VirtualPortWebResource.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a collection of virtualPorts.
 *
 * @param securityGroups the virtualPort jsonnode
 * @return a collection of securityGroups
 */
public Collection<SecurityGroup> jsonNodeToSecurityGroup(JsonNode securityGroups) {
    checkNotNull(securityGroups, JSON_NOT_NULL);
    ConcurrentMap<Integer, SecurityGroup> securMaps = Maps
            .newConcurrentMap();
    int i = 0;
    for (JsonNode node : securityGroups) {
        SecurityGroup securityGroup = SecurityGroup
                .securityGroup(node.asText());
        securMaps.put(i, securityGroup);
        i++;
    }
    return Collections.unmodifiableCollection(securMaps.values());
}
 
Example 58
Project: vertx-zero   File: Dual.java   Source Code and License 5 votes vote down vote up
private static ConcurrentMap<Integer, Object> mapIndex(
        final JsonArray sources,
        final String field
) {
    final ConcurrentMap<Integer, Object> resultMap =
            new ConcurrentHashMap<>();
    for (int idx = Values.IDX; idx < sources.size(); idx++) {
        final JsonObject item = sources.getJsonObject(idx);
        final Object value = item.getValue(field);
        if (null != value) {
            resultMap.put(idx, value);
        }
    }
    return resultMap;
}
 
Example 59
Project: stroom-stats   File: StatisticsFlatMappingServiceIT.java   Source Code and License 4 votes vote down vote up
@Test
    public void test_TwoGoodCountEventsRollUpAll() throws ExecutionException, InterruptedException, DatatypeConfigurationException {

        setAppIdPrefixes("");
        module = initStreamProcessing();

        Map<String, Object> senderProps = KafkaTestUtils.producerProps(kafkaEmbedded);
        KafkaProducer<String, String> producer = new KafkaProducer<>(senderProps, Serdes.String().serializer(), Serdes.String().serializer());

        StatisticType statisticType = StatisticType.COUNT;
        String topic = INPUT_TOPICS_MAP.get(statisticType);

        EventStoreTimeIntervalEnum interval = EventStoreTimeIntervalEnum.SECOND;

        addStatConfig(module.getMockStatisticConfigurationService(),
                GOOD_STAT_UUID,
                GOOD_STAT_NAME,
                statisticType,
                Arrays.asList(TAG_1, TAG_2),
                interval);

        ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC);

        Statistics statistics = StatisticsHelper.buildStatistics(
                StatisticsHelper.buildCountStatistic(time, 1L,
                        StatisticsHelper.buildTagType(TAG_1, TAG_1 + "val1"),
                        StatisticsHelper.buildTagType(TAG_2, TAG_2 + "val1")
                ),
                StatisticsHelper.buildCountStatistic(time.plusDays(2), 1L,
                        StatisticsHelper.buildTagType(TAG_1, TAG_1 + "val1"),
                        StatisticsHelper.buildTagType(TAG_2, TAG_2 + "val1")
                )
        );

        //Set a long purge retention to stop events being bumped up into the next interval
        setPurgeRetention(interval, Integer.MAX_VALUE);

        Map<String, Object> consumerProps = KafkaTestUtils.consumerProps("dummyGroup", "false", kafkaEmbedded);
        consumerProps.put("auto.offset.reset", "earliest");

//        startAllTopicsConsumer(consumerProps);

        ConcurrentMap<String, List<ConsumerRecord<StatEventKey, StatAggregate>>> topicToMsgsMap = new ConcurrentHashMap<>();
        List<BadStatMessage> badEvents = new ArrayList<>();

        //2 input msgs, each one is rolled up to 4 perms so expect 8
        int expectedGoodMsgCount = 2 * 4;
        int expectedBadMsgCount = 0;
        CountDownLatch intervalTopicsLatch = startIntervalTopicsConsumer(StatisticType.COUNT, consumerProps, expectedGoodMsgCount, topicToMsgsMap, true, 100);
        CountDownLatch badTopicsLatch = startBadEventsConsumer(consumerProps, expectedBadMsgCount, badEvents);

        //give the consumers and streams enough time to spin up
//        ThreadUtil.sleepAtLeastIgnoreInterrupts(1_000);

        LOGGER.info("Sending to {} stat events to topic {}", statistics.getStatistic().size(), topic);
        producer.send(buildProducerRecord(topic, GOOD_STAT_UUID, statistics)).get();
        producer.close();

        //Wait for the expected numbers of messages to arrive or timeout if not
        assertThat(intervalTopicsLatch.await(30, TimeUnit.SECONDS)).isTrue();
        assertThat(badTopicsLatch.await(30, TimeUnit.SECONDS)).isTrue();

        //both events go to same interval topic
        assertThat(topicToMsgsMap).hasSize(1);

        String topicName = topicToMsgsMap.keySet().stream().findFirst().get();
        assertThat(topicName).isEqualTo(TopicNameFactory.getIntervalTopicName(STATISTIC_ROLLUP_PERMS_TOPIC_PREFIX, statisticType, interval));
        List<ConsumerRecord<StatEventKey, StatAggregate>> messages = topicToMsgsMap.values().stream().findFirst().get();
        assertThat(messages).hasSize(expectedGoodMsgCount);

        //no bad events
        assertThat(badEvents).hasSize(expectedBadMsgCount);
    }
 
Example 60
Project: spring-io   File: WebConfigurerTest.java   Source Code and License 4 votes vote down vote up
@Override
public ConcurrentMap<String, Object> getUserContext() {
    return null;
}