com.hazelcast.core.IMap Java Examples
The following examples show how to use
com.hazelcast.core.IMap.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TimeSeriesMiniCubeManagerHzImpl.java From minicubes with Apache License 2.0 | 6 votes |
@Override protected String post(MiniCube newMiniCube) { Member localMember = instance.getCluster().getLocalMember(); String member = cubeId.split("@")[1]; // Ending build operation impl.miniCube = newMiniCube; String newCubeId = timeSeries + "::" + impl.hzGroupName + "@" + member; LOGGER.info("Success to build cube {} from {} and {}", newCubeId, cubeId, timeSeries); // Put relationship into member localMember.setStringAttribute("cubeId", newCubeId); IMap<String, String> miniCubeManager = instance.getMap(MINICUBE_MANAGER); miniCubeManager.put(member, newCubeId); return newCubeId; }
Example #2
Source File: Oauth2ClientPutHandler.java From light-oauth2 with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public void handleRequest(HttpServerExchange exchange) throws Exception { Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY); Client client = Config.getInstance().getMapper().convertValue(body, Client.class); if(client.getDerefClientId() != null && Client.ClientTypeEnum.EXTERNAL != client.getClientType()) { // only external client may have deref client id setExchangeStatus(exchange, DEREF_NOT_EXTERNAL); return; } String clientId = client.getClientId(); IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients"); Client originalClient = clients.get(clientId); if(originalClient == null) { setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId); } else { // set client secret as it is not returned by query. client.setClientSecret(originalClient.getClientSecret()); clients.set(clientId, client); } processAudit(exchange); }
Example #3
Source File: InventoryItemCreatedHandler.java From cqrs-eventsourcing-kafka with Apache License 2.0 | 6 votes |
@Override public void handle(InventoryItemCreated event) { IMap<String, InventoryItemListItem> inventoryItems = getInventoryItemsMap(); String id = event.id.toString(); InventoryItemListItem item = inventoryItems.get(id); if (item == null) { item = new InventoryItemListItem(); item.id = id; item.name = event.getName(); item.version = event.version; inventoryItems.put(id, item); } }
Example #4
Source File: Oauth2UserGetHandler.java From light-oauth2 with Apache License 2.0 | 6 votes |
@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(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values)); processAudit(exchange); }
Example #5
Source File: HazelcastLockProvider.java From ShedLock with Apache License 2.0 | 6 votes |
@Override @NonNull public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) { log.trace("lock - Attempt : {}", lockConfiguration); final Instant now = ClockProvider.now(); final String lockName = lockConfiguration.getName(); final IMap<String, HazelcastLock> store = getStore(); try { // lock the map key entry store.lock(lockName, keyLockTime(lockConfiguration), TimeUnit.MILLISECONDS); // just one thread at a time, in the cluster, can run this code // each thread waits until the lock to be unlock if (tryLock(lockConfiguration, now)) { return Optional.of(new HazelcastSimpleLock(this, lockConfiguration)); } } finally { // released the map lock for the others threads store.unlock(lockName); } return Optional.empty(); }
Example #6
Source File: HazelcastRequestRateLimiterInternalTest.java From ratelimitj with Apache License 2.0 | 6 votes |
@Test void shouldEventuallyCleanUpExpiredKeys() throws Exception { ImmutableSet<RequestLimitRule> rules = ImmutableSet.of(RequestLimitRule.of(Duration.ofSeconds(2), 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 #7
Source File: CallOutQuene.java From youkefu with Apache License 2.0 | 6 votes |
/** * 获得 当前服务状态 * @param orgi * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static AgentReport getCallCenterAgentReport(String orgi){ /** * 统计当前在线的坐席数量 */ AgentReport report = new AgentReport() ; IMap callCenterAgentMap = (IMap<String, Object>) CacheHelper.getCallCenterAgentCacheBean().getCache() ; Long agents = (Long) callCenterAgentMap.aggregate(Aggregators.<Map.Entry<String, CallCenterAgent>>count(), new CallCenterAgentOrgiFilterPredicate(orgi)) ; report.setAgents(agents.intValue()); Long readyAgent = (Long) callCenterAgentMap.aggregate(Aggregators.<Map.Entry<String, CallCenterAgent>>count(), new CallCenterAgentReadyOrgiFilterPredicate(orgi)) ; report.setReadyagents(readyAgent.intValue()); Long inCallAgent = (Long) callCenterAgentMap.aggregate(Aggregators.<Map.Entry<String, CallCenterAgent>>count(), new CallCenterInCallOrgiFilterPredicate(orgi)) ; report.setIncall(inCallAgent.intValue()); report.setOrgi(orgi); return report; }
Example #8
Source File: ListenerDemo.java From hazelcast-demo with Apache License 2.0 | 6 votes |
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 #9
Source File: Oauth2UserUserIdGetHandler.java From light-oauth2 with Apache License 2.0 | 6 votes |
@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) { setExchangeStatus(exchange, USER_NOT_FOUND, userId); processAudit(exchange); return; } // remove password here user.setPassword(null); exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json"); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(user)); processAudit(exchange); }
Example #10
Source File: TimeToLiveExample.java From chuidiang-ejemplos with GNU Lesser General Public License v3.0 | 6 votes |
public static void main( String[] args ) throws FileNotFoundException, InterruptedException { Config config = new Config(); HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config); IMap<String,String> map = hazelcastInstance.getMap("TimeToLiveMap"); map.put("hola", "tu", 10, TimeUnit.SECONDS); while (true){ Thread.sleep(1000); String dato =map.get("hola"); if (null!=dato){ System.out.println(dato); } else { break; } } System.out.println("Data expired"); }
Example #11
Source File: TimeSeriesMiniCubeManagerHzImpl.java From minicubes with Apache License 2.0 | 6 votes |
private void handleNewMember(HazelcastInstance instance, Member member) { // Relationship between Member and MiniCube ID IMap<String, String> miniCubeManager = instance.getMap(MINICUBE_MANAGER); LOGGER.info("Minicube manager status {}", ObjectUtils.getDisplayString(miniCubeManager)); String key = member.getSocketAddress().toString(); // FIXME: load-pending status need refactor instance.getCluster().getLocalMember().setBooleanAttribute("load-pending", false); if (miniCubeManager.containsKey(key) && !miniCubeManager.get(key).startsWith("?")) { // Maybe node-restart LOGGER.info("A node{} restarted, so we need rebuild cube{}", key, miniCubeManager.get(key)); // Reassign task. reassignRole(miniCubeManager.get(key), miniCubeManager.get(key).split("::")[0]); } else { // First time join into cluster String id = "?" + "::" + hzGroupName + "@" + key; miniCubeManager.put(key, id); member.setStringAttribute("cubeId", id); LOGGER.info("Add {} into cluster {}", id, hzGroupName); } LOGGER.info("Set load-pending status to false, enable reassign feature on {}", member); }
Example #12
Source File: SQLDBCacheMetadata.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
public CacheItem getCacheItem(String signature, boolean isHash) { if (isHash) { CacheItem cacheItem = null; IMap mapLocks = DistributedLockFactory.getDistributedMap(SpagoBIConstants.DISTRIBUTED_MAP_INSTANCE_NAME, SpagoBIConstants.DISTRIBUTED_MAP_FOR_CACHE); mapLocks.lock(signature); // it is possible to use also the method tryLock(...) with timeout parameter try { cacheItem = cacheDao.loadCacheItemBySignature(signature); if (cacheItem != null) { logger.debug("The dataset with hash [" + signature + "] has been found in cache"); } else { logger.debug("The dataset with hash [" + signature + "] does not exist in cache"); } } finally { mapLocks.unlock(signature); } return cacheItem; } else { return getCacheItem(signature); } }
Example #13
Source File: Oauth2ProviderPutHandler.java From light-oauth2 with Apache License 2.0 | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY); Provider provider = Config.getInstance().getMapper().convertValue(body, Provider.class); String provider_id = provider.getProviderId() ; IMap<String, Provider> providers = CacheStartupHookProvider.hz.getMap("providers"); if(providers.get(provider_id) == null) { setExchangeStatus(exchange, PROVIDER_ID_INVALID); } else { providers.set(provider_id, provider); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(provider)); } processAudit(exchange); }
Example #14
Source File: SQLDBCacheMetadata.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
@Override public void removeCacheItem(String signature) { String hashedSignature = Helper.sha256(signature); IMap mapLocks = DistributedLockFactory.getDistributedMap(SpagoBIConstants.DISTRIBUTED_MAP_INSTANCE_NAME, SpagoBIConstants.DISTRIBUTED_MAP_FOR_CACHE); mapLocks.lock(hashedSignature); // it is possible to use also the method tryLock(...) with timeout parameter try { if (containsCacheItem(signature)) { cacheDao.deleteCacheItemBySignature(hashedSignature); logger.debug("The dataset with signature[" + signature + "] and hash [" + hashedSignature + "] has been updated"); } else { logger.debug("The dataset with signature[" + signature + "] and hash [" + hashedSignature + "] does not exist in cache"); } } finally { mapLocks.unlock(hashedSignature); } }
Example #15
Source File: MatchDetailHandler.java From match-trade with Apache License 2.0 | 6 votes |
/** * @Title: inputMatchDepth 有事务处理 * @Description: TODO(买入队列) * @param input 入单 * @return void 返回类型 * @throws */ public void inputMatchDepth(MatchOrder input) { // TransactionOptions options = new TransactionOptions().setTransactionType(TransactionOptions.TransactionType.ONE_PHASE); // TransactionContext context = hzInstance.newTransactionContext(options); // context.beginTransaction(); try { IMap<BigDecimal, BigDecimal> map = hzInstance.getMap(HazelcastUtil.getMatchKey(input.getCoinTeam(), input.getIsBuy())); IMap<Long, MatchOrder> order_map = hzInstance.getMap(HazelcastUtil.getOrderBookKey(input.getCoinTeam(), input.getIsBuy())); map.compute(input.getPrice(),(k, v) -> HazelcastUtil.numberAdd(v, input.getUnFinishNumber())); input.setList(null);//清空吃单记录,减小内存。 order_map.put(input.getId(), input); //context.commitTransaction();//提交事务 } catch (Exception e) { //context.rollbackTransaction(); log.error("===入单数据处理异常,数据原型:"+input.toJsonString()+" 本次异常:"+e); } }
Example #16
Source File: Oauth2ServiceServiceIdEndpointGetHandler.java From light-oauth2 with Apache License 2.0 | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { IMap<String, List<ServiceEndpoint>> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints"); String serviceId = exchange.getQueryParameters().get("serviceId").getFirst(); List<ServiceEndpoint> values = serviceEndpoints.get(serviceId); if(values == null || values.size() == 0) { setExchangeStatus(exchange, SERVICE_ENDPOINT_NOT_FOUND, serviceId); processAudit(exchange); return; } exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json"); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values)); processAudit(exchange); }
Example #17
Source File: Oauth2ServiceGetHandler.java From light-oauth2 with Apache License 2.0 | 6 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services"); Deque<String> serviceIdDeque = exchange.getQueryParameters().get("serviceId"); String serviceId = serviceIdDeque == null? "%" : serviceIdDeque.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("serviceId", serviceId); PagingPredicate pagingPredicate = new PagingPredicate(likePredicate, new ServiceComparator(), pageSize); pagingPredicate.setPage(page); Collection<Service> values = services.values(pagingPredicate); exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "application/json"); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values)); processAudit(exchange); }
Example #18
Source File: HazelcastContextListener.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
/** * insert into distributed map info for license */ @SuppressWarnings("unchecked") @Override public void contextInitialized(ServletContextEvent servletContextEvent) { logger.debug("IN"); // recover map and insert IMap<String, HostInfo> mapLocks = DistributedLockFactory.getDistributedMap(SpagoBIConstants.DISTRIBUTED_MAP_INSTANCE_NAME, SpagoBIConstants.DISTRIBUTED_MAP_FOR_LICENSE); logger.debug("Got distributed map for licenses with " + mapLocks != null ? mapLocks.keySet().size() + "values" : "is null"); // Get localhost and add itsa info to distributed map String hostname = SpagoBIUtilities.getCurrentHostName(); logger.debug("Put in distributed map infos for current host " + hostname); HostInfo hostInfo = new HostInfo(); mapLocks.put(hostname, hostInfo); logger.debug("Info put now size is " + mapLocks.size()); logger.debug(System.identityHashCode(mapLocks)); logger.debug("OUT"); }
Example #19
Source File: HazelcastEventStore.java From Moss with Apache License 2.0 | 6 votes |
public HazelcastEventStore(int maxLogSizePerAggregate, IMap<InstanceId, List<InstanceEvent>> eventLog) { super(maxLogSizePerAggregate, eventLog); eventLog.addEntryListener((MapListener) new EntryAdapter<InstanceId, List<InstanceEvent>>() { @Override public void entryUpdated(EntryEvent<InstanceId, List<InstanceEvent>> event) { log.debug("Updated {}", event); long lastKnownVersion = getLastVersion(event.getOldValue()); List<InstanceEvent> newEvents = event.getValue() .stream() .filter(e -> e.getVersion() > lastKnownVersion) .collect(Collectors.toList()); HazelcastEventStore.this.publish(newEvents); } }, true); }
Example #20
Source File: HazelcastTransactionManager.java From jstarcraft-core with Apache License 2.0 | 6 votes |
@Override protected void unlock(TransactionDefinition definition) { Instant now = Instant.now(); String name = definition.getName(); final IMap<String, HazelcastTransactionDefinition> store = getStore(); try { store.lock(name); HazelcastTransactionDefinition current = store.get(name); if (current == null) { throw new TransactionUnlockException(); } else if (now.isAfter(current.getMost())) { throw new TransactionUnlockException(); } else { store.remove(name); } } finally { store.unlock(name); } }
Example #21
Source File: HazelcastTransactionManager.java From jstarcraft-core with Apache License 2.0 | 6 votes |
@Override protected void lock(TransactionDefinition definition) { Instant now = Instant.now(); String name = definition.getName(); final IMap<String, HazelcastTransactionDefinition> store = getStore(); try { store.lock(name); HazelcastTransactionDefinition current = store.get(name); if (current == null) { store.put(name, new HazelcastTransactionDefinition(definition)); } else if (now.isAfter(current.getMost())) { store.put(name, new HazelcastTransactionDefinition(definition)); } else { throw new TransactionLockException(); } } finally { store.unlock(name); } }
Example #22
Source File: HazelcastMemoryService.java From sakai with Educational Community License v2.0 | 5 votes |
@Override public void resetCachers() { if (!getSecurityService().isSuperUser()) { throw new SecurityException("Only super admin can reset cachers, current user not super admin"); } if (this.hcInstance != null) { Collection<DistributedObject> distributedObjects = hcInstance.getDistributedObjects(); for (DistributedObject distributedObject : distributedObjects) { if (distributedObject instanceof IMap) { ((IMap)distributedObject).clear(); } } } }
Example #23
Source File: TestCustomerSerializers.java From subzero with Apache License 2.0 | 5 votes |
@Test public void testTypedCustomSerializerRegisteredInDefaultConfigFile() throws Exception { String mapName = randomMapName(); Config config = new Config(); SubZero.useForClasses(config, NonSerializableObjectRegisteredInDefaultConfigFile.class); HazelcastInstance member = hazelcastFactory.newHazelcastInstance(config); IMap<Integer, NonSerializableObjectRegisteredInDefaultConfigFile> myMap = member.getMap(mapName); myMap.put(0, new NonSerializableObjectRegisteredInDefaultConfigFile()); NonSerializableObjectRegisteredInDefaultConfigFile fromCache = myMap.get(0); assertEquals("deserialized", fromCache.name); }
Example #24
Source File: Oauth2ServicePostHandler.java From light-oauth2 with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public void handleRequest(HttpServerExchange exchange) throws Exception { Map<String, Object> body = (Map)exchange.getAttachment(BodyHandler.REQUEST_BODY); Service service = Config.getInstance().getMapper().convertValue(body, Service.class); String serviceId = service.getServiceId(); IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services"); if(services.get(serviceId) == null) { services.set(serviceId, service); } else { setExchangeStatus(exchange, SERVICE_ID_EXISTS, serviceId); } processAudit(exchange); }
Example #25
Source File: Oauth2ClientPostHandler.java From light-oauth2 with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public void handleRequest(HttpServerExchange exchange) throws Exception { Map<String, Object> body = (Map<String, Object>)exchange.getAttachment(BodyHandler.REQUEST_BODY); Client client = Config.getInstance().getMapper().convertValue(body, Client.class); if(client.getDerefClientId() != null && Client.ClientTypeEnum.EXTERNAL != client.getClientType()) { // only external client may have deref client id setExchangeStatus(exchange, DEREF_NOT_EXTERNAL); return; } // generate client_id and client_secret here. String clientId = UUID.randomUUID().toString(); client.setClientId(clientId); String clientSecret = Util.getUUID(); client.setClientSecret(HashUtil.generateStrongPasswordHash(clientSecret)); IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients"); if(clients.get(clientId) == null) { clients.set(clientId, client); // send the client back with client_id and client_secret Client c = Client.copyClient(client); c.setClientSecret(clientSecret); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(c)); } else { setExchangeStatus(exchange, CLIENT_ID_EXISTS, clientId); } processAudit(exchange); }
Example #26
Source File: HazelcastSlidingWindowRequestRateLimiter.java From ratelimitj with Apache License 2.0 | 5 votes |
private IMap<String, Long> getMap(String key, int longestDuration) { MapConfig mapConfig = hz.getConfig().getMapConfig(key); mapConfig.setTimeToLiveSeconds(longestDuration); mapConfig.setAsyncBackupCount(1); mapConfig.setBackupCount(0); return hz.getMap(key); }
Example #27
Source File: HzCacheGateway.java From DeepMachineLearning with Apache License 2.0 | 5 votes |
@Override public void itemAdded(ItemEvent<Object> event) { System.out.println("Item added: " + event); IMap<Object, Object> generateMap = hz.getMap("generate-map"); AclfTrainDataGenerator dataGen = new AclfTrainDataGenerator(); //read case String filename = generateMap.get("Path").toString(); dataGen.loadCase(filename, generateMap.get("Builder").toString()); int trainPoint= (int) generateMap.get("Train_Points"); String[][] tranSet = dataGen.getTrainSet(trainPoint); hz.getMap("data-map").put("input",tranSet[0]); hz.getMap("data-map").put("output", tranSet[1]); hz.getQueue("finish-queue").add("finish"); }
Example #28
Source File: HazelcastTest.java From greycat with Apache License 2.0 | 5 votes |
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 #29
Source File: Oauth2ClientClientIdServiceGetHandler.java From light-oauth2 with Apache License 2.0 | 5 votes |
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { // ensure that clientId exists. String clientId = exchange.getQueryParameters().get("clientId").getFirst(); IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients"); Client client = clients.get(clientId); if(client == null) { setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId); processAudit(exchange); return; } Map<String, List<String>> serviceEndpoints = new HashMap<>(); try (Connection connection = ds.getConnection(); PreparedStatement stmt = connection.prepareStatement(select)) { stmt.setString(1, clientId); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String serviceId = rs.getString("service_id"); String endpoint = rs.getString("endpoint"); List<String> endpoints = serviceEndpoints.get(serviceId); if(endpoints == null) { endpoints = new ArrayList<>(); serviceEndpoints.put(serviceId, endpoints); } endpoints.add(endpoint); } } } catch (SQLException e) { logger.error("Exception:", e); throw new RuntimeException(e); } exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json"); exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(serviceEndpoints)); processAudit(exchange); }
Example #30
Source File: Oauth2DerefGetHandler.java From light-oauth2 with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private String authenticate(String authHeader) throws ApiException { String result = null; if (authHeader.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) { String base64Challenge = authHeader.substring(PREFIX_LENGTH); String plainChallenge; try { ByteBuffer decode = FlexBase64.decode(base64Challenge); // assume charset is UTF_8 Charset charset = StandardCharsets.UTF_8; plainChallenge = new String(decode.array(), decode.arrayOffset(), decode.limit(), charset); logger.debug("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, authHeader); int colonPos; if ((colonPos = plainChallenge.indexOf(COLON)) > -1) { String clientId = plainChallenge.substring(0, colonPos); String clientSecret = plainChallenge.substring(colonPos + 1); // match with db/cached user credentials. IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients"); Client client = clients.get(clientId); if(client == null) { throw new ApiException(new Status(CLIENT_NOT_FOUND, clientId)); } if(!HashUtil.validatePassword(clientSecret.toCharArray(), client.getClientSecret())) { throw new ApiException(new Status(UNAUTHORIZED_CLIENT)); } result = clientId; } } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) { logger.error("Exception:", e); throw new ApiException(new Status(RUNTIME_EXCEPTION)); } } return result; }