Java Code Examples for com.hazelcast.core.IMap

The following examples show how to use com.hazelcast.core.IMap. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: light-oauth2   Source File: Oauth2UserUserIdGetHandler.java    License: Apache License 2.0 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) {
        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 2
Source Project: light-oauth2   Source File: Oauth2UserGetHandler.java    License: Apache License 2.0 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(Headers.CONTENT_TYPE, "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(values));
    processAudit(exchange);
}
 
Example 3
Source Project: youkefu   Source File: CallOutQuene.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获得 当前服务状态
 * @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 4
Source Project: match-trade   Source File: MatchDetailHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * @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 5
@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 6
Source Project: light-oauth2   Source File: Oauth2ServiceGetHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: Moss   Source File: HazelcastEventStore.java    License: Apache License 2.0 6 votes vote down vote up
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 8
@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 9
@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 10
/**
 * 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 11
@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 12
Source Project: light-oauth2   Source File: Oauth2ProviderPutHandler.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
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 14
Source Project: minicubes   Source File: TimeSeriesMiniCubeManagerHzImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 15
Source Project: minicubes   Source File: TimeSeriesMiniCubeManagerHzImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 16
Source Project: light-oauth2   Source File: Oauth2ClientPutHandler.java    License: Apache License 2.0 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);
    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 17
@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 18
Source Project: ShedLock   Source File: HazelcastLockProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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 19
@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 20
Source Project: hazelcast-demo   Source File: ListenerDemo.java    License: Apache License 2.0 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 21
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 22
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 23
Source Project: light-oauth2   Source File: Oauth2KeyKeyIdGetHandler.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 24
Source Project: subzero   Source File: ClassLoadingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void givenMemberHasClassLoaderConfigured_whenObjectIsStored_thenClassLoaderWillBeUsed() throws Exception {
    String mapName = randomMapName();
    Config config = new Config();
    SubZero.useAsGlobalSerializer(config);
    ClassLoader spyingClassLoader = createSpyingClassLoader();
    config.setClassLoader(spyingClassLoader);
    config.addMapConfig(new MapConfig(mapName).setInMemoryFormat(OBJECT));
    HazelcastInstance member = hazelcastFactory.newHazelcastInstance(config);
    IMap<Integer, Object> myMap = member.getMap(mapName);

    myMap.put(0, new MyClass());

    verify(spyingClassLoader).loadClass("info.jerrinot.subzero.ClassLoadingTest$MyClass");
}
 
Example 25
@Override
public void destroyCache(String cacheName) {
    if (this.hcInstance != null) {
        IMap hcMap = this.hcInstance.getMap(cacheName);
        if (hcMap != null) {
            hcMap.destroy();
        }
    }
}
 
Example 26
Source Project: youkefu   Source File: CallOutQuene.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 预测式外呼坐席
 * @param agentStatus
 */
@SuppressWarnings("unchecked")
public static List<CallCenterAgent> forecast(String forecastid){
	List<CallCenterAgent> agentList = new ArrayList<CallCenterAgent>();
	if(CacheHelper.getCallCenterAgentCacheBean()!=null && CacheHelper.getCallCenterAgentCacheBean().getCache()!=null) {
		PagingPredicate<String, CallCenterAgent> pagingPredicate = new PagingPredicate<String, CallCenterAgent>( Predicates.like("forecastvalue", forecastid) , 1 ) ;
		agentList.addAll(((IMap<String , CallCenterAgent>) CacheHelper.getCallCenterAgentCacheBean().getCache()).values(pagingPredicate)) ;
	}
	return agentList ;
}
 
Example 27
Source Project: youkefu   Source File: CallOutQuene.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 为外呼坐席分配名单
 * @param agentStatus
 */
@SuppressWarnings("unchecked")
public static List<CallCenterAgent> extention(String extno){
	List<CallCenterAgent> agentList = new ArrayList<CallCenterAgent>();
	if(CacheHelper.getCallCenterAgentCacheBean()!=null && CacheHelper.getCallCenterAgentCacheBean().getCache()!=null) {
		PagingPredicate<String, CallCenterAgent> pagingPredicate = new PagingPredicate<String, CallCenterAgent>(  new SqlPredicate( "extno = '"+extno+"'") , 10 ) ;
		agentList.addAll(((IMap<String , CallCenterAgent>) CacheHelper.getCallCenterAgentCacheBean().getCache()).values(pagingPredicate)) ;
	}
	return agentList ;
}
 
Example 28
@Override
public void handle(InventoryItemRenamed event) {
    IMap<String, InventoryItemListItem> inventoryItems = getInventoryItemsMap();

    String id = event.id.toString();

    InventoryItemListItem item = inventoryItems.get(id);
    if (item != null) {
        item.name = event.getNewName();
        item.version = event.version;
        inventoryItems.put(id, item);
    }
}
 
Example 29
Source Project: youkefu   Source File: CallOutQuene.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 外呼监控,包含机器人和人工两个部分
 * @param agentStatus
 */
@SuppressWarnings("unchecked")
public static List<CallOutNames> callOutNames(String calltype , int p , int ps){
	List<CallOutNames> callOutNamesList = new ArrayList<CallOutNames>();
	if(CacheHelper.getCallOutCacheBean()!=null && CacheHelper.getCallOutCacheBean().getCache()!=null) {
		PagingPredicate<String, CallOutNames> pagingPredicate = new PagingPredicate<String, CallOutNames>(  new SqlPredicate( "calltype = '"+calltype+"'") , 10 ) ;
		pagingPredicate.setPage(p);
		callOutNamesList.addAll(((IMap<String , CallOutNames>) CacheHelper.getCallOutCacheBean().getCache()).values(pagingPredicate)) ;
	}
	return callOutNamesList ;
}
 
Example 30
Source Project: devicehive-java-server   Source File: HazelcastService.java    License: Apache License 2.0 5 votes vote down vote up
@PostConstruct
protected void init() {
    final IMap<String, HazelcastEntity> notificationsMap = hazelcastClient.getMap(NOTIFICATIONS_MAP);
    notificationsMap.addIndex(TIMESTAMP.getField(), true);

    final IMap<String, HazelcastEntity> commandsMap = hazelcastClient.getMap(COMMANDS_MAP);
    commandsMap.addIndex(TIMESTAMP.getField(), true);
    commandsMap.addIndex(LAST_UPDATED.getField(), true);
    
    mapsHolder.put(DeviceNotification.class, notificationsMap);
    mapsHolder.put(DeviceCommand.class, commandsMap);
}
 
Example 31
Source Project: youkefu   Source File: CallOutQuene.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public static int countForecastCallOut(String orgi,String ownerforecast) {
	/**
	 * 统计当前在线的坐席数量
	 */
	IMap callOutMap = (IMap<String, Object>) CacheHelper.getCallOutCacheBean().getCache() ;
	Long names = (Long) callOutMap.aggregate(Aggregators.<Map.Entry<String, CallOutNames>>count(), new ForecastCallOutFilterPredicate(orgi,ownerforecast)) ;
	return names!=null ? names.intValue() : 0 ;
}
 
Example 32
Source Project: youkefu   Source File: CallOutQuene.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public static int countForecastAgent(String orgi,String ownerforecast) {
	/**
	 * 统计当前在线的坐席数量
	 */
	IMap agentMap = (IMap<String, Object>) CacheHelper.getCallCenterAgentCacheBean().getCache() ;
	Long agents = (Long) agentMap .aggregate(Aggregators.<Map.Entry<String, CallCenterAgent>>count(), new ForecastAgentFilterPredicate(orgi,ownerforecast)) ;
	return agents !=null ? agents.intValue() : 0 ;
}
 
Example 33
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String clientId = exchange.getQueryParameters().get("clientId").getFirst();

    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    if(clients.get(clientId) == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
    } else {
        clients.delete(clientId);
    }
    processAudit(exchange);
}
 
Example 34
Source Project: summerframework   Source File: HazelCastAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Around("execution(* com.hazelcast.core.HazelcastInstance.getMap(..))")
public IMap aroundGetMap(ProceedingJoinPoint pjp) throws Throwable {
    IMap iMap = (IMap)pjp.proceed();
    try {
        HazelcastCacheMetrics.monitor(registry, iMap, platformTag.getTags());
    } catch (Throwable ignore) {
    }
    return iMap;
}
 
Example 35
Source Project: hypergraphdb   Source File: BerkeleyDBStore.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void init(HazelcastInstance hazelcastInstance, Properties properties, String mapName) {
    _hazelcastInstance = hazelcastInstance;
    _properties = properties;
    _mapName = mapName;

    DatabaseConfig dbConfig = new DatabaseConfig();
    dbConfig.setAllowCreate(true);
    dbConfig.setDeferredWrite(true); //延迟写
    dbConfig.setSortedDuplicates(false);
    dbConfig.setTransactional(false);
    _db = _env.openDatabase(null, _mapName, dbConfig);
    _dbMap.put(_mapName, _db);

    if (_scheduleSync == null) {
        try {
            _syncinterval = Integer.parseInt(_properties.getProperty("syncinterval"));
        } catch (Exception e) {
            _syncinterval = 3;
            _logger.log(Level.WARNING, e.getMessage(), e);
        }
        if (_syncinterval > 0) {
            _scheduleSync = Executors.newSingleThreadScheduledExecutor(); //同步磁盘的Scheduled
            _scheduleSync.scheduleWithFixedDelay(this, 1, _syncinterval, TimeUnit.SECONDS);
        }
    }
    _logger.log(Level.INFO, this.getClass().getCanonicalName() + ":" + _mapName + ":count:" + _db.count());
    _logger.log(Level.INFO, this.getClass().getCanonicalName() + ":" + _mapName + ":初始化完成!");

    //预先把数据加载进Hazelcast集群中
    IMap map = _hazelcastInstance.getMap(mapName);
    Set<K> keySet = privateLoadAllKeys();
    for (K key : keySet) {
        map.putTransient(key, load(key), 0, TimeUnit.SECONDS);
    }
    _logger.log(Level.INFO, this.getClass().getCanonicalName() + ":" + _mapName + ":预先加载数据完成!");

}
 
Example 36
Source Project: java-specialagent   Source File: HazelcastTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void test(final HazelcastInstance instance, final MockTracer tracer) {
  final IMap<String,String> map = instance.getMap("map");
  map.put("key", "value");
  assertEquals("value", map.get("key"));
  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example 37
Source Project: java-specialagent   Source File: HazelcastITest.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {
  final HazelcastInstance instance = Hazelcast.newHazelcastInstance(new Config().setProperty("hazelcast.phone.home.enabled", "false"));
  final IMap<String,String> map = instance.getMap("map");
  map.put("key", "value");
  if (!"value".equals(map.get("key")))
    throw new AssertionError("ERROR: wrong value");

  instance.shutdown();

  TestUtil.checkSpan(new ComponentSpanCount("java-hazelcast", 2));
}
 
Example 38
@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 39
Source Project: DeepMachineLearning   Source File: HzCacheGateway.java    License: Apache License 2.0 5 votes vote down vote up
@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 40
Source Project: greycat   Source File: HazelcastTest.java    License: Apache License 2.0 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")));

}