Java Code Examples for com.hazelcast.core.IMap

The following are top voted examples for showing how to use com.hazelcast.core.IMap. 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: betleopard   File: RandomSimulationUtils.java   Source Code and License 8 votes vote down vote up
/**
 * Set up an event to hang the bets off  
 */
public default void createFutureEvent() {
    // Grab some horses to use as runners in races
    final IMap<Horse, Object> fromHC = getClient().getMap("winners");
    final Set<Horse> horses = fromHC.keySet();

    // Now set up some future-dated events for next Sat
    final LocalDate nextSat = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
    LocalTime raceTime = LocalTime.of(11, 0); // 1100 start
    final Event e = CentralFactory.eventOf("Racing from Epsom", nextSat);
    final Set<Horse> runners = makeRunners(horses, 10);
    for (int i = 0; i < 18; i++) {
        final Map<Horse, Double> runnersWithOdds = makeSimulatedOdds(runners);
        final Race r = CentralFactory.raceOf(LocalDateTime.of(nextSat, raceTime), runnersWithOdds);
        e.addRace(r);

        raceTime = raceTime.plusMinutes(10);
    }
    final IMap<Long, Event> events = getClient().getMap("events");
    events.put(e.getID(), e);
}
 
Example 2
Project: hazelcast-rest   File: HazelcastMapServlet.java   Source Code and License 7 votes vote down vote up
public void setValue(String map, String key, String contentType,
        int length, final InputStream in) throws IOException
{
    verifyBucket(map);

    byte type = mapContentType(contentType);
    IMap<String, byte[]> m = hazelcast.getMap(map);
    int offset = 1;
    byte[] data = new byte[length + offset];
    data[0] = type;
    int num;
    while ((num = in.read(data, offset, length)) > 0) {
        offset += num;
        if (offset >= data.length) {
            break;
        }
    }

    m.set(key, data);
}
 
Example 3
Project: cas-5.1.0   File: HazelcastTicketRegistry.java   Source Code and License 6 votes vote down vote up
@Override
public void addTicket(final Ticket ticket) {
    final long ttl = ticket.getExpirationPolicy().getTimeToLive();
    if (ttl < 0) {
        throw new IllegalArgumentException("The expiration policy of ticket "
                + ticket.getId() + "is set to use a negative ttl");
    }

    LOGGER.debug("Adding ticket [{}] with ttl [{}s]", ticket.getId(), ttl);
    final Ticket encTicket = encodeTicket(ticket);

    final TicketDefinition metadata = this.ticketCatalog.find(ticket);
    final IMap<String, Ticket> ticketMap = getTicketMapInstanceByMetadata(metadata);

    ticketMap.set(encTicket.getId(), encTicket, ttl, TimeUnit.SECONDS);
    LOGGER.debug("Added ticket [{}] with ttl [{}s]", encTicket.getId(), ttl);
}
 
Example 4
Project: rate-limiting   File: EMARateCalculator.java   Source Code and License 6 votes vote down vote up
private boolean lock(int hash, long waitTime) {

		if (rateRecordMap instanceof IMap) {
			if (logger.isDebugEnabled())
				logger.debug("Getting distributed lock for hash " + hash);
			return ((IMap) rateRecordMap).tryLock(hash, waitTime, LOCK_TIME_UNIT);
		} else {
			try {
				if (logger.isDebugEnabled())
					logger.debug("Getting local lock for hash " + hash);
				return lock.tryLock(waitTime, LOCK_TIME_UNIT);
			} catch (InterruptedException e) {
				logger.error("Failed to acquire lock for hash " + hash + ": " + e.getMessage());
				return false;
			}
		}
	}
 
Example 5
Project: light-oauth2   File: Oauth2RefreshTokenGetHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens");
    Deque<String> userIdDeque = exchange.getQueryParameters().get("userId");
    String userId = userIdDeque == null? "%" : userIdDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());
    if(logger.isDebugEnabled()) logger.debug("userId = " + userId + " page = " + page + " pageSize = " + pageSize);
    LikePredicate likePredicate = new LikePredicate("userId", userId);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new RefreshTokenComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<RefreshToken> values = tokens.values(pagingPredicate);

    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
}
 
Example 6
Project: hazelcast-wm   File: WebFilterClientFailOverTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testWhenClusterIsDownAtBeginningInDeferedMode() throws Exception {
    if (!testName.equals("client - not deferred")) {
        return;
    }

    hz.shutdown();
    CookieStore cookieStore = new BasicCookieStore();
    assertEquals("true", executeRequest("write", serverPort1, cookieStore));
    assertEquals("value", executeRequest("read", serverPort1, cookieStore));

    hz = Hazelcast.newHazelcastInstance(
            new FileSystemXmlConfig(new File(sourceDir + "/WEB-INF/", "hazelcast.xml")));
    assertClusterSizeEventually(1, hz);
    assertEquals("value", executeRequest("read", serverPort1, cookieStore));

    IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
    assertEquals(0, map.size());
}
 
Example 7
Project: light-oauth2   File: Oauth2UserPutHandler.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY);
    User user = Config.getInstance().getMapper().convertValue(body, User.class);
    String userId = user.getUserId();
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    User u = users.get(userId);
    if(u == null) {
        Status status = new Status(USER_NOT_FOUND, userId);
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
    } else {
        // as password is not in the return value, chances are password is not in the user object
        user.setPassword(u.getPassword());
        user.setUpdateDt(new Date(System.currentTimeMillis()));
        users.set(userId, user);
    }
}
 
Example 8
Project: light-oauth2   File: Oauth2UserUserIdGetHandler.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String userId = exchange.getQueryParameters().get("userId").getFirst();

    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    User user = users.get(userId);

    if(user == null) {
        Status status = new Status(USER_NOT_FOUND, userId);
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
        return;
    }
    // remove password here
    user.setPassword(null);
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(user));
}
 
Example 9
Project: light-oauth2   File: Oauth2UserGetHandler.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    Deque<String> userIdDeque = exchange.getQueryParameters().get("userId");
    String userId = userIdDeque == null? "%" : userIdDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());

    LikePredicate likePredicate = new LikePredicate("userId", userId);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new UserComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<User> values = users.values(pagingPredicate);

    for (User value : values) {
        value.setPassword(null);
    }
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
}
 
Example 10
Project: light-oauth2   File: Oauth2ServiceServiceIdGetHandler.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();

    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    Service service = services.get(serviceId);

    if(service == null) {
        Status status = new Status(SERVICE_NOT_FOUND, serviceId);
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
        return;
    }
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(service));
}
 
Example 11
Project: light-oauth2   File: Oauth2ClientClientIdGetHandler.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String clientId = exchange.getQueryParameters().get("clientId").getFirst();

    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);

    if(client == null) {
        Status status = new Status(CLIENT_NOT_FOUND, clientId);
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
        return;
    }
    Client c = Client.copyClient(client);
    c.setClientSecret(null);
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(c));
}
 
Example 12
Project: light-oauth2   File: Oauth2ClientGetHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Deque<String> clientNameDeque = exchange.getQueryParameters().get("clientName");
    String clientName = clientNameDeque == null? "%" : clientNameDeque.getFirst() + "%";
    int page = Integer.valueOf(exchange.getQueryParameters().get("page").getFirst()) - 1;
    Deque<String> pageSizeDeque = exchange.getQueryParameters().get("pageSize");
    int pageSize = pageSizeDeque == null? 10 : Integer.valueOf(pageSizeDeque.getFirst());

    LikePredicate likePredicate = new LikePredicate("clientName", clientName);

    PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ClientComparator(), pageSize);
    pagingPredicate.setPage(page);
    Collection<Client> values = clients.values(pagingPredicate);

    List results = new ArrayList();
    for (Client value : values) {
        Client c = Client.copyClient(value);
        c.setClientSecret(null);
        results.add(c);
    }
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(results));
}
 
Example 13
Project: light-oauth2   File: CacheStartupHookProviderTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testClientCache() {
    CacheStartupHookProvider start = new CacheStartupHookProvider();
    start.onStartup();

    final IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");

    Client client = clients.get("f7d42348-c647-4efb-a52d-4c5787421e72");
    System.out.println("client = " + client);

    client.setClientType(Client.ClientTypeEnum.fromValue("trusted"));

    clients.put("f7d42348-c647-4efb-a52d-4c5787421e72", client);
    System.out.println("clients size = " + clients.size());

    clients.delete("f7d42348-c647-4efb-a52d-4c5787421e72");
    System.out.println("clients size = " + clients.size());

    CacheShutdownHookProvider shutdown = new CacheShutdownHookProvider();
    shutdown.onShutdown();

}
 
Example 14
Project: ratelimitj   File: HazelcastRequestRateLimiterInternalTest.java   Source Code and License 6 votes vote down vote up
@Test
void shouldEventuallyCleanUpExpiredKeys() throws Exception {
    ImmutableSet<RequestLimitRule> rules = ImmutableSet.of(RequestLimitRule.of(2, TimeUnit.SECONDS, 5));
    RequestRateLimiter requestRateLimiter = getRateLimiter(rules, timeBandit);

    String key = "ip:127.0.0.5";

    IntStream.rangeClosed(1, 5).forEach(value -> {
        timeBandit.addUnixTimeMilliSeconds(100L);
        assertThat(requestRateLimiter.overLimitWhenIncremented(key)).isFalse();
    });

    IMap<Object, Object> map = hz.getMap(key);
    while (map.size() != 0) {
        Thread.sleep(10);
    }
    assertThat(map.size()).isZero();
}
 
Example 15
Project: hazelcast-demo   File: ListenerDemo.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	HazelcastInstance ins = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> map = ins.getMap("");
	map.addEntryListener(new ListenerExample(), true);//添加自定义监听器
	map.put(1, "Grand Theft Auto");
	map.put(1, "Final Fantasy");
	map.put(2, "World Of Warcraft");
	
	HazelcastInstance insex = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> mapex = insex.getMap("");
	
	System.out.println(mapex.get(1));
	System.out.println(mapex.get(2));
	mapex.remove(1);
	mapex.remove(2);
	System.exit(0);
}
 
Example 16
Project: cms   File: HazelcastDistributedCacheManager.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <K, V> IMap<K, V> getCache(String cacheName) {
    if (caches.get(cacheName) == null) {
        synchronized (this) {
            if (caches.get(cacheName) == null) {
                final IMap<K, V> map = this.hazelcastInstance.getMap(cacheName);
                caches.putIfAbsent(cacheName, map);

                return map;
            }
        }
    }

    return caches.get(cacheName);
}
 
Example 17
Project: bigstreams   File: CoordinationDI.java   Source Code and License 6 votes vote down vote up
@Bean
public HazelcastFileTrackerStorage hazelcastFileTrackerStorage() {
	HazelcastInstance hazelcastInstance = beanFactory
			.getBean(HazelcastInstance.class);

	IMap<FileTrackingStatusKey, FileTrackingStatus> fileTrackerMemory = hazelcastInstance
			.getMap(DistributedMapNames.MAP.FILE_TRACKER_MAP.toString());

	IMap<String, AgentContact> agentSet = hazelcastInstance
			.getMap(DistributedMapNames.MAP.AGENT_NAMES.toString());

	IMap<String, LogTypeContact> logTypeSet = hazelcastInstance
			.getMap(DistributedMapNames.MAP.LOG_TYPES.toString());

	return new HazelcastFileTrackerStorage(fileTrackerMemory, logTypeSet,
			agentSet);
}
 
Example 18
Project: bigstreams   File: HazelcastLockMemory.java   Source Code and License 6 votes vote down vote up
public HazelcastLockMemory(IMap<String, LockValue> locksMap) {
	super();
	this.locksMap = locksMap;
	
	LOG.info("HazelcastLockMemory ----- MAP_ID: " + locksMap.getId());
	LOG.info("HazelcastLockMemory ----- MAP_NAME: " + locksMap.getName());
	LOG.info("HazelcastLockMemory ----- MAP_STRING: " + locksMap.toString());
	LOG.info("HazelcastLockMemory ----- MAP_INSTANCE_TYPE: " + locksMap.getInstanceType());
	
	MapConfig mapConf = Hazelcast.getConfig().getMapConfig(DistributedMapNames.MAP.LOCK_MEMORY_LOCKS_MAP.toString());
	
	MapStoreConfig mapStoreConf = mapConf.getMapStoreConfig();
	
	if(mapStoreConf == null){
		LOG.info("HazelcastLockMemory ----- MAPSTORE NULL");	
	}else{
		LOG.info("HazelcastLockMemory ----- MAPSTORE IMPL: " + mapStoreConf.getImplementation());
	}
	
	
}
 
Example 19
Project: bigstreams   File: HazelcastFileTrackerStorage.java   Source Code and License 6 votes vote down vote up
/**
 * Requires a hazelcast map.
 * 
 * @param fileTrackerMemory
 * @param logTypeSet
 *            stores the log types
 * @param agentSet
 */
public HazelcastFileTrackerStorage(
		IMap<FileTrackingStatusKey, FileTrackingStatus> fileTrackerMemory,
		IMap<String, LogTypeContact> logTypeSet, IMap<String, AgentContact> agentSet) {

	this.fileTrackerMemoryMap = fileTrackerMemory;
	this.logTypeSet = logTypeSet;
	this.agentSet = agentSet;

	MapConfig mapConf = Hazelcast.getConfig().getMapConfig(
			DistributedMapNames.MAP.FILE_TRACKER_MAP.toString());

	MapStoreConfig mapStoreConf = mapConf.getMapStoreConfig();

	if (mapStoreConf == null) {
		LOG.info("HazelcastFileTrackerStorage ----- MAPSTORE NULL");
	} else {
		LOG.info("HazelcastFileTrackerStorage ----- MAPSTORE IMPL: "
				+ mapStoreConf.getImplementation());
	}

}
 
Example 20
Project: bigstreams   File: TestHazelcastLockMemory.java   Source Code and License 6 votes vote down vote up
/**
 * Test that if a different collector tries to unlock a lock held by another
 * collector it is blocked from doing so.
 * 
 * @throws Exception
 */
@Test
public void testMultipleLockUnLockFromDifferentCollector() throws Exception {

	IMap<String, LockValue> locksMap = Hazelcast.getMap(
			DistributedMapNames.MAP.LOCK_MEMORY_LOCKS_MAP.toString());
	
	final HazelcastLockMemory memory = new HazelcastLockMemory(locksMap);
	/**
	 * (long filePointer, long fileSize,int linePointer, String agentName,
	 * String fileName, String logType)
	 */
	final FileTrackingStatus status = new FileTrackingStatus(new Date(), 0L, 0L, 1,
			"agent1", "file1", "type1", new Date(), 1L);

	SyncPointer pointer = memory.setLock(status, "localhost1");
	assertNotNull(pointer);

	assertNull(memory.removeLock(pointer, "localhost2"));
	assertNotNull(memory.removeLock(pointer, "localhost1"));

}
 
Example 21
Project: jpoint-2016-computing-talk   File: WordCountExample.java   Source Code and License 6 votes vote down vote up
private static void fillMapWithData(HazelcastInstance hazelcastInstance)
    throws Exception {

    IMap<String, String> map = hazelcastInstance.getMap(MAP_NAME);
    for (String file : DATA_RESOURCES_TO_LOAD) {
        InputStream is = WordCountExample.class.getResourceAsStream("/wordcount/" + file);
        LineNumberReader reader = new LineNumberReader(new InputStreamReader(is));

        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        map.put(file, sb.toString());

        is.close();
        reader.close();
    }
}
 
Example 22
Project: subzero   File: ClassLoadingTest.java   Source Code and License 6 votes vote down vote up
@Test
public void givenClientHasClassLoaderConfigured_whenObjectIsFetched_thenClassLoaderWillBeUsed() throws Exception {
    Config memberConfig = new Config();
    SubZero.useAsGlobalSerializer(memberConfig);
    hazelcastFactory.newHazelcastInstance(memberConfig);

    ClientConfig clientConfig = new ClientConfig();
    ClassLoader clientClassLoader = createSpyingClassLoader();
    clientConfig.setClassLoader(clientClassLoader);
    SubZero.useAsGlobalSerializer(clientConfig);
    HazelcastInstance client = hazelcastFactory.newHazelcastClient(clientConfig);
    IMap<Integer, Object> myMap = client.getMap(randomMapName());
    myMap.put(0, new MyClass());

    myMap.get(0);

    verify(clientClassLoader).loadClass("info.jerrinot.subzero.ClassLoadingTest$MyClass");
}
 
Example 23
Project: subzero   File: TestCustomerSerializers.java   Source Code and License 6 votes vote down vote up
@Test
public void testGlobalCustomDelegateSerializationConfiguredProgrammaticallyForClientConfig() {
    Config memberConfig = new Config();
    SubZero.useAsGlobalSerializer(memberConfig);
    hazelcastFactory.newHazelcastInstance(memberConfig);

    String mapName = randomMapName();
    ClientConfig config = new ClientConfig();

    SubZero.useAsGlobalSerializer(config, MyGlobalDelegateSerlizationConfig.class);

    HazelcastInstance member = hazelcastFactory.newHazelcastClient(config);
    IMap<Integer, AnotherNonSerializableObject> myMap = member.getMap(mapName);
    myMap.put(0, new AnotherNonSerializableObject());
    AnotherNonSerializableObject fromCache = myMap.get(0);

    assertEquals("deserialized", fromCache.name);
}
 
Example 24
Project: greycat   File: HazelcastTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.addAddress("127.0.0.1:5701");
    HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
    IMap map = client.getMap("customers");
    System.out.println("Map Size:" + map.size());

    client.getDurableExecutorService("hello").submit(new HazelcastJob(() -> System.out.println("Hello")));

}
 
Example 25
Project: cas-5.1.0   File: HazelcastMonitor.java   Source Code and License 5 votes vote down vote up
@Override
protected CacheStatistics[] getStatistics() {
    final List<CacheStatistics> statsList = new ArrayList<>();
    final HazelcastProperties hz = casProperties.getTicket().getRegistry().getHazelcast();
    LOGGER.debug("Locating hazelcast instance [{}]...", hz.getCluster().getInstanceName());
    final HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName(hz.getCluster().getInstanceName());

    instance.getConfig().getMapConfigs().keySet().forEach(key -> {
        final IMap map = instance.getMap(key);
        LOGGER.debug("Starting to collect hazelcast statistics for map [{}] identified by key [{}]...", map, key);
        statsList.add(new HazelcastStatistics(map, hz.getCluster().getMembers().size()));
    });
    return statsList.toArray(new CacheStatistics[statsList.size()]);
}
 
Example 26
Project: cas-5.1.0   File: HazelcastTicketRegistry.java   Source Code and License 5 votes vote down vote up
@Override
public boolean deleteSingleTicket(final String ticketId) {
    final String encTicketId = encodeTicketId(ticketId);
    final TicketDefinition metadata = this.ticketCatalog.find(ticketId);
    final IMap<String, Ticket> map = getTicketMapInstanceByMetadata(metadata);
    return map.remove(encTicketId) != null;
}
 
Example 27
Project: cas-5.1.0   File: HazelcastTicketRegistry.java   Source Code and License 5 votes vote down vote up
@Override
public long deleteAll() {
    final Collection<TicketDefinition> metadata = this.ticketCatalog.findAll();
    final AtomicLong count = new AtomicLong();
    metadata.forEach(r -> {
        final IMap<String, Ticket> instance = getTicketMapInstanceByMetadata(r);
        if (instance != null) {
            count.addAndGet(instance.size());
            instance.evictAll();
            instance.clear();
        }
    });
    return count.get();
}
 
Example 28
Project: cas-5.1.0   File: HazelcastTicketRegistry.java   Source Code and License 5 votes vote down vote up
@Override
public Collection<Ticket> getTickets() {
    final Collection<Ticket> tickets = new HashSet<>();
    try {
        final Collection<TicketDefinition> metadata = this.ticketCatalog.findAll();
        metadata.forEach(t -> {
            final IMap<String, Ticket> map = getTicketMapInstanceByMetadata(t);
            tickets.addAll(map.values().stream().limit(this.pageSize).collect(Collectors.toList()));
        });
        return tickets;
    } catch (final Exception e) {
        LOGGER.warn(e.getMessage(), e);
    }
    return decodeTickets(tickets);
}
 
Example 29
Project: cas-5.1.0   File: HazelcastTicketRegistry.java   Source Code and License 5 votes vote down vote up
private IMap<String, Ticket> getTicketMapInstance(final String mapName) {
    try {
        final IMap<String, Ticket> inst = hazelcastInstance.getMap(mapName);
        LOGGER.debug("Located Hazelcast map instance [{}] for [{}]", inst, mapName);
        return inst;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
 
Example 30
Project: teamcity-gradle-build-cache-plugin   File: BuildCachePage.java   Source Code and License 5 votes vote down vote up
public void fillModel(@NotNull Map<String, Object> model, @NotNull HttpServletRequest request) {
    HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName(INSTANCE_NAME);
    if (instance != null) {
        IMap<String, byte[]> taskCache = instance.getMap(TASK_CACHE_NAME);
        LocalMapStats statistics = taskCache.getLocalMapStats();
        model.put("statistics", statistics);
    }
}
 
Example 31
Project: xm-commons   File: InitRefreshableConfigurationBeanPostProcessor.java   Source Code and License 5 votes vote down vote up
private void initBean(RefreshableConfiguration refreshableConfiguration) {
    IMap<String, String> configMap = hazelcastInstance.getMap(TENANT_CONFIGURATION_MAP);

    configMap.forEach((key, value) -> {
        if (refreshableConfiguration.isListeningConfiguration(key)) {

            log.info(
                "Process config init event: [key = {}, size = {}, newHash = {}] in bean: [{}]",
                key,
                StringUtils.length(value),
                getValueHash(value),
                getBeanName(refreshableConfiguration));

            refreshableConfiguration.onInit(key, value);
        }
    });

    log.info("refreshable configuration bean [{}] initialized by configMap with {} entries",
             getBeanName(refreshableConfiguration), configMap.size());

    final boolean includeValue = true;
    configMap.addEntryListener((EntryAddedListener<String, String>) e -> {
        onEntryChange(refreshableConfiguration, e, configMap);
    }, includeValue);
    configMap.addEntryListener((EntryRemovedListener<String, String>) e -> {
        onEntryChange(refreshableConfiguration, e, configMap);
    }, includeValue);
    configMap.addEntryListener((EntryUpdatedListener<String, String>) e -> {
        onEntryChange(refreshableConfiguration, e, configMap);
    }, includeValue);
}
 
Example 32
Project: xm-commons   File: InitRefreshableConfigurationBeanPostProcessor.java   Source Code and License 5 votes vote down vote up
private void onEntryChange(RefreshableConfiguration refreshableConfiguration,
                           EntryEvent<String, String> entry,
                           IMap<String, String> configMap) {

    String entryKey = entry.getKey();
    String configContent = configMap.get(entryKey);

    if (refreshableConfiguration.isListeningConfiguration(entryKey)) {

        refreshableConfiguration.onRefresh(entryKey, configContent);

        log.info(
            "Process config update event: "
            + "[key = {}, evtType = {}, size = {}, newHash = {}, oldHash = {}] in bean: [{}]",
            entryKey,
            entry.getEventType(),
            StringUtils.length(configContent),
            getValueHash(configContent),
            getValueHash(entry.getOldValue()),
            getBeanName(refreshableConfiguration));

    } else {
        log.debug("Ignored config update event: [key = {}, evtType = {}, configSize = {} in bean [{}]",
                  entryKey,
                  entry.getEventType(),
                  StringUtils.length(configContent),
                  getBeanName(refreshableConfiguration));
    }
}
 
Example 33
Project: rate-limiting   File: RateLimitingFilter.java   Source Code and License 5 votes vote down vote up
private void applyConfig(RateLimitingSettings newSettings) {
	logger.info("applying new rate limiting settings");
	enabled = newSettings.isEnabled();
	if (!enabled) {
		logger.warn(
				"Rate limiting is configured to be disabled! Set 'isEnabled' to 'true' in the configuration file to activate");
		return;
	}

	if (statsManager != null)
		statsManager.unregisterBeans();

	Label.clearFilters();
	disabledForHeaders = newSettings.getDisabledForHeaders();

	labels = new ArrayList<Label>();

	if (newSettings.getLabels() != null)
		for (LabelDefinition ld : newSettings.getLabels()) {
			if (ld.isEnabled())
				labels.add(Label.fromLabelDefinition(ld, newSettings, filterId));
		}

	logger.info("Loaded " + labels.size() + " label" + (labels.size() == 1 ? "" : "s"));

	IMap<Integer, EMARateHistory> map = getHZ().getMap(newSettings.getHazelcastConfig().getMapName());
	rateCalculator = new EMARateCalculator(map);
}
 
Example 34
Project: testcontainers-hazelcast   File: NativeTestingHazelcast.java   Source Code and License 5 votes vote down vote up
@Test
public void simpleTest() throws Exception {
    final IMap<Integer, String> testMapFromMember = member.getMap("testMap");
    testMapFromMember.set(1, "test1");

    final IMap<Integer, String> testMap = client.getMap("testMap");
    final String value = testMap.get(1);
    assertEquals("member puts, client gets", value, "test1");
}
 
Example 35
Project: micrometer   File: HazelcastCacheMetricsTest.java   Source Code and License 5 votes vote down vote up
@Test
void cacheMetrics() {
    IMap<String, String> map = h.getMap("my-distributed-map");

    SimpleMeterRegistry registry = new SimpleMeterRegistry();
    HazelcastCacheMetrics.monitor(registry, map, "cache",emptyList());

    map.put("key", "value");
    map.get("key");

    assertThat(registry.mustFind("cache.gets").functionTimer().count()).isEqualTo(1L);
    assertThat(registry.mustFind("cache.puts").functionTimer().count()).isEqualTo(1L);
}
 
Example 36
Project: betleopard   File: RandomSimulationUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Return a {@code Race} at random from the provided set
 * 
 * @param eventsByID
 * @return 
 */
public static Race getRandomRace(final IMap<Long, Event> eventsByID) {
    final List<Event> events = new ArrayList<>(eventsByID.values());
    final int rI = new Random().nextInt(events.size());
    final Event theDay = events.get(rI);
    final List<Race> races = theDay.getRaces();
    final int rR = new Random().nextInt(races.size());
    return races.get(rR);
}
 
Example 37
Project: betleopard   File: RandomSimulationUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Sets up some random users (to place bets) and stores them in Hazlecast IMDG
 */
public default void createRandomUsers() {
    final IMap<Long, User> users = getClient().getMap("users");

    final String[] firstNames = {"Dave", "Christine", "Sarah", "Sadiq", "Zoe", "Helen", "Mike", "George", "Joanne"};
    final String[] lastNames = {"Baker", "Jones", "Smith", "Singh", "Shah", "Johnson", "Taylor", "Evans", "Howe"};
    final Random r = new Random();
    for (int i = 0; i < NUM_USERS; i++) {
        final User u = CentralFactory.userOf(firstNames[r.nextInt(firstNames.length)], lastNames[r.nextInt(lastNames.length)]);
        users.put(u.getID(), u);
    }
}
 
Example 38
Project: betleopard   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * Return a {@code Race} at random from the provided set
 * 
 * @param eventsByID
 * @return 
 */
public static Race getRandomRace(final IMap<Long, Event> eventsByID) {
    final List<Event> events = new ArrayList<>(eventsByID.values());
    final int rI = new Random().nextInt(events.size());
    final Event theDay = events.get(rI);
    final List<Race> races = theDay.getRaces();
    final int rR = new Random().nextInt(races.size());
    return races.get(rR);
}
 
Example 39
Project: light-oauth2   File: Oauth2RefreshTokenRefreshTokenDeleteHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String refreshToken = exchange.getQueryParameters().get("refreshToken").getFirst();
    if(logger.isDebugEnabled()) logger.debug("refreshToken = " + refreshToken);
    IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens");
    if(tokens.get(refreshToken) == null) {
        Status status = new Status(REFRESH_TOKEN_NOT_FOUND, refreshToken);
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
    } else {
        tokens.delete(refreshToken);
    }
}
 
Example 40
Project: hazelcast-wm   File: WebFilterSlowTests.java   Source Code and License 5 votes vote down vote up
@Test(timeout = 60000)
public void testAttributeInvalidate() throws Exception {
    IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
    CookieStore cookieStore = new BasicCookieStore();
    assertEquals("true", executeRequest("write", serverPort1, cookieStore));
    assertEquals(1, map.size());
    assertEquals("value", executeRequest("read", serverPort2, cookieStore));
    assertEquals("true", executeRequest("invalidate", serverPort2, cookieStore));
    assertTrue(map.isEmpty());
}