/** * 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); }
@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); }
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; } } }
@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)); }
@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()); }
@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); } }
@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)); }
@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)); }
@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)); }
@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)); }
@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)); }
@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(); }
@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(); }
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); }
@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); }
@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); }
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()); } }
/** * 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()); } }
/** * 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")); }
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(); } }
@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"); }
@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); }
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); }
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"))); }
@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()]); }
@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; }
@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(); }
@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); }
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; }
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); } }
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); }
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)); } }
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); }
private void storeAndUnlock(int hash, EMARateHistory history) { if (rateRecordMap instanceof IMap) { ((IMap) rateRecordMap).putAndUnlock(hash, history); } else { rateRecordMap.put(hash, history); lock.unlock(); } }
@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"); }
@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); }
/** * 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); }
/** * 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); } }
@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); } }