Search in sources :

Example 1 with NeverThrowsException

use of org.forgerock.util.promise.NeverThrowsException in project OpenAM by OpenRock.

the class Endpoints method from.

/**
     * Produce a {@code Handler} from the annotated methods on the provided object.
     * <p>
     * This method currently only distinguishes requests by their method type. In future this
     * should be extended to support selection by request and response media types, and request
     * path.
     * @param obj The object containing annotated methods.
     * @return A new {@code Handler}.
     */
public static Handler from(final Object obj) {
    final Map<String, AnnotatedMethod> methods = new HashMap<>();
    methods.put("DELETE", AnnotatedMethod.findMethod(obj, Delete.class));
    methods.put("GET", AnnotatedMethod.findMethod(obj, Get.class));
    methods.put("POST", AnnotatedMethod.findMethod(obj, Post.class));
    methods.put("PUT", AnnotatedMethod.findMethod(obj, Put.class));
    return new Handler() {

        @Override
        public Promise<Response, NeverThrowsException> handle(Context context, Request request) {
            AnnotatedMethod method = methods.get(getMethod(request));
            if (method == null) {
                Response response = new Response(Status.METHOD_NOT_ALLOWED);
                response.setEntity(new NotSupportedException().toJsonValue().getObject());
                return newResultPromise(response);
            }
            return method.invoke(context, request);
        }
    };
}
Also used : Context(org.forgerock.services.context.Context) HashMap(java.util.HashMap) Request(org.forgerock.http.protocol.Request) Handler(org.forgerock.http.Handler) Response(org.forgerock.http.protocol.Response) NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) NotSupportedException(org.forgerock.json.resource.NotSupportedException)

Example 2 with NeverThrowsException

use of org.forgerock.util.promise.NeverThrowsException in project OpenAM by OpenRock.

the class UpgradeResourceTypeStep method createResourceType.

/**
     * Create the resource type for the given application if a suitable resource type does not already exist.
     * @param state The state object that contains the various parameters for creating the resource type.
     * @param realm The realm in which the application and resource type resides.
     * @return The resource type if it could be created or {@code null} if it could not.
     * @throws UpgradeException If the application types could not be read.
     */
private ResourceType createResourceType(ResourceTypeState state, String realm) throws UpgradeException {
    final Set<QueryFilter<SmsAttribute>> actionFilters = transformSet(state.actions, new Function<String, QueryFilter<SmsAttribute>, NeverThrowsException>() {

        @Override
        public QueryFilter<SmsAttribute> apply(String value) {
            return QueryFilter.equalTo(ResourceTypeSmsAttributes.ACTIONS, value);
        }
    });
    final Set<QueryFilter<SmsAttribute>> patternFilters = transformSet(state.patterns, new Function<String, QueryFilter<SmsAttribute>, NeverThrowsException>() {

        @Override
        public QueryFilter<SmsAttribute> apply(String value) {
            return QueryFilter.equalTo(ResourceTypeSmsAttributes.PATTERNS, value);
        }
    });
    final Set<ResourceType> resourceTypes;
    try {
        resourceTypes = resourceTypeService.getResourceTypes(QueryFilter.and(QueryFilter.and(actionFilters), QueryFilter.and(patternFilters)), getAdminSubject(), realm);
    } catch (EntitlementException e) {
        throw new UpgradeException("Failed to retrieve resource type for " + state.appName, e);
    }
    if (!resourceTypes.isEmpty()) {
        // Some matching resource types have been found, return the first one.
        return resourceTypes.iterator().next();
    }
    ResourceType resourceType = ResourceType.builder().setName(state.appName + RESOURCES_TYPE_NAME_SUFFIX).addActions(getActions(state.actions)).addPatterns(state.patterns).setDescription(RESOURCE_TYPE_DESCRIPTION + state.appName).generateUUID().build();
    saveResourceType(resourceType, realm);
    state.resourceTypeName = resourceType.getName();
    return resourceType;
}
Also used : NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) UpgradeException(org.forgerock.openam.upgrade.UpgradeException) EntitlementException(com.sun.identity.entitlement.EntitlementException) QueryFilter(org.forgerock.util.query.QueryFilter) ResourceType(org.forgerock.openam.entitlement.ResourceType)

Example 3 with NeverThrowsException

use of org.forgerock.util.promise.NeverThrowsException in project OpenAM by OpenRock.

the class AbstractHttpAccessAuditFilterTest method mockHandler.

private Handler mockHandler(Context context, Request request, Status status) {
    Handler handler = mock(Handler.class);
    Promise<Response, NeverThrowsException> promise = newResultPromise(new Response(status));
    given(handler.handle(context, request)).willReturn(promise);
    return handler;
}
Also used : Response(org.forgerock.http.protocol.Response) NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) Handler(org.forgerock.http.Handler)

Example 4 with NeverThrowsException

use of org.forgerock.util.promise.NeverThrowsException in project OpenAM by OpenRock.

the class CoreGuiceModule method configure.

@Override
protected void configure() {
    bind(new AdminTokenType()).toProvider(new AdminTokenProvider()).in(Singleton.class);
    bind(ServiceManagementDAO.class).to(ServiceManagementDAOWrapper.class).in(Singleton.class);
    bind(DNWrapper.class).in(Singleton.class);
    bind(URLValidator.class).toInstance(URLValidator.getInstance());
    bind(new TypeLiteral<TokenAdapter<JsonValue>>() {
    }).annotatedWith(Names.named(OAuth2Constants.CoreTokenParams.OAUTH_TOKEN_ADAPTER)).to(OAuthAdapter.class);
    bind(DSConfigMgr.class).toProvider(new Provider<DSConfigMgr>() {

        public DSConfigMgr get() {
            try {
                return DSConfigMgr.getDSConfigMgr();
            } catch (LDAPServiceException e) {
                throw new IllegalStateException(e);
            }
        }
    }).in(Singleton.class);
    bind(SSOTokenManager.class).toProvider(new Provider<SSOTokenManager>() {

        public SSOTokenManager get() {
            try {
                return SSOTokenManager.getInstance();
            } catch (SSOException e) {
                throw new IllegalStateException(e);
            }
        }
    }).in(Singleton.class);
    /**
         * Core Token Service bindings are divided into a number of logical groups.
         */
    // CTS General
    bind(CTSPersistentStore.class).to(CTSPersistentStoreImpl.class);
    bind(Debug.class).annotatedWith(Names.named(CoreTokenConstants.CTS_DEBUG)).toInstance(Debug.getInstance(CoreTokenConstants.CTS_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(CoreTokenConstants.CTS_REAPER_DEBUG)).toInstance(Debug.getInstance(CoreTokenConstants.CTS_REAPER_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(CoreTokenConstants.CTS_ASYNC_DEBUG)).toInstance(Debug.getInstance(CoreTokenConstants.CTS_ASYNC_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(CoreTokenConstants.CTS_MONITOR_DEBUG)).toInstance(Debug.getInstance(CoreTokenConstants.CTS_MONITOR_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(DataLayerConstants.DATA_LAYER_DEBUG)).toInstance(Debug.getInstance(DataLayerConstants.DATA_LAYER_DEBUG));
    bind(Debug.class).annotatedWith(Names.named("amSMS")).toInstance(Debug.getInstance("amSMS"));
    bind(Debug.class).annotatedWith(Names.named(PolicyMonitor.POLICY_MONITOR_DEBUG)).toInstance(Debug.getInstance(PolicyMonitor.POLICY_MONITOR_DEBUG));
    bind(Debug.class).annotatedWith(Names.named(OAuth2Constants.DEBUG_LOG_NAME)).toInstance(Debug.getInstance(OAuth2Constants.DEBUG_LOG_NAME));
    bind(CoreTokenConstants.class).in(Singleton.class);
    bind(CoreTokenConfig.class).in(Singleton.class);
    // CTS Connection Management
    bind(String.class).annotatedWith(Names.named(DataLayerConstants.ROOT_DN_SUFFIX)).toProvider(new Provider<String>() {

        public String get() {
            return SMSEntry.getRootSuffix();
        }
    }).in(Singleton.class);
    bind(ConfigurationObserver.class).toProvider(new Provider<ConfigurationObserver>() {

        public ConfigurationObserver get() {
            return ConfigurationObserver.getInstance();
        }
    }).in(Singleton.class);
    // CTS Monitoring
    bind(CTSOperationsMonitoringStore.class).to(CTSMonitoringStoreImpl.class);
    bind(CTSReaperMonitoringStore.class).to(CTSMonitoringStoreImpl.class);
    bind(CTSConnectionMonitoringStore.class).to(CTSMonitoringStoreImpl.class);
    // Enable monitoring of all CTS operations
    bind(ResultHandlerFactory.class).to(MonitoredResultHandlerFactory.class);
    // CTS Reaper configuration
    bind(ReaperQuery.class).to(ReaperConnection.class);
    // Policy Monitoring
    bind(PolicyMonitor.class).to(PolicyMonitorImpl.class);
    // SAML2 token repository dependencies
    bind(new TypeLiteral<TokenAdapter<SAMLToken>>() {
    }).to(SAMLAdapter.class);
    /**
         * Session related dependencies.
         */
    bind(SessionOperationStrategy.class).to(ServerSessionOperationStrategy.class);
    // TODO: Investigate whether or not this lazy-loading "Config<SessionService>" wrapper is still needed
    bind(new TypeLiteral<Config<SessionService>>() {
    }).toInstance(new Config<SessionService>() {

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public SessionService get() {
            return InjectorHolder.getInstance(SessionService.class);
        }
    });
    bind(Debug.class).annotatedWith(Names.named(SessionConstants.SESSION_DEBUG)).toInstance(Debug.getInstance(SessionConstants.SESSION_DEBUG));
    bind(new TypeLiteral<Function<String, String, NeverThrowsException>>() {
    }).annotatedWith(Names.named("tagSwapFunc")).toInstance(new Function<String, String, NeverThrowsException>() {

        @Override
        public String apply(String text) {
            return ServicesDefaultValues.tagSwap(text, true);
        }
    });
    install(new FactoryModuleBuilder().implement(AMIdentityRepository.class, AMIdentityRepository.class).build(AMIdentityRepositoryFactory.class));
    install(new FactoryModuleBuilder().implement(SMSAuditor.class, SMSAuditor.class).build(ConfigAuditorFactory.class));
    Multibinder.newSetBinder(binder(), SMSAuditFilter.class);
    Multibinder.newSetBinder(binder(), IdRepoCreationListener.class);
    bind(Stats.class).annotatedWith(Names.named(SessionConstants.STATS_MASTER_TABLE)).toInstance(Stats.getInstance(SessionConstants.STATS_MASTER_TABLE));
    bind(SessionCache.class).toInstance(SessionCache.getInstance());
    bind(SessionPollerPool.class).toInstance(SessionPollerPool.getInstance());
    /*
         * Must use a provider to ensure initialisation happens after SystemProperties have been set.
         */
    bind(SessionCookies.class).toProvider(new Provider<SessionCookies>() {

        @Override
        public SessionCookies get() {
            return SessionCookies.getInstance();
        }
    });
    /*
         * Must use a provider to ensure initialisation happens after SystemProperties have been set.
         */
    bind(SessionURL.class).toProvider(new Provider<SessionURL>() {

        @Override
        public SessionURL get() {
            return SessionURL.getInstance();
        }
    });
    bind(SessionServiceURLService.class).toInstance(SessionServiceURLService.getInstance());
    bind(ConsoleConfigHandler.class).to(ConsoleConfigHandlerImpl.class);
}
Also used : ServiceManagementDAOWrapper(com.sun.identity.sm.ServiceManagementDAOWrapper) FactoryModuleBuilder(com.google.inject.assistedinject.FactoryModuleBuilder) SessionURL(org.forgerock.openam.session.SessionURL) SSOException(com.iplanet.sso.SSOException) PolicyMonitor(org.forgerock.openam.entitlement.monitoring.PolicyMonitor) CTSOperationsMonitoringStore(org.forgerock.openam.cts.monitoring.CTSOperationsMonitoringStore) CTSPersistentStore(org.forgerock.openam.cts.CTSPersistentStore) Function(org.forgerock.util.Function) SessionCookies(org.forgerock.openam.session.SessionCookies) TypeLiteral(com.google.inject.TypeLiteral) URLValidator(com.sun.identity.shared.validation.URLValidator) ConfigAuditorFactory(com.sun.identity.sm.ldap.ConfigAuditorFactory) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) CTSConnectionMonitoringStore(org.forgerock.openam.cts.monitoring.CTSConnectionMonitoringStore) ServerSessionOperationStrategy(com.iplanet.dpro.session.operations.ServerSessionOperationStrategy) SessionOperationStrategy(com.iplanet.dpro.session.operations.SessionOperationStrategy) SessionPollerPool(org.forgerock.openam.session.SessionPollerPool) CTSReaperMonitoringStore(org.forgerock.openam.cts.monitoring.CTSReaperMonitoringStore) ConsoleConfigHandler(org.forgerock.openam.sm.config.ConsoleConfigHandler) AMIdentityRepositoryFactory(org.forgerock.openam.identity.idm.AMIdentityRepositoryFactory) SAMLToken(org.forgerock.openam.cts.api.tokens.SAMLToken) SessionServiceURLService(org.forgerock.openam.session.SessionServiceURLService) Provider(com.google.inject.Provider) ReaperQuery(org.forgerock.openam.cts.impl.query.reaper.ReaperQuery) CoreTokenConfig(org.forgerock.openam.cts.CoreTokenConfig) NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) SessionService(com.iplanet.dpro.session.service.SessionService) CoreTokenConstants(org.forgerock.openam.cts.api.CoreTokenConstants) TokenAdapter(org.forgerock.openam.cts.adapters.TokenAdapter) MonitoredResultHandlerFactory(org.forgerock.openam.cts.monitoring.impl.queue.MonitoredResultHandlerFactory) ResultHandlerFactory(org.forgerock.openam.cts.impl.queue.ResultHandlerFactory) SessionCache(org.forgerock.openam.session.SessionCache)

Example 5 with NeverThrowsException

use of org.forgerock.util.promise.NeverThrowsException in project OpenAM by OpenRock.

the class AnnotatedMethod method checkMethod.

static AnnotatedMethod checkMethod(Class<?> annotation, Object requestHandler, Method method) {
    List<ContextParameter> contextParams = new ArrayList<>();
    int requestParam = -1;
    for (int i = 0; i < method.getParameterTypes().length; i++) {
        Class<?> type = method.getParameterTypes()[i];
        for (Annotation paramAnnotation : method.getParameterAnnotations()[i]) {
            if (paramAnnotation instanceof Contextual) {
                if (Context.class.isAssignableFrom(type)) {
                    contextParams.add(new ContextParameter(i, (Class<? extends Context>) type));
                } else if (Request.class.isAssignableFrom(type)) {
                    requestParam = i;
                }
            }
        }
    }
    Function<Object, Promise<Response, NeverThrowsException>, NeverThrowsException> resourceCreator;
    if (Promise.class.equals(method.getReturnType())) {
        resourceCreator = new PromisedResponseCreator();
    } else if (Response.class.equals(method.getReturnType())) {
        resourceCreator = new Function<Object, Promise<Response, NeverThrowsException>, NeverThrowsException>() {

            @Override
            public Promise<Response, NeverThrowsException> apply(Object o) {
                return newResultPromise((Response) o);
            }
        };
    } else {
        resourceCreator = ResponseCreator.forType(method.getReturnType());
    }
    return new AnnotatedMethod(annotation.getSimpleName(), requestHandler, method, contextParams, requestParam, method.getParameterTypes().length, resourceCreator);
}
Also used : Context(org.forgerock.services.context.Context) ArrayList(java.util.ArrayList) Request(org.forgerock.http.protocol.Request) Annotation(java.lang.annotation.Annotation) NeverThrowsException(org.forgerock.util.promise.NeverThrowsException) Response(org.forgerock.http.protocol.Response) Promises.newResultPromise(org.forgerock.util.promise.Promises.newResultPromise) Promise(org.forgerock.util.promise.Promise) Function(org.forgerock.util.Function)

Aggregations

NeverThrowsException (org.forgerock.util.promise.NeverThrowsException)6 Response (org.forgerock.http.protocol.Response)4 Request (org.forgerock.http.protocol.Request)3 Context (org.forgerock.services.context.Context)3 Handler (org.forgerock.http.Handler)2 Function (org.forgerock.util.Function)2 Provider (com.google.inject.Provider)1 TypeLiteral (com.google.inject.TypeLiteral)1 FactoryModuleBuilder (com.google.inject.assistedinject.FactoryModuleBuilder)1 ServerSessionOperationStrategy (com.iplanet.dpro.session.operations.ServerSessionOperationStrategy)1 SessionOperationStrategy (com.iplanet.dpro.session.operations.SessionOperationStrategy)1 SessionService (com.iplanet.dpro.session.service.SessionService)1 LDAPServiceException (com.iplanet.services.ldap.LDAPServiceException)1 SSOException (com.iplanet.sso.SSOException)1 EntitlementException (com.sun.identity.entitlement.EntitlementException)1 URLValidator (com.sun.identity.shared.validation.URLValidator)1 ServiceManagementDAOWrapper (com.sun.identity.sm.ServiceManagementDAOWrapper)1 ConfigAuditorFactory (com.sun.identity.sm.ldap.ConfigAuditorFactory)1 Annotation (java.lang.annotation.Annotation)1 ArrayList (java.util.ArrayList)1