Java Code Examples for com.hazelcast.core.IMap#put()

The following examples show how to use com.hazelcast.core.IMap#put() . 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: TestCustomerSerializers.java    From subzero with Apache License 2.0 6 votes vote down vote up
@Test
public void testTypedCustomSerializer_configuredBySubclassing() throws Exception {
    String mapName = randomMapName();

    Config config = new Config();
    SerializerConfig serializerConfig = new SerializerConfig();
    serializerConfig.setClass(MySerializer.class);
    serializerConfig.setTypeClass(AnotherNonSerializableObject.class);
    config.getSerializationConfig().getSerializerConfigs().add(serializerConfig);

    HazelcastInstance member = hazelcastFactory.newHazelcastInstance(config);
    IMap<Integer, AnotherNonSerializableObject> myMap = member.getMap(mapName);

    myMap.put(0, new AnotherNonSerializableObject());
    AnotherNonSerializableObject fromCache = myMap.get(0);

    assertEquals("deserialized", fromCache.name);
}
 
Example 2
Source File: ClassLoadingTest.java    From subzero with Apache License 2.0 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 3
Source File: TimeSeriesMiniCubeManagerHzImpl.java    From minicubes with 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 4
Source File: TimeSeriesMiniCubeManagerHzImpl.java    From minicubes with 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 5
Source File: HazelcastContextListener.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 6
Source File: TestCustomerSerializers.java    From subzero with Apache License 2.0 6 votes vote down vote up
@Test
public void testGlobalCustomSerializationConfiguredProgrammaticallyForClientConfig() {
    Config memberConfig = new Config();
    SubZero.useAsGlobalSerializer(memberConfig);
    hazelcastFactory.newHazelcastInstance(memberConfig);

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

    SubZero.useAsGlobalSerializer(config, MyGlobalUserSerlizationConfig.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 7
Source File: InventoryItemCreatedHandler.java    From cqrs-eventsourcing-kafka with Apache License 2.0 6 votes vote down vote up
@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 8
Source File: TestCustomerSerializers.java    From subzero with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalCustomSerializationConfiguredProgrammaticallyForHzConfig() {
    String mapName = randomMapName();
    Config config = new Config();

    SubZero.useAsGlobalSerializer(config, MyGlobalUserSerlizationConfig.class);

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

    assertEquals("deserialized", fromCache.name);
}
 
Example 9
Source File: TestCustomerSerializers.java    From subzero with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalCustomSerializerRegisteredInDefaultConfigFile() throws Exception {
    String mapName = randomMapName();
    Config config = new Config();
    SubZero.useAsGlobalSerializer(config);
    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 10
Source File: ClassLoadingTest.java    From subzero with 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 11
Source File: InventoryItemRenamedHandler.java    From cqrs-eventsourcing-kafka with Apache License 2.0 5 votes vote down vote up
@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 12
Source File: TestCustomerSerializers.java    From subzero with Apache License 2.0 5 votes vote down vote up
@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 13
Source File: TestCustomerSerializers.java    From subzero with Apache License 2.0 5 votes vote down vote up
@Test
public void testTypedSerializer_SpecialRegistrationRegisteredInDefaultConfigFile() {
    String mapName = randomMapName();
    Config config = new Config();

    SubZero.useForClasses(config, ClassWithUnmodifieableList.class);
    HazelcastInstance member = hazelcastFactory.newHazelcastInstance(config);
    IMap<Integer, ClassWithUnmodifieableList> myMap = member.getMap(mapName);
    myMap.put(0, new ClassWithUnmodifieableList("foo"));

    //does not throw an exception
    myMap.get(0);
}
 
Example 14
Source File: TestCustomerSerializers.java    From subzero with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalCustomDelegateSerializationConfiguredProgrammaticallyForHzConfig() {
    String mapName = randomMapName();
    Config config = new Config();

    SubZero.useAsGlobalSerializer(config, MyGlobalDelegateSerlizationConfig.class);

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

    assertEquals("deserialized", fromCache.name);
}
 
Example 15
Source File: TestCustomerSerializers.java    From subzero with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalCustomSerializer_SpecialRegistrationRegisteredInDefaultConfigFile() {
    String mapName = randomMapName();
    Config config = new Config();

    SubZero.useAsGlobalSerializer(config);
    HazelcastInstance member = hazelcastFactory.newHazelcastInstance(config);
    IMap<Integer, ClassWithUnmodifieableList> myMap = member.getMap(mapName);
    myMap.put(0, new ClassWithUnmodifieableList("foo"));

    //does not throw an exception
    myMap.get(0);
}
 
Example 16
Source File: HazelcastITest.java    From java-specialagent with 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 17
Source File: Oauth2TokenPostHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, Object> handleRefreshToken(HttpServerExchange exchange, Map<String, Object> formMap) throws ApiException {
    String refreshToken = (String)formMap.get("refresh_token");
    String scope = (String) formMap.get("scope");
    // Get csrf token from the input. every time a new token is generated, a new csrf token will be used.
    String csrf = (String)formMap.get("csrf");
    if(logger.isDebugEnabled()) logger.debug("refreshToken = " + refreshToken + " scope = " + scope);
    Client client = authenticateClient(exchange, formMap);
    if(client != null) {
        // make sure that the refresh token can be found and client_id matches.
        IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens");
        RefreshToken token = tokens.remove(refreshToken);
        if(token != null) {
            String userId = token.getUserId();
            String userType = token.getUserType();
            String roles = token.getRoles();
            String clientId = token.getClientId();
            String oldScope = token.getScope();
            String remember = token.getRemember();

            if(client.getClientId().equals(clientId)) {
                if(scope == null) {
                    scope = oldScope; // use the previous scope when access token is generated
                } else {
                    // make sure scope is the same as oldScope or contained in oldScope.
                    if(!matchScope(scope, oldScope)) {
                        throw new ApiException(new Status(MISMATCH_SCOPE, scope, oldScope));
                    }
                }
                String jwt;
                Map<String, Object> customMap = null;
                // assume that the custom_claim is in format of json map string.
                String customClaim = client.getCustomClaim();
                try {
                    if(customClaim != null && customClaim.length() > 0) {
                        customMap = Config.getInstance().getMapper().readValue(customClaim, new TypeReference<Map<String, Object>>(){});
                    }
                    jwt = JwtIssuer.getJwt(mockAcClaims(client.getClientId(), scope, userId, userType, roles, csrf, customMap));
                } catch (Exception e) {
                    throw new ApiException(new Status(GENERIC_EXCEPTION, e.getMessage()));
                }
                // generate a new refresh token and associate it with userId and clientId
                String newRefreshToken = UUID.randomUUID().toString();
                RefreshToken newToken = new RefreshToken();
                newToken.setRefreshToken(newRefreshToken);
                newToken.setUserId(userId);
                newToken.setUserType(userType);
                newToken.setRoles(roles);
                newToken.setClientId(client.getClientId());
                newToken.setScope(scope);
                newToken.setRemember(remember);
                tokens.put(newRefreshToken, newToken);
                // if the client type is external, save the jwt to reference map and send the reference
                if(Client.ClientTypeEnum.EXTERNAL == client.getClientType()) {
                    jwt = jwtReference(jwt, client.getDerefClientId());
                }
                Map<String, Object> resMap = new HashMap<>();
                resMap.put("access_token", jwt);
                resMap.put("token_type", "bearer");
                resMap.put("expires_in", config.getExpiredInMinutes()*60);
                resMap.put("refresh_token", newRefreshToken);
                resMap.put("remember", remember);
                return resMap;

            } else {
                // mismatched client id
                throw new ApiException(new Status(MISMATCH_CLIENT_ID, client.getClientId(), clientId));
            }
        } else {
            // refresh token cannot be found.
            throw new ApiException(new Status(REFRESH_TOKEN_NOT_FOUND, refreshToken));
        }
    }
    return new HashMap<>(); // return an empty hash map. this is actually not reachable at all.
}
 
Example 18
Source File: MatchDetailHandler.java    From match-trade with Apache License 2.0 4 votes vote down vote up
/**
 * @Title: outMatchDepth 保证了原子操作,无需事务
 * @Description: TODO(out订单处理)
 * @param @param order 入单
 * @return void 返回类型
 * @throws
 */
@Async
public void outMatchDepth(MatchOrder order) {
	List<LevelMatch> list = order.getList();
	try {
		if (null!=list&&list.size()>0) {
			Iterator<LevelMatch> itr = list.iterator();
			while (itr.hasNext()){
				LevelMatch lm = itr.next();
				itr.remove();
				BigDecimal dealNumber = lm.getNumber();
				while (dealNumber.compareTo(BigDecimal.ZERO)>0) {
					//对手盘
					IMap<Long, MatchOrder> order_map = hzInstance.getMap(HazelcastUtil.getOrderBookKey(order.getCoinTeam(), !order.getIsBuy()));
					@SuppressWarnings("rawtypes")
					Predicate pricePredicate = Predicates.equal("price", lm.getPrice());
					Collection<MatchOrder> orders = order_map.values(pricePredicate);
					for (MatchOrder mor : orders) {
						MatchOrder out = order_map.remove(mor.getId());
						if (null!=out) {
							int cpr = dealNumber.compareTo(out.getUnFinishNumber());
							if (cpr>0) {
								dealNumber=dealNumber.subtract(out.getUnFinishNumber());
								this.updateOutOder(out, OrderState.ALL, out.getUnFinishNumber());
							}else if (cpr==0) {
								this.updateOutOder(out, OrderState.ALL, dealNumber);
								dealNumber = BigDecimal.ZERO;
								break;
							}else {
								out = this.updateOutOder(out, OrderState.PART, dealNumber);
								order_map.put(out.getId(), out);
								dealNumber = BigDecimal.ZERO;
								break;
							}
						}
					}
				}
			}
		}
	} catch (Exception e) {
		log.error("===出单数据处理异常,数据原型:"+order.toJsonString()+"   本次异常:"+e);
	}
}
 
Example 19
Source File: CacheStartupHookProviderTest.java    From light-oauth2 with Apache License 2.0 3 votes vote down vote up
@Test
public void testRefreshTokenCache() {
    CacheStartupHookProvider start = new CacheStartupHookProvider();
    start.onStartup();

    final IMap<String, RefreshToken> tokens = CacheStartupHookProvider.hz.getMap("tokens");
    RefreshToken token = new RefreshToken();
    token.setUserId("admin2");
    token.setClientId("59f347a0-c92d-11e6-9d9d-cec0c932ce01");

    token.setScope("todo.r");
    token.setRemember("N");
    token.setRefreshToken("token1");


    tokens.put("token1", token);

    System.out.println("tokens size = " + tokens.size());

    tokens.delete("token1");

    System.out.println("tokens size = " + tokens.size());

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

}
 
Example 20
Source File: CacheStartupHookProviderTest.java    From light-oauth2 with Apache License 2.0 3 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testUserCache() {
    CacheStartupHookProvider start = new CacheStartupHookProvider();
    start.onStartup();

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

    User user = (User)users.get("admin");
    System.out.println("user = " + user);

    user.setUserType(User.UserTypeEnum.fromValue("customer"));

    users.put("admin", user);

    System.out.println("users size = " + users.size());

    // query email as it is indexed.
    String email = "adm%";
    Predicate predicate = new SqlPredicate(String.format("email like %s", email));
    Set<User> uSet = (Set<User>) users.values(predicate);

    System.out.println("uSet = " + uSet);

    users.delete("admin");

    System.out.println("users size = " + users.size());

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

}