org.jboss.resteasy.spi.ResteasyProviderFactory Java Examples

The following examples show how to use org.jboss.resteasy.spi.ResteasyProviderFactory. 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: RxVertxProvider.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	Vertx vertx = ResteasyProviderFactory.getContextData(io.vertx.core.Vertx.class);
	HttpServerRequest req = ResteasyProviderFactory.getContextData(HttpServerRequest.class);
	HttpServerResponse resp = ResteasyProviderFactory.getContextData(HttpServerResponse.class);
	
	// rx2
	ResteasyProviderFactory.pushContext(io.vertx.reactivex.core.Vertx.class, 
			io.vertx.reactivex.core.Vertx.newInstance(vertx));
	ResteasyProviderFactory.pushContext(io.vertx.reactivex.core.http.HttpServerRequest.class, 
			io.vertx.reactivex.core.http.HttpServerRequest.newInstance(req));
	ResteasyProviderFactory.pushContext(io.vertx.reactivex.core.http.HttpServerResponse.class, 
			io.vertx.reactivex.core.http.HttpServerResponse.newInstance(resp));
	// rx1
	ResteasyProviderFactory.pushContext(io.vertx.rxjava.core.Vertx.class, 
			io.vertx.rxjava.core.Vertx.newInstance(vertx));
	ResteasyProviderFactory.pushContext(io.vertx.rxjava.core.http.HttpServerRequest.class, 
			io.vertx.rxjava.core.http.HttpServerRequest.newInstance(req));
	ResteasyProviderFactory.pushContext(io.vertx.rxjava.core.http.HttpServerResponse.class, 
			io.vertx.rxjava.core.http.HttpServerResponse.newInstance(resp));

	ResteasyProviderFactory.pushContext(ServletContext.class, AppGlobals.get().getGlobal(ServletContext.class));
}
 
Example #2
Source File: RestServer.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 启动前钩子
 *
 * @param transport
 * @return
 */
protected CompletableFuture<Void> beforeOpen(final ServerTransport transport) {
    CompletableFuture<Void> result = new CompletableFuture<>();
    try {
        deployment.start();
        ResteasyProviderFactory providerFactory = deployment.getProviderFactory();
        String root = url.getString(REST_ROOT);
        root = REST_ROOT.getValue().equals(root) ? "" : root;
        Map<Class<?>, ExceptionMapper> mapperMap = providerFactory.getExceptionMappers();
        mapperMap.put(ApplicationException.class, ApplicationExceptionMapper.mapper);
        mapperMap.put(ClientErrorException.class, ClientErrorExceptionMapper.mapper);
        mapperMap.put(IllegalArgumentException.class, IllegalArgumentExceptionMapper.mapper);
        transport.setCodec(new ResteasyCodec(root,
                new RequestDispatcher((SynchronousDispatcher) deployment.getDispatcher(), providerFactory, null)));
        result.complete(null);
    } catch (Throwable e) {
        result.completeExceptionally(e);
    }
    return result;
}
 
Example #3
Source File: RealmsResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path("{realm}/protocol/{protocol}")
public Object getProtocol(final @PathParam("realm") String name,
                          final @PathParam("protocol") String protocol) {
    RealmModel realm = init(name);

    LoginProtocolFactory factory = (LoginProtocolFactory)session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, protocol);
    if(factory == null){
        logger.debugf("protocol %s not found", protocol);
        throw new NotFoundException("Protocol not found");
    }

    EventBuilder event = new EventBuilder(realm, session, clientConnection);

    Object endpoint = factory.createProtocolEndpoint(realm, event);

    ResteasyProviderFactory.getInstance().injectProperties(endpoint);
    return endpoint;
}
 
Example #4
Source File: ClientsResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Base path for managing a specific client.
 *
 * @param id id of client (not client-id)
 * @return
 */
@Path("{id}")
public ClientResource getClient(final @PathParam("id") String id) {

    ClientModel clientModel = realm.getClientById(id);
    if (clientModel == null) {
        // we do this to make sure somebody can't phish ids
        if (auth.clients().canList()) throw new NotFoundException("Could not find client");
        else throw new ForbiddenException();
    }

    session.getContext().setClient(clientModel);

    ClientResource clientResource = new ClientResource(realm, auth, clientModel, session, adminEvent);
    ResteasyProviderFactory.getInstance().injectProperties(clientResource);
    return clientResource;
}
 
Example #5
Source File: SchedulerClient.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void init(ConnectionInfo connectionInfo) throws Exception {
    HttpClient client = new HttpClientBuilder().insecure(connectionInfo.isInsecure()).useSystemProperties().build();
    SchedulerRestClient restApiClient = new SchedulerRestClient(connectionInfo.getUrl(),
                                                                new ApacheHttpClient4Engine(client));

    ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance();
    factory.register(new WildCardTypeReader());
    factory.register(new OctetStreamReader());
    factory.register(new TaskResultReader());
    SchedulerRestClient.registerGzipEncoding(factory);

    setApiClient(restApiClient);

    this.connectionInfo = connectionInfo;
    this.initialized = true;

    renewSession();
}
 
Example #6
Source File: IdentityProvidersResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path("instances/{alias}")
public IdentityProviderResource getIdentityProvider(@PathParam("alias") String alias) {
    this.auth.realm().requireViewIdentityProviders();
    IdentityProviderModel identityProviderModel = null;

    for (IdentityProviderModel storedIdentityProvider : this.realm.getIdentityProviders()) {
        if (storedIdentityProvider.getAlias().equals(alias)
                || storedIdentityProvider.getInternalId().equals(alias)) {
            identityProviderModel = storedIdentityProvider;
        }
    }

    IdentityProviderResource identityProviderResource = new IdentityProviderResource(this.auth, realm, session, identityProviderModel, adminEvent);
    ResteasyProviderFactory.getInstance().injectProperties(identityProviderResource);
    
    return identityProviderResource;
}
 
Example #7
Source File: RpcContextFilter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext requestContext) throws IOException {
    HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
    RpcContext.getContext().setRequest(request);

    // this only works for servlet containers
    if (request != null && RpcContext.getContext().getRemoteAddress() == null) {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
    }

    RpcContext.getContext().setResponse(ResteasyProviderFactory.getContextData(HttpServletResponse.class));

    String headers = requestContext.getHeaderString(DUBBO_ATTACHMENT_HEADER);
    if (headers != null) {
        for (String header : headers.split(",")) {
            int index = header.indexOf("=");
            if (index > 0) {
                String key = header.substring(0, index);
                String value = header.substring(index + 1);
                if (!StringUtils.isEmpty(key)) {
                    RpcContext.getContext().setAttachment(key.trim(), value.trim());
                }
            }
        }
    }
}
 
Example #8
Source File: SofaResteasyClientBuilder.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 注册jaxrs Provider
 *
 * @return SofaResteasyClientBuilder
 */
public SofaResteasyClientBuilder registerProvider() {
    ResteasyProviderFactory providerFactory = getProviderFactory();
    // 注册内置
    Set<Class> internalProviderClasses = JAXRSProviderManager.getInternalProviderClasses();
    if (CommonUtils.isNotEmpty(internalProviderClasses)) {
        for (Class providerClass : internalProviderClasses) {
            providerFactory.register(providerClass);
        }
    }
    // 注册自定义
    Set<Object> customProviderInstances = JAXRSProviderManager.getCustomProviderInstances();
    if (CommonUtils.isNotEmpty(customProviderInstances)) {
        for (Object provider : customProviderInstances) {
            PropertyInjector propertyInjector = providerFactory.getInjectorFactory()
                .createPropertyInjector(
                    JAXRSProviderManager.getTargetClass(provider), providerFactory);
            propertyInjector.inject(provider);
            providerFactory.registerProviderInstance(provider);
        }
    }

    return this;
}
 
Example #9
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * If there is a client whose SAML IDP-initiated SSO URL name is set to the
 * given {@code clientUrlName}, creates a fresh client session for that
 * client and returns a {@link ParsedCodeContext} object with that session.
 * Otherwise returns "client not found" response.
 *
 * @param clientUrlName
 * @return see description
 */
private ParsedCodeContext samlIdpInitiatedSSO(final String clientUrlName) {
    event.event(EventType.LOGIN);
    CacheControlUtil.noBackButtonCacheControlHeader();
    Optional<ClientModel> oClient = this.realmModel.getClients().stream()
      .filter(c -> Objects.equals(c.getAttribute(SamlProtocol.SAML_IDP_INITIATED_SSO_URL_NAME), clientUrlName))
      .findFirst();

    if (! oClient.isPresent()) {
        event.error(Errors.CLIENT_NOT_FOUND);
        return ParsedCodeContext.response(redirectToErrorPage(Response.Status.BAD_REQUEST, Messages.CLIENT_NOT_FOUND));
    }

    LoginProtocolFactory factory = (LoginProtocolFactory) session.getKeycloakSessionFactory().getProviderFactory(LoginProtocol.class, SamlProtocol.LOGIN_PROTOCOL);
    SamlService samlService = (SamlService) factory.createProtocolEndpoint(realmModel, event);
    ResteasyProviderFactory.getInstance().injectProperties(samlService);
    AuthenticationSessionModel authSession = samlService.getOrCreateLoginSessionForIdpInitiatedSso(session, realmModel, oClient.get(), null);
    if (authSession == null) {
        event.error(Errors.INVALID_REDIRECT_URI);
        return ParsedCodeContext.response(redirectToErrorPage(Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI));
    }

    return ParsedCodeContext.clientSessionCode(new ClientSessionCode<>(session, this.realmModel, authSession));
}
 
Example #10
Source File: ComponentContainerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void removeComponent(final BeanEntry<?, ?> entry) throws Exception {
  Class<?> type = entry.getImplementationClass();
  if (isResource(type)) {
    getDispatcher().getRegistry().removeRegistrations(type);
    String path = resourcePath(type);
    log.debug("Removed resource: {} with path: {}", type.getName(), path);
  }
  else {
    ResteasyProviderFactory providerFactory = getDispatcher().getProviderFactory();
    if (providerFactory instanceof SisuResteasyProviderFactory) {
      ((SisuResteasyProviderFactory) providerFactory).removeRegistrations(type);
      log.debug("Removed component: {}", type.getName());
    }
    else {
      log.warn("Component removal not supported; Unable to remove component: {}", type.getName());
    }
  }
}
 
Example #11
Source File: AdminRoot.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Base Path to realm admin REST interface
 *
 * @param headers
 * @return
 */
@Path("realms")
public Object getRealmsAdmin(@Context final HttpHeaders headers) {
    if (request.getHttpMethod().equals(HttpMethod.OPTIONS)) {
        return new AdminCorsPreflightService(request);
    }

    AdminAuth auth = authenticateRealmAdminRequest(headers);
    if (auth != null) {
        logger.debug("authenticated admin access for: " + auth.getUser().getUsername());
    }

    Cors.add(request).allowedOrigins(auth.getToken()).allowedMethods("GET", "PUT", "POST", "DELETE").exposedHeaders("Location").auth().build(response);

    RealmsAdminResource adminResource = new RealmsAdminResource(auth, tokenManager);
    ResteasyProviderFactory.getInstance().injectProperties(adminResource);
    return adminResource;
}
 
Example #12
Source File: RestEasyResource.java    From jax-rs-pac4j with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/securitycontext")
@Pac4JSecurity(clients = "DirectFormClient", authorizers = DefaultAuthorizers.IS_AUTHENTICATED)
public String directSecurityContext() {
    // Note: SecurityContext injected via @Context can't be cast
    SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class);
    if (context != null) {
        if (context instanceof Pac4JSecurityContext) {
            return "ok";
        } else {
            return "fail";
        }
    } else {
        return "error";
    }
}
 
Example #13
Source File: NexusITSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The jax-rs clients require ObjectMapper customizations to work with ComponentXO.
 */
private Customizer getObjectMapperCustomizer(final TestSuiteObjectMapperResolver testSuiteObjectMapperResolver) {
  return builder -> {
    ResteasyProviderFactory providerFactory = new LocalResteasyProviderFactory(
        ResteasyProviderFactory.newInstance());
    providerFactory.registerProviderInstance(testSuiteObjectMapperResolver, null, 1000, false);

    ResteasyClientBuilder resteasyClientBuilder = (ResteasyClientBuilder) builder;
    resteasyClientBuilder.providerFactory(providerFactory);
    RegisterBuiltin.register(providerFactory);
  };
}
 
Example #14
Source File: UserResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("role-mappings")
public RoleMapperResource getRoleMappings() {
    AdminPermissionEvaluator.RequirePermissionCheck manageCheck = () -> auth.users().requireMapRoles(user);
    AdminPermissionEvaluator.RequirePermissionCheck viewCheck = () -> auth.users().requireView(user);
    RoleMapperResource resource =  new RoleMapperResource(realm, auth, user, adminEvent, manageCheck, viewCheck);
    ResteasyProviderFactory.getInstance().injectProperties(resource);
    return resource;

}
 
Example #15
Source File: RealmsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("{realm}/authz")
public Object getAuthorizationService(@PathParam("realm") String name) {
    init(name);
    AuthorizationProvider authorization = this.session.getProvider(AuthorizationProvider.class);
    AuthorizationService service = new AuthorizationService(authorization);

    ResteasyProviderFactory.getInstance().injectProperties(service);

    return service;
}
 
Example #16
Source File: TokenEndpoint.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("introspect")
public Object introspect() {
    TokenIntrospectionEndpoint tokenIntrospectionEndpoint = new TokenIntrospectionEndpoint(this.realm, this.event);

    ResteasyProviderFactory.getInstance().injectProperties(tokenIntrospectionEndpoint);

    return tokenIntrospectionEndpoint;
}
 
Example #17
Source File: GroupResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("role-mappings")
public RoleMapperResource getRoleMappings() {
    AdminPermissionEvaluator.RequirePermissionCheck manageCheck = () -> auth.groups().requireManage(group);
    AdminPermissionEvaluator.RequirePermissionCheck viewCheck = () -> auth.groups().requireView(group);
    RoleMapperResource resource =  new RoleMapperResource(realm, auth, group, adminEvent, manageCheck, viewCheck);
    ResteasyProviderFactory.getInstance().injectProperties(resource);
    return resource;

}
 
Example #18
Source File: ResourceServerService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("/scope")
public ScopeService getScopeResource() {
    ScopeService resource = new ScopeService(this.session, this.resourceServer, this.authorization, this.auth, adminEvent);

    ResteasyProviderFactory.getInstance().injectProperties(resource);

    return resource;
}
 
Example #19
Source File: NexusITSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The jax-rs clients require ObjectMapper customizations to work with ComponentXO.
 */
private Customizer getObjectMapperCustomizer(final TestSuiteObjectMapperResolver testSuiteObjectMapperResolver) {
  return builder -> {
    ResteasyProviderFactory providerFactory = new LocalResteasyProviderFactory(
        ResteasyProviderFactory.newInstance());
    providerFactory.registerProviderInstance(testSuiteObjectMapperResolver, null, 1000, false);

    ResteasyClientBuilder resteasyClientBuilder = (ResteasyClientBuilder) builder;
    resteasyClientBuilder.providerFactory(providerFactory);
    RegisterBuiltin.register(providerFactory);
  };
}
 
Example #20
Source File: PolicyService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("evaluate")
public PolicyEvaluationService getPolicyEvaluateResource() {
    if (auth != null) {
        this.auth.realm().requireViewAuthorization();
    }

    PolicyEvaluationService resource = new PolicyEvaluationService(this.resourceServer, this.authorization, this.auth);

    ResteasyProviderFactory.getInstance().injectProperties(resource);

    return resource;
}
 
Example #21
Source File: RealmsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("{realm}")
public PublicRealmResource getRealmResource(final @PathParam("realm") String name) {
    RealmModel realm = init(name);
    PublicRealmResource realmResource = new PublicRealmResource(realm);
    ResteasyProviderFactory.getInstance().injectProperties(realmResource);
    return realmResource;
}
 
Example #22
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private static SchedulerRestInterface createRestProxy(ResteasyProviderFactory provider, String restEndpointURL,
        ClientHttpEngine httpEngine) {
    ResteasyClient client = buildResteasyClient(provider);
    ResteasyWebTarget target = client.target(restEndpointURL);
    SchedulerRestInterface schedulerRestClient = target.proxy(SchedulerRestInterface.class);
    return createExceptionProxy(schedulerRestClient);
}
 
Example #23
Source File: RealmsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("{realm}/login-actions")
public LoginActionsService getLoginActionsService(final @PathParam("realm") String name) {
    RealmModel realm = init(name);
    EventBuilder event = new EventBuilder(realm, session, clientConnection);
    LoginActionsService service = new LoginActionsService(realm, event);
    ResteasyProviderFactory.getInstance().injectProperties(service);
    return service;
}
 
Example #24
Source File: PermissionInjector.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
public Single<Boolean> resolve(Class<? extends Single<Boolean>> rawType, Type genericType,
		Annotation[] annotations) {
	for (Annotation annotation : annotations) {
		if(annotation.annotationType() == HasPermission.class) {
			RoutingContext ctx = ResteasyProviderFactory.getContextData(RoutingContext.class);
			User user = ctx.user();
			if(user == null)
				return Single.just(false);
			return user.rxIsAuthorised(((HasPermission) annotation).value());
		}
	}
	return null;
}
 
Example #25
Source File: GlobalRequestResponseFilterResourceProvider.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
public void init(Config.Scope config) {
    ResteasyProviderFactory.getInstance().getContainerRequestFilterRegistry()
            .registerSingleton(GlobalRequestResponseFilter.INSTANCE);

    ResteasyProviderFactory.getInstance().getContainerResponseFilterRegistry()
            .registerSingleton(GlobalRequestResponseFilter.INSTANCE);
}
 
Example #26
Source File: LoginRedirectFilter.java    From redpipe with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	User subject = ResteasyProviderFactory.getContextData(User.class);
	if(subject == null){
		UriBuilder builder = requestContext.getUriInfo().getBaseUriBuilder();
		Session session = ResteasyProviderFactory.getContextData(Session.class);
		session.put(BaseSecurityResource.REDIRECT_KEY, requestContext.getUriInfo().getPath(false));
		URI loginUri = builder.path(BaseSecurityResource.class).path(BaseSecurityResource.class, "login").build();
		requestContext.abortWith(Response.status(Status.TEMPORARY_REDIRECT).location(loginUri).build());
	}
}
 
Example #27
Source File: QuasiFibers.java    From redpipe with Apache License 2.0 5 votes vote down vote up
public static <T> Fiber<T> rawFiber(SuspendableCallable<T> body){
	final Map<Class<?>, Object> contextDataMap = ResteasyProviderFactory.getContextDataMap();
	AppGlobals globals = AppGlobals.get();
	return new Fiber<T>(getContextScheduler(), () -> {
		try{
			// start by restoring the RE context in this Fiber's ThreadLocal
			ResteasyProviderFactory.pushContextDataMap(contextDataMap);
			AppGlobals.set(globals);
			return body.run();
		}finally {
			ResteasyProviderFactory.removeContextDataLevel();
			AppGlobals.set(null);
		}
	});
}
 
Example #28
Source File: SchedulerRestClient.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void registerGzipEncoding(ResteasyProviderFactory providerFactory) {
    if (!providerFactory.isRegistered(AcceptEncodingGZIPFilter.class)) {
        providerFactory.registerProvider(AcceptEncodingGZIPFilter.class);
    }
    if (!providerFactory.isRegistered(GZIPDecodingInterceptor.class)) {
        providerFactory.registerProvider(GZIPDecodingInterceptor.class);
    }
    if (!providerFactory.isRegistered(GZIPEncodingInterceptor.class)) {
        providerFactory.registerProvider(GZIPEncodingInterceptor.class);
    }
}
 
Example #29
Source File: Router.java    From redpipe with Apache License 2.0 5 votes vote down vote up
private static URI findURI(MethodFinder method, Object... params) {
	Method m = method.method();
	
	UriInfo uriInfo = ResteasyProviderFactory.getContextData(UriInfo.class);
	
	UriBuilder builder = uriInfo.getBaseUriBuilder().path(m.getDeclaringClass());
	if(m.isAnnotationPresent(Path.class))
		builder.path(m);
	return builder.build(params);
}
 
Example #30
Source File: GuiceRsApplicationServlet.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Override
public Object createResource(HttpRequest request, HttpResponse response, ResteasyProviderFactory factory)
{
    Object resource = provider.get();
    contextPropertyInjector.inject(request, response, resource);
    return resource;
}