Search in sources :

Example 1 with InjectionManager

use of org.jvnet.hk2.config.InjectionManager in project jersey by jersey.

the class JettyContainerTest method testParentServiceLocator.

/**
     * Test that defined ServiceLocator becomes a parent of the newly created service locator.
     */
@Test
public void testParentServiceLocator() {
    final ServiceLocator locator = new ServiceLocatorImpl("MyServiceLocator", null);
    final Server server = JettyHttpContainerFactory.createServer(URI.create("http://localhost:9876"), new ResourceConfig(Resource.class), false, locator);
    JettyHttpContainer container = (JettyHttpContainer) server.getHandler();
    InjectionManager injectionManager = container.getApplicationHandler().getInjectionManager();
    HK2InjectionManager hk2InjectionManager = (HK2InjectionManager) injectionManager;
    ServiceLocator serviceLocator = hk2InjectionManager.getServiceLocator();
    assertTrue("Application injection manager was expected to have defined parent locator", serviceLocator.getParent() == locator);
}
Also used : ServiceLocator(org.glassfish.hk2.api.ServiceLocator) Server(org.eclipse.jetty.server.Server) HK2InjectionManager(org.glassfish.jersey.hk2.HK2InjectionManager) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) JettyHttpContainer(org.glassfish.jersey.jetty.JettyHttpContainer) ServiceLocatorImpl(org.jvnet.hk2.internal.ServiceLocatorImpl) HK2InjectionManager(org.glassfish.jersey.hk2.HK2InjectionManager) InjectionManager(org.glassfish.jersey.internal.inject.InjectionManager) Test(org.junit.Test) JerseyTest(org.glassfish.jersey.test.JerseyTest)

Example 2 with InjectionManager

use of org.jvnet.hk2.config.InjectionManager in project jersey by jersey.

the class SpringComponentProvider method initialize.

@Override
public void initialize(InjectionManager injectionManager) {
    this.injectionManager = injectionManager;
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(LocalizationMessages.CTX_LOOKUP_STARTED());
    }
    ServletContext sc = injectionManager.getInstance(ServletContext.class);
    if (sc != null) {
        // servlet container
        ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
    } else {
        // non-servlet container
        ctx = createSpringContext();
    }
    if (ctx == null) {
        LOGGER.severe(LocalizationMessages.CTX_LOOKUP_FAILED());
        return;
    }
    LOGGER.config(LocalizationMessages.CTX_LOOKUP_SUCESSFUL());
    // initialize HK2 spring-bridge
    HK2InjectionManager hk2InjectionManager = (HK2InjectionManager) injectionManager;
    SpringBridge.getSpringBridge().initializeSpringBridge(hk2InjectionManager.getServiceLocator());
    SpringIntoHK2Bridge springBridge = injectionManager.getInstance(SpringIntoHK2Bridge.class);
    springBridge.bridgeSpringBeanFactory(ctx);
    // register Spring @Autowired annotation handler with HK2 ServiceLocator
    Binder binder = new AbstractBinder() {

        @Override
        protected void configure() {
            bind(new AutowiredInjectResolver(ctx)).to(InjectionResolver.class);
            bind(ctx).to(ApplicationContext.class).named("SpringContext");
        }
    };
    injectionManager.register(binder);
    LOGGER.config(LocalizationMessages.SPRING_COMPONENT_PROVIDER_INITIALIZED());
}
Also used : AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) Binder(org.glassfish.jersey.internal.inject.Binder) ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) SpringIntoHK2Bridge(org.jvnet.hk2.spring.bridge.api.SpringIntoHK2Bridge) AbstractBinder(org.glassfish.jersey.internal.inject.AbstractBinder) ServletContext(javax.servlet.ServletContext) HK2InjectionManager(org.glassfish.jersey.hk2.HK2InjectionManager)

Example 3 with InjectionManager

use of org.jvnet.hk2.config.InjectionManager in project Payara by payara.

the class GenericCrudCommand method prepareInjection.

void prepareInjection(final AdminCommandContext ctx) {
    // inject resolver with command parameters...
    manager = new InjectionManager();
    resolver = habitat.getService(resolverType);
    paramResolver = getInjectionResolver();
    manager.inject(resolver, paramResolver);
}
Also used : InjectionManager(org.jvnet.hk2.config.InjectionManager)

Example 4 with InjectionManager

use of org.jvnet.hk2.config.InjectionManager in project Payara by payara.

the class GenericCrudCommand method getInjectionResolver.

public InjectionResolver<Param> getInjectionResolver() {
    final InjectionResolver<Param> delegate = injector;
    return new InjectionResolver<Param>(Param.class) {

        @Override
        public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
            if (type.isAssignableFrom(List.class)) {
                final List<ConfigBeanProxy> values;
                try {
                    if (annotated instanceof Method) {
                        values = (List<ConfigBeanProxy>) ((Method) annotated).invoke(component);
                    } else if (annotated instanceof Field) {
                        values = (List<ConfigBeanProxy>) ((Field) annotated).get(component);
                    } else {
                        String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invalid_type", "Invalid annotated type {0} passed to InjectionResolver:getValue()", annotated.getClass().toString());
                        logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVALID_ANNO_TYPE, annotated.getClass().toString());
                        throw new MultiException(new IllegalArgumentException(msg));
                    }
                } catch (IllegalAccessException e) {
                    String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invocation_failure", "Failure {0} while getting List<?> values from component", e.getMessage());
                    logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVOKE_FAILURE);
                    throw new MultiException(new IllegalStateException(msg, e));
                } catch (InvocationTargetException e) {
                    String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invocation_failure", "Failure {0} while getting List<?> values from component", e.getMessage());
                    logger.log(Level.SEVERE, ConfigApiLoggerInfo.INVOKE_FAILURE);
                    throw new MultiException(new IllegalStateException(msg, e));
                }
                Object value = delegate.getValue(component, annotated, genericType, type);
                if (value == null) {
                    if (logger.isLoggable(level)) {
                        logger.log(level, "Value of " + annotated.toString() + " is null");
                    }
                    return null;
                }
                Type genericReturnType = null;
                if (annotated instanceof Method) {
                    genericReturnType = ((Method) annotated).getGenericReturnType();
                } else if (annotated instanceof Field) {
                    genericReturnType = ((Field) annotated).getGenericType();
                }
                if (genericReturnType == null) {
                    throw new MultiException(new IllegalArgumentException("Cannot determine parametized type from " + annotated.toString()));
                }
                final Class<? extends ConfigBeanProxy> itemType = Types.erasure(Types.getTypeArgument(genericReturnType, 0));
                if (logger.isLoggable(level)) {
                    logger.log(level, "Found that List<?> really is a List<" + itemType.toString() + ">");
                }
                if (itemType == null) {
                    String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.nongeneric_type", "The List type returned by {0} must be a generic type", annotated.toString());
                    logger.log(Level.SEVERE, ConfigApiLoggerInfo.LIST_NOT_GENERIC_TYPE, annotated.toString());
                    throw new MultiException(new IllegalArgumentException(msg));
                }
                if (!ConfigBeanProxy.class.isAssignableFrom(itemType)) {
                    String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.wrong_type", "The generic type {0} is not supported, only List<? extends ConfigBeanProxy> is", annotated.toString());
                    logger.log(Level.SEVERE, ConfigApiLoggerInfo.GENERIC_TYPE_NOT_SUPPORTED, annotated.toString());
                    throw new MultiException(new IllegalArgumentException(msg));
                }
                Properties props = convertStringToProperties(value.toString(), ':');
                if (logger.isLoggable(level)) {
                    for (Map.Entry<Object, Object> entry : props.entrySet()) {
                        logger.log(level, "Subtype " + itemType + " key:" + entry.getKey() + " value:" + entry.getValue());
                    }
                }
                final BeanInfo beanInfo;
                try {
                    beanInfo = Introspector.getBeanInfo(itemType);
                } catch (IntrospectionException e) {
                    String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.introspection_failure", "Failure {0} while instrospecting {1} to find all getters and setters", e.getMessage(), itemType.getName());
                    LogHelper.log(logger, Level.SEVERE, ConfigApiLoggerInfo.INTROSPECTION_FAILED, e, itemType.getName());
                    throw new MultiException(new IllegalStateException(msg, e));
                }
                for (final Map.Entry<Object, Object> entry : props.entrySet()) {
                    ConfigBeanProxy child = (ConfigBeanProxy) component;
                    try {
                        ConfigBeanProxy cc = child.createChild(itemType);
                        new InjectionManager().inject(cc, itemType, new InjectionResolver<Attribute>(Attribute.class) {

                            @Override
                            public boolean isOptional(AnnotatedElement annotated, Attribute annotation) {
                                return true;
                            }

                            @Override
                            public Method getSetterMethod(Method annotated, Attribute annotation) {
                                // variant.
                                for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                                    if (pd.getReadMethod().equals(annotated)) {
                                        return pd.getWriteMethod();
                                    }
                                }
                                return annotated;
                            }

                            @Override
                            public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
                                String name = annotated.getAnnotation(Attribute.class).value();
                                if ((name == null || name.length() == 0) && annotated instanceof Method) {
                                    // maybe there is a better way to do this...
                                    name = ((Method) annotated).getName().substring(3);
                                    if (name.equalsIgnoreCase("name") || name.equalsIgnoreCase("key")) {
                                        return type.cast(entry.getKey());
                                    }
                                    if (name.equalsIgnoreCase("value")) {
                                        return type.cast(entry.getValue());
                                    }
                                }
                                return null;
                            }
                        });
                        values.add(cc);
                    } catch (TransactionFailure transactionFailure) {
                        String msg = localStrings.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.transactionException", "Transaction exception {0} while injecting {1}", transactionFailure.getMessage(), itemType);
                        LogHelper.log(logger, Level.SEVERE, ConfigApiLoggerInfo.TX_FAILED, transactionFailure, itemType);
                        throw new MultiException(new IllegalStateException(msg, transactionFailure));
                    }
                }
                return null;
            }
            return delegate.getValue(component, annotated, genericType, type);
        }

        @Override
        public boolean isOptional(AnnotatedElement annotated, Param annotation) {
            return annotation.optional();
        }
    };
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Attribute(org.jvnet.hk2.config.Attribute) BeanInfo(java.beans.BeanInfo) AnnotatedElement(java.lang.reflect.AnnotatedElement) IntrospectionException(java.beans.IntrospectionException) Properties(java.util.Properties) Field(java.lang.reflect.Field) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) List(java.util.List) PropertyDescriptor(java.beans.PropertyDescriptor) GenerateServiceFromMethod(org.jvnet.hk2.config.GenerateServiceFromMethod) Method(java.lang.reflect.Method) InjectionResolver(org.jvnet.hk2.config.InjectionResolver) InvocationTargetException(java.lang.reflect.InvocationTargetException) Type(java.lang.reflect.Type) Param(org.glassfish.api.Param) MultiException(org.glassfish.hk2.api.MultiException) Map(java.util.Map) InjectionManager(org.jvnet.hk2.config.InjectionManager)

Aggregations

HK2InjectionManager (org.glassfish.jersey.hk2.HK2InjectionManager)2 InjectionManager (org.jvnet.hk2.config.InjectionManager)2 BeanInfo (java.beans.BeanInfo)1 IntrospectionException (java.beans.IntrospectionException)1 PropertyDescriptor (java.beans.PropertyDescriptor)1 AnnotatedElement (java.lang.reflect.AnnotatedElement)1 Field (java.lang.reflect.Field)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 Type (java.lang.reflect.Type)1 List (java.util.List)1 Map (java.util.Map)1 Properties (java.util.Properties)1 ServletContext (javax.servlet.ServletContext)1 Server (org.eclipse.jetty.server.Server)1 Param (org.glassfish.api.Param)1 MultiException (org.glassfish.hk2.api.MultiException)1 ServiceLocator (org.glassfish.hk2.api.ServiceLocator)1 AbstractBinder (org.glassfish.jersey.internal.inject.AbstractBinder)1 Binder (org.glassfish.jersey.internal.inject.Binder)1