Search in sources :

Example 26 with Attribute

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

the class DynamicConfigListener method processNetworkListener.

private <T extends ConfigBeanProxy> NotProcessed processNetworkListener(Changed.TYPE type, NetworkListener listener, final PropertyChangeEvent[] changedProperties) {
    if (findConfigName(listener).equals(findConfigName(config))) {
        boolean isAdminListener = ADMIN_LISTENER.equals(listener.getName());
        Lock portLock = null;
        try {
            portLock = acquirePortLock(listener);
            if (type == Changed.TYPE.ADD) {
                final int[] ports = portLock.getPorts();
                if (isAdminListener && ports[ports.length - 1] == -1) {
                    return null;
                }
                final Future future = grizzlyService.createNetworkProxy(listener);
                if (future != null) {
                    future.get(RECONFIG_LOCK_TIMEOUT_SEC, TimeUnit.SECONDS);
                    grizzlyService.registerContainerAdapters();
                } else {
                    logger.log(Level.FINE, "Skipping proxy registration for the listener {0}", listener.getName());
                }
            } else if (type == Changed.TYPE.REMOVE) {
                if (!isAdminListener) {
                    grizzlyService.removeNetworkProxy(listener);
                }
            } else if (type == Changed.TYPE.CHANGE) {
                // If the listener is the admin listener
                if (isAdminListener) {
                    final boolean dynamic = isAdminDynamic(changedProperties);
                    // If configuration is dynamic then make the change
                    if (dynamic) {
                        GrizzlyProxy proxy = (GrizzlyProxy) grizzlyService.lookupNetworkProxy(listener);
                        if (proxy != null) {
                            GrizzlyListener netListener = proxy.getUnderlyingListener();
                            netListener.processDynamicConfigurationChange(grizzlyService.getHabitat(), changedProperties);
                            return null;
                        }
                    }
                    // Otherwise return the unprocessed event, describing the changed values.
                    if (!isRedundantChange(changedProperties)) {
                        StringBuilder eventsMessage = new StringBuilder();
                        /* Add list of changed events to an events message.
                            *  Usually only one message is sent to this method at a time, so the for loop should only run once,
                            *  but it's there just in case.
                            */
                        for (PropertyChangeEvent event : changedProperties) {
                            eventsMessage.append("\"" + event.getPropertyName() + "\" changed from \"" + event.getOldValue() + "\" to \"" + event.getNewValue() + "\".\n");
                        }
                        return new NotProcessed(listener.getThreadPool() + " attribute " + eventsMessage.toString());
                    }
                    return null;
                }
                // Only restart the network listener if something hasn't changed
                if (!isRedundantChange(changedProperties)) {
                    MonitoringService ms = config.getMonitoringService();
                    String level = ms.getModuleMonitoringLevels().getHttpService();
                    // We only need to throw an unprocessed change event if monitoring is enabled for the HTTP service
                    if (level != null && (!level.equals(OFF))) {
                        String eventsMessage = "Monitoring statistics will be incorrect for " + listener.findHttpProtocolName() + " until restart due to changed attribute(s): ";
                        // so the for loop should only run once, but it's there just in case.
                        for (PropertyChangeEvent event : changedProperties) {
                            eventsMessage += ("\"" + event.getPropertyName() + "\" changed from \"" + event.getOldValue() + "\" to \"" + event.getNewValue() + "\".\n");
                        }
                        // Still restart the network listener, as it's only the monitoring that breaks.
                        grizzlyService.restartNetworkListener(listener, RECONFIG_LOCK_TIMEOUT_SEC, TimeUnit.SECONDS);
                        return new NotProcessed(eventsMessage);
                    } else {
                        // Restart the network listener without throwing an unprocessed change
                        grizzlyService.restartNetworkListener(listener, RECONFIG_LOCK_TIMEOUT_SEC, TimeUnit.SECONDS);
                    }
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Network listener configuration error. Type: " + type, e);
        } finally {
            if (portLock != null) {
                releaseListenerLock(portLock);
            }
        }
    }
    return null;
}
Also used : GrizzlyListener(org.glassfish.grizzly.config.GrizzlyListener) PropertyChangeEvent(java.beans.PropertyChangeEvent) Future(java.util.concurrent.Future) NotProcessed(org.jvnet.hk2.config.NotProcessed) MonitoringService(com.sun.enterprise.config.serverbeans.MonitoringService) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) ReentrantLock(java.util.concurrent.locks.ReentrantLock)

Example 27 with Attribute

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

the class CommandModelImpl method add.

private static void add(Map<String, ParamModel> results, AnnotatedElement e, I18n parentI18n, LocalStringManager localStrings) {
    Param param = e.getAnnotation(Param.class);
    if (param != null) {
        String defaultValue = param.defaultValue();
        ModelBinding mb = e.getAnnotation(ModelBinding.class);
        if (mb != null && defaultValue.isEmpty()) {
            Method m = null;
            try {
                m = mb.type().getMethod(mb.getterMethodName());
            } catch (NoSuchMethodException e1) {
            // ignore.
            }
            if (m != null) {
                Attribute attr = m.getAnnotation(Attribute.class);
                if (attr != null) {
                    defaultValue = attr.defaultValue();
                }
            }
        }
        ParamModel model = new ParamModelImpl(e, defaultValue, parentI18n, localStrings);
        if (!results.containsKey(model.getName())) {
            results.put(model.getName(), model);
        }
    }
}
Also used : ModelBinding(org.glassfish.api.admin.config.ModelBinding) Attribute(org.jvnet.hk2.config.Attribute) Param(org.glassfish.api.Param) Method(java.lang.reflect.Method)

Example 28 with Attribute

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

the class AttributeMethodVisitor method visitAnnotation.

/**
 * Visits an annotation of this method.
 *
 * @param desc the class descriptor of the annotation class.
 * @param visible <tt>true</tt> if the annotation is visible at runtime.
 *
 * @return a visitor to visit the annotation values, or <tt>null</tt> if this visitor is not interested in visiting
 *         this annotation.
 */
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
    duckTyped |= "Lorg/jvnet/hk2/config/DuckTyped;".equals(desc);
    AnnotationVisitor visitor = null;
    if ("Lorg/jvnet/hk2/config/Attribute;".equals(desc) || "Lorg/jvnet/hk2/config/Element;".equals(desc)) {
        try {
            final Class<?> configurable = Thread.currentThread().getContextClassLoader().loadClass(def.getDef());
            final Attribute annotation = configurable.getMethod(name).getAnnotation(Attribute.class);
            def.addAttribute(name, annotation);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    } else if ("Lorg/glassfish/api/admin/config/PropertiesDesc;".equals(desc)) {
        try {
            final Class<?> configurable = Thread.currentThread().getContextClassLoader().loadClass(def.getDef());
            final PropertiesDesc annotation = configurable.getMethod(name).getAnnotation(PropertiesDesc.class);
            final PropertyDesc[] propertyDescs = annotation.props();
            for (PropertyDesc prop : propertyDescs) {
                def.addProperty(prop);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    return visitor;
}
Also used : PropertiesDesc(org.glassfish.api.admin.config.PropertiesDesc) Attribute(org.jvnet.hk2.config.Attribute) AnnotationVisitor(org.glassfish.hk2.external.org.objectweb.asm.AnnotationVisitor) PropertyDesc(org.glassfish.api.admin.config.PropertyDesc)

Example 29 with Attribute

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

the class ResourcesGeneratorBase method processNonLeafChildElement.

private void processNonLeafChildElement(String elementName, ConfigModel.Property childElement, DomDocument domDocument, ClassWriter classWriter) {
    ConfigModel.Node node = (ConfigModel.Node) childElement;
    ConfigModel childModel = node.getModel();
    String beanName = ResourceUtil.getUnqualifiedTypeName(childModel.targetTypeName);
    if (beanName.equals("Property")) {
        classWriter.createGetChildResource("property", "PropertiesBagResource");
    } else if (beanName.equals("MonitoredAttribute")) {
        classWriter.createGetChildResource("monitored-attribute", "MonitoredAttributeBagResource");
    } else {
        String childResourceClassName = getClassName(beanName);
        if (childElement.isCollection()) {
            childResourceClassName = "List" + childResourceClassName;
        }
        classWriter.createGetChildResource(/*
                     * childModel.getTagName()
                     */
        elementName, childResourceClassName);
    }
    if (childElement.isCollection()) {
        generateList(childModel, domDocument);
    } else {
        generateSingle(childModel, domDocument);
    }
}
Also used : ConfigModel(org.jvnet.hk2.config.ConfigModel)

Example 30 with Attribute

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

Attribute (org.jvnet.hk2.config.Attribute)11 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)7 Method (java.lang.reflect.Method)6 ArrayList (java.util.ArrayList)6 PropertyChangeEvent (java.beans.PropertyChangeEvent)5 HashMap (java.util.HashMap)5 MultiException (org.glassfish.hk2.api.MultiException)5 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)5 Map (java.util.Map)4 Dom (org.jvnet.hk2.config.Dom)4 Property (org.jvnet.hk2.config.types.Property)4 Cluster (com.sun.enterprise.config.serverbeans.Cluster)3 SystemProperty (com.sun.enterprise.config.serverbeans.SystemProperty)3 PropertyVetoException (java.beans.PropertyVetoException)3 List (java.util.List)3 Param (org.glassfish.api.Param)3 ParameterMap (org.glassfish.api.admin.ParameterMap)3 Domain (com.sun.enterprise.config.serverbeans.Domain)2 MonitoringService (com.sun.enterprise.config.serverbeans.MonitoringService)2 Server (com.sun.enterprise.config.serverbeans.Server)2