org.glassfish.jersey.internal.inject.AbstractBinder Java Examples

The following examples show how to use org.glassfish.jersey.internal.inject.AbstractBinder. 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: Application.java    From ameba with MIT License 6 votes vote down vote up
private void registerBinder() {
    register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(Application.this).to(Application.class).proxy(false);
            bind(mode).to(Application.Mode.class).proxy(false);
            bind(ConfigurationInjectionResolver.class)
                    .to(new GenericType<InjectionResolver<Named>>() {
                    }).in(Singleton.class);
            bind(ValueConfigurationInjectionResolver.class)
                    .to(new GenericType<InjectionResolver<Value>>() {
                    }).in(Singleton.class);
        }
    });
    register(Requests.BindRequest.class);
    register(SysEventListener.class);
}
 
Example #2
Source File: ServiceTalkFeature.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Override
public boolean configure(final FeatureContext context) {
    if (!context.getConfiguration().isRegistered(EndpointEnhancingRequestFilter.class)) {
        context.register(BufferMessageBodyReaderWriter.class);
        context.register(BufferPublisherMessageBodyReaderWriter.class);
        context.register(BufferSingleMessageBodyReaderWriter.class);
        context.register(EndpointEnhancingRequestFilter.class);

        context.register(new AbstractBinder() {
            @Override
            protected void configure() {
                bindFactory(ConnectionContextReferencingFactory.class).to(ConnectionContext.class)
                        .proxy(true).proxyForSameScope(true).in(RequestScoped.class);
                bindFactory(referenceFactory()).to(CONNECTION_CONTEXT_REF_GENERIC_TYPE).in(RequestScoped.class);

                bindFactory(HttpRequestReferencingFactory.class).to(HTTP_REQUEST_GENERIC_TYPE)
                        .proxy(true).proxyForSameScope(false).in(RequestScoped.class);
                bindFactory(referenceFactory()).to(HTTP_REQUEST_REF_GENERIC_TYPE).in(RequestScoped.class);
            }
        });
    }

    return true;
}
 
Example #3
Source File: JerseyBinding.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
/**
 * Binds jersey specific component (component implements jersey interface or extends class).
 * Specific binding is required for types directly supported by jersey (e.g. ExceptionMapper).
 * Such types must be bound to target interface directly, otherwise jersey would not be able to resolve them.
 * <p> If type is {@link JerseyManaged}, binds directly.
 * Otherwise, use guice "bridge" factory to lazily bind type.</p>
 *
 * @param binder        jersey binder
 * @param injector      guice injector
 * @param type          type which implements specific jersey interface or extends class
 * @param specificType  specific jersey type (interface or abstract class)
 * @param jerseyManaged true if bean must be managed by jersey, false to bind guice managed instance
 * @param singleton     true to force singleton scope
 */
public static void bindSpecificComponent(final AbstractBinder binder,
                                         final Injector injector,
                                         final Class<?> type,
                                         final Class<?> specificType,
                                         final boolean jerseyManaged,
                                         final boolean singleton) {
    // resolve generics of specific type
    final GenericsContext context = GenericsResolver.resolve(type).type(specificType);
    final List<Type> genericTypes = context.genericTypes();
    final Type[] generics = genericTypes.toArray(new Type[0]);
    final Type bindingType = generics.length > 0 ? new ParameterizedTypeImpl(specificType, generics)
            : specificType;
    if (jerseyManaged) {
        optionalSingleton(
                binder.bind(type).to(type).to(bindingType),
                singleton);
    } else {
        optionalSingleton(
                binder.bindFactory(new GuiceComponentFactory<>(injector, type)).to(type).to(bindingType),
                singleton);
    }
}
 
Example #4
Source File: JerseyBinding.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
/**
 * Binds jersey {@link Supplier}. If bean is {@link JerseyManaged} then registered directly as
 * factory. Otherwise register factory through special "lazy bridge" to delay guice factory bean instantiation.
 * Also registers factory directly (through wrapper to be able to inject factory by its type).
 * <p>
 * NOTE: since jersey 2.26 jersey don't use hk2 directly and so all HK interfaces replaced by java 8 interfaces.
 *
 * @param binder        jersey binder
 * @param injector      guice injector
 * @param type          factory to bind
 * @param jerseyManaged true if bean must be managed by jersey, false to bind guice managed instance
 * @param singleton     true to force singleton scope
 * @param <T>           actual type (used to workaround type checks)
 * @see ru.vyarus.dropwizard.guice.module.jersey.support.LazyGuiceFactory
 * @see ru.vyarus.dropwizard.guice.module.jersey.support.GuiceComponentFactory
 */
@SuppressWarnings("unchecked")
public static <T> void bindFactory(final AbstractBinder binder, final Injector injector, final Class<?> type,
                                   final boolean jerseyManaged, final boolean singleton) {
    // resolve Factory<T> actual type to bind properly
    final Class<T> res = (Class<T>) GenericsResolver.resolve(type).type(Supplier.class).generic(0);
    if (jerseyManaged) {
        optionalSingleton(singleton
                        ? binder.bindFactory((Class<Supplier<T>>) type, Singleton.class).to(type).to(res)
                        : binder.bindFactory((Class<Supplier<T>>) type).to(type).to(res),
                singleton);
    } else {
        binder.bindFactory(new LazyGuiceFactory(injector, type)).to(res);
        // binding factory type to be able to autowire factory by name
        optionalSingleton(binder.bindFactory(new GuiceComponentFactory<>(injector, type)).to(type),
                singleton);
    }
}
 
Example #5
Source File: JerseyProviderInstaller.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
@Override
public void install(final AbstractBinder binder, final Injector injector, final Class<Object> type) {
    final boolean hkExtension = isJerseyExtension(type);
    final boolean forceSingleton = isForceSingleton(type, hkExtension);
    // since jersey 2.26 internal hk Factory class replaced by java 8 Supplier
    if (is(type, Supplier.class)) {
        // register factory directly (without wrapping)
        bindFactory(binder, injector, type, hkExtension, forceSingleton);

    } else {
        // support multiple extension interfaces on one type
        final Set<Class<?>> extensions = Sets.intersection(EXTENSION_TYPES,
                GenericsResolver.resolve(type).getGenericsInfo().getComposingTypes());
        if (!extensions.isEmpty()) {
            for (Class<?> ext : extensions) {
                bindSpecificComponent(binder, injector, type, ext, hkExtension, forceSingleton);
            }
        } else {
            // no known extension found
            bindComponent(binder, injector, type, hkExtension, forceSingleton);
        }
    }
}
 
Example #6
Source File: RxJerseyTest.java    From rx-jersey with MIT License 6 votes vote down vote up
@Override
protected Application configure() {
    ResourceConfig resourceConfig = new ResourceConfig()
            .register(InjectTestFeature.class)
            .register(JacksonFeature.class)
            .register(RxJerseyClientFeature.class)
            .register(ServerResource.class)
            .register(new AbstractBinder() {
                @Override
                protected void configure() {
                    bind(RxJerseyTest.this).to(JerseyTest.class);
                }
            });

    configure(resourceConfig);

    return resourceConfig;
}
 
Example #7
Source File: RxBodyWriterTest.java    From rx-jersey with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    injectionManager = new Hk2InjectionManagerFactory().create();
    injectionManager.register(
            new MessagingBinders.MessageBodyProviders(null, null)
    );
    injectionManager.register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(RxBodyWriter.class).to(MessageBodyWriter.class).in(Singleton.class);
        }
    });

    BootstrapBag bootstrapBag = new ServerBootstrapBag();
    bootstrapBag.setConfiguration(new ResourceConfig());

    MessageBodyWorkersConfigurator workerConfig = new MessageBodyWorkersConfigurator();
    workerConfig.init(injectionManager, bootstrapBag);
    injectionManager.completeRegistration();
    workerConfig.postInit(injectionManager, bootstrapBag);
}
 
Example #8
Source File: RxJerseyTest.java    From rx-jersey with MIT License 6 votes vote down vote up
@Override
protected Application configure() {
    ResourceConfig resourceConfig = new ResourceConfig()
            .register(InjectTestFeature.class)
            .register(JacksonFeature.class)
            .register(RxJerseyClientFeature.class)
            .register(ServerResource.class)
            .register(new AbstractBinder() {
                @Override
                protected void configure() {
                    bind(RxJerseyTest.this).to(JerseyTest.class);
                }
            });

    configure(resourceConfig);

    return resourceConfig;
}
 
Example #9
Source File: RxJerseyBinder.java    From rx-jersey with MIT License 5 votes vote down vote up
public RxJerseyBinder() {
    try {
        // Damn private properties everywhere
        injectionManagerField = AbstractBinder.class.getDeclaredField("injectionManager");
        injectionManagerField.setAccessible(true);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: HK2DebugFeature.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
@Override
public boolean configure(final FeatureContext context) {
    context.register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(listener).to(InstanceLifecycleListener.class);
        }
    });
    return true;
}
 
Example #11
Source File: JerseyBinding.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
/**
 * Binds component into jersey context. If component is annotated with {@link JerseyManaged}, then registers type,
 * otherwise register guice "bridge" factory around component.
 *
 * @param binder        jersey binder
 * @param injector      guice injector
 * @param type          component type
 * @param jerseyManaged true if bean must be managed by jersey, false to bind guice managed instance
 * @param singleton     true to force singleton scope
 * @see ru.vyarus.dropwizard.guice.module.jersey.support.GuiceComponentFactory
 */
public static void bindComponent(final AbstractBinder binder, final Injector injector, final Class<?> type,
                                 final boolean jerseyManaged, final boolean singleton) {
    if (jerseyManaged) {
        optionalSingleton(
                binder.bindAsContract(type),
                singleton);
    } else {
        // default case: simple service registered directly (including resource)
        optionalSingleton(
                binder.bindFactory(new GuiceComponentFactory<>(injector, type)).to(type),
                singleton);
    }
}
 
Example #12
Source File: EmbeddedHttpServer.java    From cantor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Server createServer(final int port, final String basePath) {
    final ResourceConfig config = new SwaggerJaxrsConfig();

    // bind resources with required constructor parameters
    final Cantor cantor = getCantorOnMysql();
    config.register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(new EventsResource(cantor));
            bind(new ObjectsResource(cantor));
            bind(new SetsResource(cantor));
            bind(new FunctionsResource(cantor));
        }
    });

    final Server server = new Server(port);

    // load jersey servlets
    final ServletHolder jerseyServlet = new ServletHolder(new ServletContainer(config));
    final ServletContextHandler context = new ServletContextHandler(server, "/");
    context.addServlet(jerseyServlet, basePath);

    // serve static resources
    context.setResourceBase("cantor-http-server/src/main/resources/static");
    context.addServlet(DefaultServlet.class, "/");

    return server;
}
 
Example #13
Source File: BackendServiceFactory.java    From jrestless-examples with Apache License 2.0 5 votes vote down vote up
public static Binder createBinder() {
	return new AbstractBinder() {
		@Override
		protected void configure() {
			bindFactory(BackendServiceFactory.class).to(BackendService.class).in(Singleton.class);
		}
	};
}
 
Example #14
Source File: JerseyLambdaContainerHandler.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
/**
 * Private constructor for a LambdaContainer. Sets the application object, sets the ApplicationHandler,
 * and initializes the application using the <code>onStartup</code> method.
 * @param requestTypeClass The class for the expected event type
 * @param responseTypeClass The class for the output type
 * @param requestReader A request reader instance
 * @param responseWriter A response writer instance
 * @param securityContextWriter A security context writer object
 * @param exceptionHandler An exception handler
 * @param jaxRsApplication The JaxRs application
 */
public JerseyLambdaContainerHandler(Class<RequestType> requestTypeClass,
                                    Class<ResponseType> responseTypeClass,
                                    RequestReader<RequestType, HttpServletRequest> requestReader,
                                    ResponseWriter<AwsHttpServletResponse, ResponseType> responseWriter,
                                    SecurityContextWriter<RequestType> securityContextWriter,
                                    ExceptionHandler<ResponseType> exceptionHandler,
                                    Application jaxRsApplication) {

    super(requestTypeClass, responseTypeClass, requestReader, responseWriter, securityContextWriter, exceptionHandler);
    Timer.start("JERSEY_CONTAINER_CONSTRUCTOR");
    initialized = false;
    if (jaxRsApplication instanceof ResourceConfig) {
        ((ResourceConfig)jaxRsApplication).register(new AbstractBinder() {
            @Override
            protected void configure() {
                bindFactory(AwsProxyServletContextSupplier.class)
                        .proxy(true)
                        .proxyForSameScope(true)
                        .to(ServletContext.class)
                        .in(RequestScoped.class);
                bindFactory(AwsProxyServletRequestSupplier.class)
                        .proxy(true)
                        .proxyForSameScope(true)
                        .to(HttpServletRequest.class)
                        .in(RequestScoped.class);
                bindFactory(AwsProxyServletResponseSupplier.class)
                        .proxy(true)
                        .proxyForSameScope(true)
                        .to(HttpServletResponse.class)
                        .in(RequestScoped.class);
            }
        });
    }

    this.jerseyFilter = new JerseyHandlerFilter(jaxRsApplication);
    Timer.stop("JERSEY_CONTAINER_CONSTRUCTOR");
}
 
Example #15
Source File: MockApp.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
public MockApp(Path dir) {
    super(dir);

    register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(MockApp.this).to(MockApp.class);
        }
    });
}
 
Example #16
Source File: ModuleBinder.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
public ModuleBinder() {
    interceptionService = new HK2InterceptionService();
    jerseyBinder = new AbstractBinder() {
        @Override
        protected void configure() {
            bind(interceptionService).to(InterceptionService.class).in(Singleton.class);
        }
    };
}
 
Example #17
Source File: DefaultJerseyStreamingHttpRouter.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private DefaultJerseyStreamingHttpRouter(final ApplicationHandler applicationHandler,
                                         final int publisherInputStreamQueueCapacity,
                                         final BiFunction<ConnectionContext, HttpRequestMetaData,
                                                 String> baseUriFunction,
                                         final RouteExecutionStrategyFactory<HttpExecutionStrategy>
                                                 strategyFactory) {

    if (!applicationHandler.getConfiguration().isEnabled(ServiceTalkFeature.class)) {
        throw new IllegalStateException("The " + ServiceTalkFeature.class.getSimpleName()
                + " needs to be enabled for this application.");
    }

    final RouteStrategiesConfig routeStrategiesConfig =
            validateRouteStrategies(applicationHandler, strategyFactory);

    this.applicationHandler = applicationHandler;
    this.publisherInputStreamQueueCapacity = publisherInputStreamQueueCapacity;
    this.baseUriFunction = requireNonNull(baseUriFunction);

    applicationHandler.getInjectionManager().register(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(routeStrategiesConfig).to(RouteStrategiesConfig.class).proxy(false);
        }
    });

    container = new DefaultContainer(applicationHandler);
    applicationHandler.onStartup(container);
}
 
Example #18
Source File: ResourceInstaller.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
@Override
public void install(final AbstractBinder binder, final Injector injector, final Class<Object> type) {
    final boolean jerseyManaged = isJerseyExtension(type);
    JerseyBinding.bindComponent(binder, injector, type, jerseyManaged, isForceSingleton(type, jerseyManaged));
}
 
Example #19
Source File: ModuleBinder.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
BindingBuilder(Type type, AbstractBinder binder) {
    this.type = type;
    this.binder = binder;
}
 
Example #20
Source File: ModuleBinder.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
public AbstractBinder raw() {
    return jerseyBinder;
}
 
Example #21
Source File: JerseyInstaller.java    From dropwizard-guicey with MIT License 2 votes vote down vote up
/**
 * Called on jersey start to inject extensions into HK context.
 * Use {@link ru.vyarus.dropwizard.guice.module.installer.util.JerseyBinding} utility for proper types binding:
 * it provide utilities for various jersey extensions and use special "bridges" for registration to
 * respect guice scopes (most of the time we not register ready instance, but factory which delegates
 * creation to guice).
 *
 * @param binder   hk binder
 * @param injector guice injector
 * @param type     extension type to register
 * @see ru.vyarus.dropwizard.guice.module.installer.util.JerseyBinding
 * @see ru.vyarus.dropwizard.guice.module.installer.feature.jersey.JerseyManaged
 */
void install(AbstractBinder binder, Injector injector, Class<T> type);