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

The following examples show how to use com.hazelcast.core.IMap#get() . 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: Oauth2ServiceServiceIdEndpointGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@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 3
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 4
Source File: Oauth2ProviderPostHandler.java    From light-oauth2 with 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<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) {
        providers.set(provider_id, provider);
        exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(provider));
    } else {
        setExchangeStatus(exchange, PROVIDER_ID_EXISTS, provider_id);
    }
    processAudit(exchange);
}
 
Example 5
Source File: Oauth2ClientClientIdGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String clientId = exchange.getQueryParameters().get("clientId").getFirst();

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

    if(client == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
        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));
    processAudit(exchange);
}
 
Example 6
Source File: Oauth2ServiceServiceIdGetHandler.java    From light-oauth2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();

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

    if(service == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
        processAudit(exchange);
        return;
    }
    exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/json");
    exchange.getResponseSender().send(Config.getInstance().getMapper().writeValueAsString(service));
    processAudit(exchange);
}
 
Example 7
Source File: Oauth2KeyKeyIdGetHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
private String getCertificateFromProvider(String providerId, String keyId) throws ClientException {
    IMap<String, Provider> providers = CacheStartupHookProvider.hz.getMap("providers");
    Provider provider = providers.get(providerId);
    String key = null;

    if(provider != null) {
        KeyRequest keyRequest = new KeyRequest(keyId);
        keyRequest.setServerUrl(provider.getServerUrl());
        keyRequest.setUri(provider.getUri() + "/00" + keyId);
        keyRequest.setEnableHttp2(true);
        key = OauthHelper.getKey(keyRequest);
    }
    return key;
}
 
Example 8
Source File: Oauth2ServiceServiceIdDeleteHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
    IMap<String, ServiceEndpoint> serviceEndpoints = CacheStartupHookProvider.hz.getMap("serviceEndpoints");
    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    if(services.get(serviceId) == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
    } else {
        serviceEndpoints.delete(serviceId);
        services.delete(serviceId);
    }
    processAudit(exchange);
}
 
Example 9
Source File: Oauth2ClientClientIdServiceServiceIdGetHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    // ensure that both clientId and serviceId exist.
    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;
    }

    String serviceId = exchange.getQueryParameters().get("serviceId").getFirst();
    IMap<String, Service> services = CacheStartupHookProvider.hz.getMap("services");
    if(services.get(serviceId) == null) {
        setExchangeStatus(exchange, SERVICE_NOT_FOUND, serviceId);
        processAudit(exchange);
        return;
    }

    List<String> endpoints = new ArrayList<>();
    try (Connection connection = ds.getConnection(); PreparedStatement stmt = connection.prepareStatement(select)) {
        stmt.setString(1, clientId);
        stmt.setString(2, serviceId);
        try (ResultSet rs = stmt.executeQuery()) {
            while (rs.next()) {
                endpoints.add(rs.getString("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(endpoints));
    processAudit(exchange);
}
 
Example 10
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 11
Source File: Oauth2DerefGetHandler.java    From light-oauth2 with 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 12
Source File: InterceptorDemo.java    From hazelcast-demo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	HazelcastInstance ins = Hazelcast.newHazelcastInstance();
	IMap<Integer, String> imap = ins.getMap("");
	imap.addInterceptor(new InterceptorExample());// 添加拦截器
	imap.put(1, "Mei");
	imap.put(1, "Tracer");
	imap.put(1, "D.va");
	imap.put(1, "Mercy");
	
	imap.get(1);
	imap.remove(1);
	System.out.println(imap.get(1));
}
 
Example 13
Source File: Oauth2PasswordUserIdPostHandler.java    From light-oauth2 with Apache License 2.0 5 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);
    String userId = exchange.getQueryParameters().get("userId").getFirst();
    char[] password = null;
    if(body.get("password") != null) {
        password = ((String)body.get("password")).toCharArray();
    }
    String newPassword = (String)body.get("newPassword");
    String newPasswordConfirm = (String)body.get("newPasswordConfirm");

    IMap<String, User> users = CacheStartupHookProvider.hz.getMap("users");
    User user = users.get(userId);
    if(user == null) {
        setExchangeStatus(exchange, USER_NOT_FOUND, userId);
        processAudit(exchange);
    } else {
        if(!HashUtil.validatePassword(password, user.getPassword())) {
            setExchangeStatus(exchange, INCORRECT_PASSWORD);
            processAudit(exchange);
            return;
        }
        if(newPassword.equals(newPasswordConfirm)) {
            String hashedPass = HashUtil.generateStrongPasswordHash(newPassword);
            user.setPassword(hashedPass);
            users.set(userId, user);
        } else {
            setExchangeStatus(exchange, PASSWORD_PASSWORDCONFIRM_NOT_MATCH, newPassword, newPasswordConfirm);
        }
        processAudit(exchange);
    }
}
 
Example 14
Source File: Signup.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private String validateRequest(String accountId, String uuid, IMap mapLocks) {
	logger.debug("IN");

	// verify request authenticity
	if (uuid == null) {
		logger.error("missing uuid key, request not valid, user cannot be activated");
		return "signup.msg.invalidRequestKO";
	}

	Object obj = mapLocks.get(accountId);
	String UUIDinMap = null;
	try {

		UUIDinMap = (String) obj;

		if (!UUIDinMap.equals(uuid)) {
			logger.error("Request seems not be valid, uuid check failed");
			return "signup.msg.invalidRequestKO";
		}
	} catch (Exception e) {
		logger.error("Could not verify uuid or timeout passed, user cannot be activated");
		return "signup.msg.invalidRequestKO";
	}

	logger.debug("request is valid ");
	logger.debug("OUT");
	return null;
}
 
Example 15
Source File: Oauth2AuthorizePostHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");

    // parse all the parameters here as this is a redirected get request.
    Map<String, String> params = new HashMap<>();
    Map<String, Deque<String>> pnames = exchange.getQueryParameters();
    for (Map.Entry<String, Deque<String>> entry : pnames.entrySet()) {
        String pname = entry.getKey();
        Iterator<String> pvalues = entry.getValue().iterator();
        if(pvalues.hasNext()) {
            params.put(pname, pvalues.next());
        }
    }
    if(logger.isDebugEnabled()) logger.debug("params", params);
    String clientId = params.get("client_id");
    // check if the client_id is valid
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);
    if(client == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
    } else {
            /*
            String clazz = (String)client.get("authenticateClass");
            if(clazz == null) clazz = DEFAULT_AUTHENTICATE_CLASS;
            Authentication auth = (Authentication)Class.forName(clazz).getConstructor().newInstance();
            String userId = auth.authenticate(exchange);
            if(userId == null) {
                Status status = new Status(MISSING_AUTHORIZATION_HEADER, clientId);
                exchange.setStatusCode(status.getStatusCode());
                exchange.getResponseSender().send(status.toString());
                return;
            }
            */
        final SecurityContext context = exchange.getSecurityContext();
        String userId = context.getAuthenticatedAccount().getPrincipal().getName();
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("userId", userId);
        // generate auth code
        String code = Util.getUUID();
        String redirectUri = params.get("redirect_uri");
        if(redirectUri == null) {
            redirectUri = client.getRedirectUri();
        } else {
            codeMap.put("redirectUri", redirectUri);
        }
        CacheStartupHookProvider.hz.getMap("codes").set(code, codeMap);

        redirectUri = redirectUri + "?code=" + code;
        String state = params.get("state");
        if(state != null) {
            redirectUri = redirectUri + "&state=" + state;
        }
        if(logger.isDebugEnabled()) logger.debug("redirectUri = " + redirectUri);
        // now redirect here.
        exchange.setStatusCode(StatusCodes.FOUND);
        exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri);
        exchange.endExchange();
        processAudit(exchange);
    }
}
 
Example 16
Source File: Oauth2AuthorizeGetHandler.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
    // parse all the parameters here as this is a redirected get request.
    Map<String, String> params = new HashMap<>();
    Map<String, Deque<String>> pnames = exchange.getQueryParameters();
    for (Map.Entry<String, Deque<String>> entry : pnames.entrySet()) {
        String pname = entry.getKey();
        Iterator<String> pvalues = entry.getValue().iterator();
        if(pvalues.hasNext()) {
            params.put(pname, pvalues.next());
        }
    }
    if(logger.isDebugEnabled()) logger.debug("params", params);
    String clientId = params.get("client_id");
    // check if the client_id is valid
    IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
    Client client = clients.get(clientId);
    if(client == null) {
        setExchangeStatus(exchange, CLIENT_NOT_FOUND, clientId);
        processAudit(exchange);
    } else {
        String code = Util.getUUID();
        final SecurityContext context = exchange.getSecurityContext();
        String userId = context.getAuthenticatedAccount().getPrincipal().getName();
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("userId", userId);
        String scope = params.get("scope");
        if(scope != null) {
            codeMap.put("scope", scope);
        }
        String redirectUri = params.get("redirect_uri");
        if(redirectUri == null) {
            redirectUri = client.getRedirectUri();
        } else {
            codeMap.put("redirectUri", redirectUri);
        }
        // https://tools.ietf.org/html/rfc7636#section-4 PKCE
        String codeChallenge = params.get(OAuth2Constants.CODE_CHALLENGE);
        String codeChallengeMethod = params.get(OAuth2Constants.CODE_CHALLENGE_METHOD);
        if (codeChallenge == null) {
            // PKCE is not used by this client.
            // Do we need to force native client to use PKCE?
        } else {
            if(codeChallengeMethod != null) {
                // https://tools.ietf.org/html/rfc7636#section-4.2
                // plain or S256
                if (!codeChallengeMethod.equals(CodeVerifierUtil.CODE_CHALLENGE_METHOD_S256) &&
                        !codeChallengeMethod.equals(CodeVerifierUtil.CODE_CHALLENGE_METHOD_PLAIN)) {
                    setExchangeStatus(exchange, INVALID_CODE_CHALLENGE_METHOD, codeChallengeMethod);
                    processAudit(exchange);
                    return;
                }
            } else {
                // https://tools.ietf.org/html/rfc7636#section-4.3
                // default code_challenge_method is plain
                codeChallengeMethod = CodeVerifierUtil.CODE_CHALLENGE_METHOD_PLAIN;
            }
            // validate codeChallenge.
            if(codeChallenge.length() < CodeVerifierUtil.MIN_CODE_VERIFIER_LENGTH) {
                setExchangeStatus(exchange, CODE_CHALLENGE_TOO_SHORT, codeChallenge);
                processAudit(exchange);
                return;
            }
            if(codeChallenge.length() > CodeVerifierUtil.MAX_CODE_VERIFIER_LENGTH) {
                setExchangeStatus(exchange, CODE_CHALLENGE_TOO_LONG, codeChallenge);
                processAudit(exchange);
                return;
            }
            // check the format
            Matcher m = CodeVerifierUtil.VALID_CODE_CHALLENGE_PATTERN.matcher(codeChallenge);
            if(!m.matches()) {
                setExchangeStatus(exchange, INVALID_CODE_CHALLENGE_FORMAT, codeChallenge);
                processAudit(exchange);
                return;
            }
            // put the code challenge and method into the codes map.
            codeMap.put(OAuth2Constants.CODE_CHALLENGE, codeChallenge);
            codeMap.put(OAuth2Constants.CODE_CHALLENGE_METHOD, codeChallengeMethod);
        }

        CacheStartupHookProvider.hz.getMap("codes").set(code, codeMap);
        redirectUri = redirectUri + "?code=" + code;
        String state = params.get("state");
        if(state != null) {
            redirectUri = redirectUri + "&state=" + state;
        }
        if(logger.isDebugEnabled()) logger.debug("redirectUri = " + redirectUri);
        // now redirect here.
        exchange.setStatusCode(StatusCodes.FOUND);
        exchange.getResponseHeaders().put(Headers.LOCATION, redirectUri);
        exchange.endExchange();
        processAudit(exchange);
    }
}
 
Example 17
Source File: LightGSSAPIAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@Override
public AuthenticationMechanismOutcome run() throws GSSException {
    NegotiationContext negContext = exchange.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext == null) {
        negContext = new NegotiationContext();
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        // Also cache it on the connection for future calls.
        exchange.getConnection().putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
    }

    GSSContext gssContext = negContext.getGssContext();
    if (gssContext == null) {
        GSSManager manager = GSSManager.getInstance();

        GSSCredential credential = manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, mechanisms, GSSCredential.ACCEPT_ONLY);

        gssContext = manager.createContext(credential);

        negContext.setGssContext(gssContext);
    }

    byte[] respToken = gssContext.acceptSecContext(challenge.array(), challenge.arrayOffset(), challenge.limit());
    negContext.setResponseToken(respToken);

    if (negContext.isEstablished()) {

        if (respToken != null) {
            // There will be no further challenge but we do have a token so set it here.
            exchange.getResponseHeaders().add(WWW_AUTHENTICATE,
                    NEGOTIATE_PREFIX + FlexBase64.encodeString(respToken, false));
        }
        IdentityManager identityManager = securityContext.getIdentityManager();
        // get the client authenticate class and user type from the exchange.
        String clientAuthClass = null;
        String userType = null;
        Map<String, Deque<String>> params = exchange.getQueryParameters();
        Deque<String> clientIdDeque = params.get("client_id");
        if(clientIdDeque != null) {
            String clientId = clientIdDeque.getFirst();
            IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
            Client client = clients.get(clientId);
            if(client != null) {
                clientAuthClass = client.getAuthenticateClass();
            }
        }
        Deque<String> userTypeDeque = params.get("user_type");
        if(userTypeDeque != null) {
            userType = userTypeDeque.getFirst();
        }

        final Account account = identityManager.verify(new LightGSSContextCredential(negContext.getGssContext(), clientAuthClass, userType));
        if (account != null) {
            securityContext.authenticationComplete(account, name, false);
            return AuthenticationMechanismOutcome.AUTHENTICATED;
        } else {
            return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        }
    } else {
        // This isn't a failure but as the context is not established another round trip with the client is needed.
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
}
 
Example 18
Source File: LightGSSAPIAuthenticationMechanism.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
@Override
public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange,
                                                   final SecurityContext securityContext) {
    ServerConnection connection = exchange.getConnection();
    NegotiationContext negContext = connection.getAttachment(NegotiationContext.ATTACHMENT_KEY);
    if (negContext != null) {

        if(logger.isDebugEnabled()) logger.debug("Existing negotiation context found for %s", exchange);
        exchange.putAttachment(NegotiationContext.ATTACHMENT_KEY, negContext);
        if (negContext.isEstablished()) {
            IdentityManager identityManager = getIdentityManager(securityContext);
            // get the client authenticate class and user type from the exchange.
            String clientAuthClass = null;
            String userType = null;
            Map<String, Deque<String>> params = exchange.getQueryParameters();
            Deque<String> clientIdDeque = params.get("client_id");
            if(clientIdDeque != null) {
                String clientId = clientIdDeque.getFirst();
                IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
                Client client = clients.get(clientId);
                if(client != null) {
                    clientAuthClass = client.getAuthenticateClass();
                }
            }
            Deque<String> userTypeDeque = params.get("user_type");
            if(userTypeDeque != null) {
                userType = userTypeDeque.getFirst();
            }

            final Account account = identityManager.verify(new LightGSSContextCredential(negContext.getGssContext(), clientAuthClass, userType));
            if (account != null) {
                securityContext.authenticationComplete(account, name, false);
                if(logger.isDebugEnabled()) logger.debug("Authenticated as user %s with existing GSSAPI negotiation context for %s", account.getPrincipal().getName(), exchange);
                return AuthenticationMechanismOutcome.AUTHENTICATED;
            } else {
                if(logger.isDebugEnabled()) logger.debug("Failed to authenticate with existing GSSAPI negotiation context for %s", exchange);
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    List<String> authHeaders = exchange.getRequestHeaders().get(AUTHORIZATION);
    if (authHeaders != null) {
        for (String current : authHeaders) {
            if (current.startsWith(NEGOTIATE_PREFIX)) {
                String base64Challenge = current.substring(NEGOTIATE_PREFIX.length());
                try {
                    ByteBuffer challenge = FlexBase64.decode(base64Challenge);
                    return runGSSAPI(exchange, challenge, securityContext);
                } catch (IOException e) {
                }

                // By this point we had a header we should have been able to verify but for some reason
                // it was not correctly structured.
                return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            }
        }
    }

    // No suitable header was found so authentication was not even attempted.
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example 19
Source File: InventoryItemsQuery.java    From cqrs-eventsourcing-kafka with Apache License 2.0 4 votes vote down vote up
public InventoryItemDetails getInventoryItemDetails(String id) {
    IMap<String, InventoryItemDetails> map = hazelcastInstance.getMap(INVENTORY_ITEMS_DETAILS_MAP);

    return map.get(id);
}
 
Example 20
Source File: MatchExecutor.java    From match-trade with Apache License 2.0 4 votes vote down vote up
public MatchOrder doMatch(MatchOrder input) {
	try {
		// 获取对手盘口
		IMap<BigDecimal, BigDecimal> outMap = hzInstance.getMap(HazelcastUtil.getMatchKey(input.getCoinTeam(), !input.getIsBuy()));
		if (null!=outMap&&outMap.size()>0) {
			BigDecimal outPrice = HazelcastUtil.getOptimalMatch(outMap,input.getIsBuy()); 
			if (HazelcastUtil.canMatch(input, outPrice)) {
				BigDecimal outNum = outMap.get(outPrice);
				if (outNum.compareTo(BigDecimal.ZERO)<1) {
					outMap.remove(outPrice);
					doMatch(input); // 递归处理
				}
				int contrast = input.getUnFinishNumber().compareTo(outNum);
				BigDecimal dealNum = contrast > -1?outNum:input.getUnFinishNumber();
				input.setFinishNumber(input.getFinishNumber().add(dealNum));
				input.setUnFinishNumber(input.getUnFinishNumber().subtract(dealNum));
				if (input.getIsBuy()) {
					input.setSurplusFrozen(input.getSurplusFrozen().subtract(outPrice.multiply(dealNum)));
				}else {
					input.setSurplusFrozen(input.getSurplusFrozen().subtract(dealNum));
				}
				//撮合详情记录 >>> 一个价格一个详情
				matchDetailHandler.sendTradeRecord(input, outPrice, dealNum, DealWay.TAKER);
				List<LevelMatch> lms = input.getList();
				LevelMatch lm = new LevelMatch(outPrice, dealNum);
				lm.setEatUp(contrast > -1 ?true:false);
				lms.add(lm);
				input.setList(lms);
				if (contrast == 1) {//水平价格被吃完
					outMap.remove(outPrice);
					input.setState(OrderState.PART.value);
					doMatch(input); // 递归处理
				}else if (contrast == 0) {//都被吃完
					outMap.remove(outPrice);
					input.setState(OrderState.ALL.value);
				}else {//水平价格有剩余
					outMap.compute(outPrice, (k,v) -> v.subtract(dealNum));
					input.setState(OrderState.ALL.value);
				}
			}
		}
	} catch (Exception e) {
		log.error("执行撮合错误:"+e);
		input.setState(3);//撤销掉
	} 
	return input;
}