Search in sources :

Example 51 with ConfigBeanProxy

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

the class DeleteModuleConfigCommand method removeCustomTokens.

private static <T extends ConfigBeanProxy> boolean removeCustomTokens(final ConfigBeanDefaultValue configBeanDefaultValue, T finalConfigBean, ConfigBeanProxy parent) throws TransactionFailure, PropertyVetoException {
    if (parent instanceof SystemPropertyBag) {
        removeSystemPropertyForTokens(configBeanDefaultValue.getCustomizationTokens(), (SystemPropertyBag) parent);
        return true;
    } else {
        ConfigBeanProxy curParent = finalConfigBean;
        while (!(curParent instanceof SystemPropertyBag)) {
            curParent = curParent.getParent();
        }
        if (configBeanDefaultValue.getCustomizationTokens().size() != 0) {
            final SystemPropertyBag bag = (SystemPropertyBag) curParent;
            final List<ConfigCustomizationToken> tokens = configBeanDefaultValue.getCustomizationTokens();
            removeSystemPropertyForTokens(tokens, bag);
            return true;
        }
        return false;
    }
}
Also used : ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) ConfigCustomizationToken(com.sun.enterprise.config.modularity.customization.ConfigCustomizationToken) SystemPropertyBag(com.sun.enterprise.config.serverbeans.SystemPropertyBag)

Example 52 with ConfigBeanProxy

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

the class ReferenceValidator method isValid.

@Override
public boolean isValid(ConfigBeanProxy config, ConstraintValidatorContext cvc) throws UnexpectedTypeException {
    if (config == null) {
        return true;
    }
    Dom dom = Dom.unwrap(config);
    if (rc.skipDuringCreation() && dom.getKey() == null) {
        // During creation the coresponding DOM is not fully loaded.
        return true;
    }
    Collection<RemoteKeyInfo> remoteKeys = findRemoteKeys(config);
    if (remoteKeys != null && !remoteKeys.isEmpty()) {
        ServiceLocator habitat = dom.getHabitat();
        boolean result = true;
        boolean disableGlobalMessage = true;
        for (RemoteKeyInfo remoteKeyInfo : remoteKeys) {
            if (remoteKeyInfo.method.getParameterTypes().length > 0) {
                throw new UnexpectedTypeException(localStrings.getLocalString("referenceValidator.not.getter", "The RemoteKey annotation must be on a getter method."));
            }
            try {
                Object value = remoteKeyInfo.method.invoke(config);
                if (value instanceof String) {
                    String key = (String) value;
                    ConfigBeanProxy component = habitat.getService(remoteKeyInfo.annotation.type(), key);
                    if (component == null) {
                        result = false;
                        if (remoteKeyInfo.annotation.message().isEmpty()) {
                            disableGlobalMessage = false;
                        } else {
                            cvc.buildConstraintViolationWithTemplate(remoteKeyInfo.annotation.message()).addNode(Dom.convertName(remoteKeyInfo.method.getName())).addConstraintViolation();
                        }
                    }
                } else {
                    throw new UnexpectedTypeException(localStrings.getLocalString("referenceValidator.not.string", "The RemoteKey annotation must identify a method that returns a String."));
                }
            } catch (Exception ex) {
                return false;
            }
        }
        if (!result && disableGlobalMessage) {
            cvc.disableDefaultConstraintViolation();
        }
        return result;
    }
    return true;
}
Also used : ServiceLocator(org.glassfish.hk2.api.ServiceLocator) Dom(org.jvnet.hk2.config.Dom) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) UnexpectedTypeException(javax.validation.UnexpectedTypeException) UnexpectedTypeException(javax.validation.UnexpectedTypeException)

Example 53 with ConfigBeanProxy

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

the class ConfigConfigBeanListener method changed.

/* force serial behavior; don't allow more than one thread to make a mess here */
@Override
public synchronized UnprocessedChangeEvents changed(PropertyChangeEvent[] events) {
    for (PropertyChangeEvent e : events) {
        // ignore all events for which the source isn't the Config
        if (e.getSource().getClass() != config.getClass()) {
            continue;
        }
        // remove the DEFAULT_INSTANCE_NAME entry for an old value
        Object ov = e.getOldValue();
        if (ov instanceof ConfigBeanProxy) {
            ConfigBeanProxy ovbp = (ConfigBeanProxy) ov;
            logger.log(Level.FINE, removingDefaultInstanceIndexFor, ConfigSupport.getImpl(ovbp).getProxyType().getName());
            ServiceLocatorUtilities.removeFilter(habitat, BuilderHelper.createNameAndContractFilter(ConfigSupport.getImpl(ovbp).getProxyType().getName(), ServerEnvironment.DEFAULT_INSTANCE_NAME));
        }
        // add the DEFAULT_INSTANCE_NAME entry for a new value
        Object nv = e.getNewValue();
        if (nv instanceof ConfigBean) {
            ConfigBean nvb = (ConfigBean) nv;
            ConfigBeanProxy nvbp = nvb.getProxy(nvb.getProxyType());
            logger.log(Level.FINE, AddingDefaultInstanceIndexFor, nvb.getProxyType().getName());
            ServiceLocatorUtilities.addOneConstant(habitat, nvbp, ServerEnvironment.DEFAULT_INSTANCE_NAME, nvb.getProxyType());
        }
    }
    return null;
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) ConfigBean(org.jvnet.hk2.config.ConfigBean)

Example 54 with ConfigBeanProxy

use of org.jvnet.hk2.config.ConfigBeanProxy 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)

Example 55 with ConfigBeanProxy

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

the class BasicModularityTest method owningObjectTest.

@Test
public void owningObjectTest() {
    String location = "domain/configs/config[$CURRENT_INSTANCE_CONFIG_NAME]/config-extension-one/property[prop.foo]";
    ConfigBeanProxy obj = configModularityUtils.getOwningObject(location);
    assertNotNull("Cannot find owning object for: " + location, obj);
    assertEquals("Getting Owning object for location is not right", "prop.foo.value.custom", ((Property) obj).getValue());
}
Also used : ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) ConfigApiTest(com.sun.enterprise.configapi.tests.ConfigApiTest) Test(org.junit.Test)

Aggregations

ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)41 PropertyVetoException (java.beans.PropertyVetoException)21 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)14 Method (java.lang.reflect.Method)11 ArrayList (java.util.ArrayList)11 ConfigCode (org.jvnet.hk2.config.ConfigCode)10 Config (com.sun.enterprise.config.serverbeans.Config)8 Server (com.sun.enterprise.config.serverbeans.Server)6 IOException (java.io.IOException)6 List (java.util.List)6 ActionReport (org.glassfish.api.ActionReport)6 NetworkListeners (org.glassfish.grizzly.config.dom.NetworkListeners)6 Protocol (org.glassfish.grizzly.config.dom.Protocol)6 MultiException (org.glassfish.hk2.api.MultiException)6 ConfigModel (org.jvnet.hk2.config.ConfigModel)6 InvocationTargetException (java.lang.reflect.InvocationTargetException)5 XMLStreamException (javax.xml.stream.XMLStreamException)5 NetworkListener (org.glassfish.grizzly.config.dom.NetworkListener)5 ConfigBean (org.jvnet.hk2.config.ConfigBean)5 Property (org.jvnet.hk2.config.types.Property)5