Search in sources :

Example 11 with TokenFilter

use of org.forgerock.openam.cts.api.filter.TokenFilter in project OpenAM by OpenRock.

the class LdapAdapterTest method shouldQuery.

@Test
public void shouldQuery() throws Exception {
    // Given
    final QueryBuilder<Connection, Filter> mockBuilder = mock(QueryBuilder.class);
    given(mockBuilder.withFilter(any(Filter.class))).willAnswer(new Answer<QueryBuilder<Connection, Filter>>() {

        @Override
        public QueryBuilder<Connection, Filter> answer(InvocationOnMock invocation) throws Throwable {
            return mockBuilder;
        }
    });
    given(mockBuilder.execute(any(Connection.class))).willReturn(Arrays.asList((Collection<Token>) Arrays.asList(new Token("weasel", TokenType.OAUTH))).iterator());
    given(mockQueryFactory.createInstance()).willReturn(mockBuilder);
    QueryFilterVisitor<Filter, Void, CoreTokenField> visitor = mock(QueryFilterVisitor.class);
    given(mockQueryFactory.createFilterConverter()).willReturn(visitor);
    given(visitor.visitBooleanLiteralFilter(null, true)).willReturn(Filter.alwaysTrue());
    // When
    TokenFilter filter = new TokenFilterBuilder().withQuery(QueryFilter.<CoreTokenField>alwaysTrue()).build();
    Collection<Token> result = adapter.query(mockConnection, filter);
    // Then
    verify(mockBuilder).withFilter(any(Filter.class));
    verify(mockBuilder).execute(mockConnection);
    assertThat(result.size()).isEqualTo(1);
    assertThat(result.iterator().next().getTokenId()).isEqualTo("weasel");
}
Also used : Connection(org.forgerock.opendj.ldap.Connection) PartialToken(org.forgerock.openam.sm.datalayer.api.query.PartialToken) Token(org.forgerock.openam.cts.api.tokens.Token) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) QueryBuilder(org.forgerock.openam.sm.datalayer.api.query.QueryBuilder) Filter(org.forgerock.opendj.ldap.Filter) TokenFilter(org.forgerock.openam.cts.api.filter.TokenFilter) QueryFilter(org.forgerock.util.query.QueryFilter) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TokenFilterBuilder(org.forgerock.openam.cts.api.filter.TokenFilterBuilder) TokenFilter(org.forgerock.openam.cts.api.filter.TokenFilter) Test(org.testng.annotations.Test)

Example 12 with TokenFilter

use of org.forgerock.openam.cts.api.filter.TokenFilter in project OpenAM by OpenRock.

the class LdapAdapterTest method shouldPartialQuery.

@Test
public void shouldPartialQuery() throws Exception {
    // Given
    final QueryBuilder<Connection, Filter> mockBuilder = mock(QueryBuilder.class);
    given(mockBuilder.withFilter(any(Filter.class))).willAnswer(new Answer<QueryBuilder<Connection, Filter>>() {

        @Override
        public QueryBuilder<Connection, Filter> answer(InvocationOnMock invocation) throws Throwable {
            return mockBuilder;
        }
    });
    given(mockBuilder.returnTheseAttributes(anySetOf(CoreTokenField.class))).willAnswer(new Answer<QueryBuilder<Connection, Filter>>() {

        @Override
        public QueryBuilder<Connection, Filter> answer(InvocationOnMock invocation) throws Throwable {
            return mockBuilder;
        }
    });
    PartialToken partialToken = new PartialToken(new HashMap<CoreTokenField, Object>());
    given(mockBuilder.executeAttributeQuery(any(Connection.class))).willReturn(Arrays.asList((Collection<PartialToken>) Arrays.asList(partialToken)).iterator());
    given(mockQueryFactory.createInstance()).willReturn(mockBuilder);
    QueryFilterVisitor<Filter, Void, CoreTokenField> visitor = mock(QueryFilterVisitor.class);
    given(mockQueryFactory.createFilterConverter()).willReturn(visitor);
    given(visitor.visitBooleanLiteralFilter(null, true)).willReturn(Filter.alwaysTrue());
    // When
    TokenFilter filter = new TokenFilterBuilder().withQuery(QueryFilter.<CoreTokenField>alwaysTrue()).returnAttribute(CoreTokenField.STRING_ONE).build();
    Collection<PartialToken> result = adapter.partialQuery(mockConnection, filter);
    // Then
    verify(mockBuilder).withFilter(any(Filter.class));
    verify(mockBuilder).returnTheseAttributes(asSet(CoreTokenField.STRING_ONE));
    verify(mockBuilder).executeAttributeQuery(mockConnection);
    assertThat(result).containsOnly(partialToken);
}
Also used : PartialToken(org.forgerock.openam.sm.datalayer.api.query.PartialToken) Connection(org.forgerock.opendj.ldap.Connection) CoreTokenField(org.forgerock.openam.tokens.CoreTokenField) QueryBuilder(org.forgerock.openam.sm.datalayer.api.query.QueryBuilder) Filter(org.forgerock.opendj.ldap.Filter) TokenFilter(org.forgerock.openam.cts.api.filter.TokenFilter) QueryFilter(org.forgerock.util.query.QueryFilter) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TokenFilterBuilder(org.forgerock.openam.cts.api.filter.TokenFilterBuilder) TokenFilter(org.forgerock.openam.cts.api.filter.TokenFilter) Test(org.testng.annotations.Test)

Example 13 with TokenFilter

use of org.forgerock.openam.cts.api.filter.TokenFilter in project OpenAM by OpenRock.

the class ClientResource method deleteInstance.

public Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request) {
    String principal = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
    Map<String, String> responseVal = new HashMap<String, String>();
    JsonValue response;
    try {
        String realm = request.getAdditionalParameter("realm");
        if (realm == null) {
            realm = "/";
        }
        manager.deleteIdentity(resourceId, realm);
        try {
            //delete the tokens associated with that client_id
            final TokenFilter tokenFilter = new TokenFilterBuilder().and().withAttribute(OAuthTokenField.CLIENT_ID.getField(), resourceId).withAttribute(OAuthTokenField.REALM.getField(), realm).build();
            store.deleteOnQueryAsync(tokenFilter);
        } catch (CoreTokenException e) {
            if (auditLogger.isAuditLogEnabled()) {
                String[] obs = { "FAILED_DELETE_CLIENT", responseVal.toString() };
                auditLogger.logErrorMessage("FAILED_DELETE_CLIENT", obs, null);
            }
            if (debug.errorEnabled()) {
                debug.error("ClientResource :: DELETE by " + principal + ": Unable to delete client with ID, " + resourceId);
            }
            throw new InternalServerErrorException("Unable to delete client", e);
        }
        responseVal.put("success", "true");
        response = new JsonValue(responseVal);
        ResourceResponse resource = newResourceResponse("results", "1", response);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "DELETED_CLIENT", response.toString() };
            auditLogger.logAccessMessage("DELETED_CLIENT", obs, null);
            if (debug.messageEnabled()) {
                debug.error("ClientResource :: DELETE by " + principal + ": delete client with ID, " + resourceId);
            }
        }
        return newResultPromise(resource);
    } catch (IdRepoException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_DELETE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_DELETE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: DELETE by " + principal + ": Unable to delete client with ID, " + resourceId, e);
        }
        return new InternalServerErrorException("Unable to delete client", e).asPromise();
    } catch (SSOException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_DELETE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_DELETE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: DELETE by " + principal + ": Unable to delete client with ID, " + resourceId, e);
        }
        return new InternalServerErrorException("Unable to delete client", e).asPromise();
    } catch (InternalServerErrorException e) {
        responseVal.put("success", "false");
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_DELETE_CLIENT", responseVal.toString() };
            auditLogger.logErrorMessage("FAILED_DELETE_CLIENT", obs, null);
        }
        if (debug.errorEnabled()) {
            debug.error("ClientResource :: DELETE by " + principal + ": Unable to delete client with ID, " + resourceId, e);
        }
        return new InternalServerErrorException("Unable to delete client", e).asPromise();
    }
}
Also used : Responses.newResourceResponse(org.forgerock.json.resource.Responses.newResourceResponse) ResourceResponse(org.forgerock.json.resource.ResourceResponse) HashMap(java.util.HashMap) JsonValue(org.forgerock.json.JsonValue) IdRepoException(com.sun.identity.idm.IdRepoException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) TokenFilterBuilder(org.forgerock.openam.cts.api.filter.TokenFilterBuilder) SSOException(com.iplanet.sso.SSOException) TokenFilter(org.forgerock.openam.cts.api.filter.TokenFilter)

Example 14 with TokenFilter

use of org.forgerock.openam.cts.api.filter.TokenFilter in project OpenAM by OpenRock.

the class SessionCount method getSessionsFromRepository.

private static Map<String, Long> getSessionsFromRepository(String uuid) throws Exception {
    CTSPersistentStore repo = sessionService.getRepository();
    try {
        // Filter and Query the CTS
        TokenFilter filter = new TokenFilterBuilder().returnAttribute(SessionTokenField.SESSION_ID.getField()).returnAttribute(CoreTokenField.EXPIRY_DATE).and().withAttribute(CoreTokenField.USER_ID, uuid).build();
        Collection<PartialToken> partialTokens = repo.attributeQuery(filter);
        if (debug.messageEnabled()) {
            debug.message(MessageFormat.format("getSessionsFromRepository query success:\n" + "Query: {0}\n" + "Count: {1}", filter, partialTokens.size()));
        }
        // Populate the return Map from the query results.
        Map<String, Long> sessions = new HashMap<String, Long>();
        for (PartialToken partialToken : partialTokens) {
            // Session ID
            String sessionId = partialToken.getValue(SessionTokenField.SESSION_ID.getField());
            // Expiration Date converted to Unix Time
            Calendar timestamp = partialToken.getValue(CoreTokenField.EXPIRY_DATE);
            long unixTime = TimeUtils.toUnixTime(timestamp);
            sessions.put(sessionId, unixTime);
        }
        if (debug.messageEnabled()) {
            debug.message(MessageFormat.format("getSessionsFromRepository query results:\n" + "{0}", sessions));
        }
        return sessions;
    } catch (Exception e) {
        debug.error("SessionCount.getSessionsFromRepository: " + "Session repository is not available", e);
        throw e;
    }
}
Also used : CTSPersistentStore(org.forgerock.openam.cts.CTSPersistentStore) PartialToken(org.forgerock.openam.sm.datalayer.api.query.PartialToken) HashMap(java.util.HashMap) Calendar(java.util.Calendar) TokenFilterBuilder(org.forgerock.openam.cts.api.filter.TokenFilterBuilder) SessionException(com.iplanet.dpro.session.SessionException) TokenFilter(org.forgerock.openam.cts.api.filter.TokenFilter)

Example 15 with TokenFilter

use of org.forgerock.openam.cts.api.filter.TokenFilter in project OpenAM by OpenRock.

the class CtsPersistenceOperationsDelegate method listDurationOfTokens.

/**
     * Gathers list of the durations of tokens in epoch'd seconds
     *
     * @param tokenType The type of token for which we are gathering results
     * @return A collection of longs, each of which represents the duration of a token inside the CTS
     * @throws CoreTokenException
     */
public Collection<Long> listDurationOfTokens(TokenType tokenType) throws CoreTokenException {
    final Collection<Long> results = new ArrayList<Long>();
    final long unixTime = TimeUtils.currentUnixTime();
    final TokenFilter filter = new TokenFilterBuilder().returnAttribute(CoreTokenField.CREATE_TIMESTAMP).and().withAttribute(CoreTokenField.TOKEN_TYPE, tokenType).build();
    for (PartialToken token : store.attributeQuery(filter)) {
        Calendar timestamp = token.getValue(CoreTokenField.CREATE_TIMESTAMP);
        results.add(unixTime - TimeUtils.toUnixTime(timestamp));
    }
    return results;
}
Also used : PartialToken(org.forgerock.openam.sm.datalayer.api.query.PartialToken) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) TokenFilterBuilder(org.forgerock.openam.cts.api.filter.TokenFilterBuilder) TokenFilter(org.forgerock.openam.cts.api.filter.TokenFilter)

Aggregations

TokenFilter (org.forgerock.openam.cts.api.filter.TokenFilter)15 TokenFilterBuilder (org.forgerock.openam.cts.api.filter.TokenFilterBuilder)10 Test (org.testng.annotations.Test)10 PartialToken (org.forgerock.openam.sm.datalayer.api.query.PartialToken)7 Token (org.forgerock.openam.cts.api.tokens.Token)6 ArrayList (java.util.ArrayList)5 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)5 Task (org.forgerock.openam.sm.datalayer.api.Task)5 ResultHandler (org.forgerock.openam.sm.datalayer.api.ResultHandler)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 CoreTokenField (org.forgerock.openam.tokens.CoreTokenField)3 Calendar (java.util.Calendar)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 QueryBuilder (org.forgerock.openam.sm.datalayer.api.query.QueryBuilder)2 Connection (org.forgerock.opendj.ldap.Connection)2 Filter (org.forgerock.opendj.ldap.Filter)2 QueryFilter (org.forgerock.util.query.QueryFilter)2 SessionException (com.iplanet.dpro.session.SessionException)1 SSOException (com.iplanet.sso.SSOException)1