Search in sources :

Example 41 with ConfigBeanProxy

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

the class TemplateRestResource method setParentAndTagName.

public void setParentAndTagName(Dom parent, String tagName) {
    if (parent == null) {
        // prevent https://glassfish.dev.java.net/issues/show_bug.cgi?id=14125
        throw new WebApplicationException(Response.Status.NOT_FOUND);
    }
    this.parent = parent;
    this.tagName = tagName;
    synchronized (parent) {
        entity = parent.nodeElement(tagName);
    }
    if (entity == null) {
        // In some cases, the tagName requested is not found in the DOM tree.  This is true,
        // for example, for the various ZeroConf elements (e.g., transaction-service).  If
        // the zero conf element is not in domain.xml, then it won't be in the Dom tree
        // returned by HK2.  If that's the case, we can use ConfigModularityUtils.getOwningObject()
        // to find the ConfigBean matching the path requested, which will add the node to
        // the Dom tree. Once that's done, we can return that node and proceed as normal
        String location = buildPath(parent) + "/" + tagName;
        if (location.startsWith("domain/configs")) {
            final ConfigModularityUtils cmu = locatorBridge.getRemoteLocator().<ConfigModularityUtils>getService(ConfigModularityUtils.class);
            ConfigBeanProxy cbp = cmu.getOwningObject(location);
            if (cbp == null) {
                cbp = cmu.getConfigBeanInstanceFor(cmu.getOwningClassForLocation(location));
            }
            if (cbp != null) {
                entity = Dom.unwrap(cbp);
                childModel = entity.model;
            }
        }
    // throw new WebApplicationException(new Exception("Trying to create an entity using generic create"),Response.Status.INTERNAL_SERVER_ERROR);
    } else {
        childModel = entity.model;
    }
}
Also used : ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) WebApplicationException(javax.ws.rs.WebApplicationException) ConfigModularityUtils(com.sun.enterprise.config.modularity.ConfigModularityUtils)

Example 42 with ConfigBeanProxy

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

the class CombinedJavaConfigSystemPropertyListener method changed.

/* force serial behavior; don't allow more than one thread to make a mess here */
@Override
public synchronized UnprocessedChangeEvents changed(PropertyChangeEvent[] events) {
    // ignore a REMOVE and an ADD of the same value
    final UnprocessedChangeEvents unp = ConfigSupport.sortAndDispatch(events, new Changed() {

        @Override
        public <T extends ConfigBeanProxy> NotProcessed changed(TYPE type, Class<T> tc, T t) {
            NotProcessed result = null;
            if (tc == Profiler.class) {
                result = new NotProcessed("Creation or changes to a profiler require restart");
            } else if (tc == Property.class && t.getParent().getClass() == JavaConfig.class) {
                result = new NotProcessed("Addition of properties to JavaConfig requires restart");
            } else if (tc == JavaConfig.class && t instanceof JavaConfig) {
                final JavaConfig njc = (JavaConfig) t;
                logFine(type, njc);
                // we must *always* check the jvm options, no way to know except by comparing,
                // plus we should send an appropriate message back for each removed/added item
                final List<String> curProps = new ArrayList<String>(njc.getJvmOptions());
                final boolean jvmOptionsWereChanged = !oldProps.equals(curProps);
                final List<String> reasons = handle(oldProps, curProps);
                oldProps = curProps;
                // something in the JavaConfig itself changed
                // to do this well, we ought to keep a list of attributes, so we can make a good message
                // saying exactly which attribute what changed
                final Map<String, String> curAttrs = collectAttrs(njc);
                reasons.addAll(handleAttrs(oldAttrs, curAttrs));
                oldAttrs = curAttrs;
                result = reasons.isEmpty() ? null : new NotProcessed(CombinedJavaConfigSystemPropertyListener.toString(reasons));
            } else if (tc == SystemProperty.class && t instanceof SystemProperty) {
                final SystemProperty sp = (SystemProperty) t;
                // check to see if this system property is for this instance
                ConfigBeanProxy proxy = sp.getParent();
                ConfigView p = ConfigSupport.getImpl(proxy);
                if (p == ConfigSupport.getImpl(server) || p == ConfigSupport.getImpl(config) || (cluster != null && p == ConfigSupport.getImpl(cluster)) || p == ConfigSupport.getImpl(domain)) {
                    // check to see if this system property is referenced by any of the options
                    String pname = sp.getName();
                    if (referencesProperty(pname, oldProps) || referencesProperty(pname, oldAttrs.values())) {
                        result = new NotProcessed("The system-property, " + pname + ", that is referenced by the Java configuration, was modified");
                    }
                }
                if (type == TYPE.ADD || type == TYPE.CHANGE) {
                    // create-system-properties
                    if (proxy instanceof Domain) {
                        return addToDomain(sp);
                    } else if (proxy instanceof Config && p == ConfigSupport.getImpl(config)) {
                        return addToConfig(sp);
                    } else if (cluster != null && proxy instanceof Cluster && p == ConfigSupport.getImpl(cluster)) {
                        return addToCluster(sp);
                    } else if (proxy instanceof Server && p == ConfigSupport.getImpl(server)) {
                        return addToServer(sp);
                    }
                } else if (type == TYPE.REMOVE) {
                    if (proxy instanceof Domain) {
                        return removeFromDomain(sp);
                    } else if (proxy instanceof Config && p == ConfigSupport.getImpl(config)) {
                        return removeFromConfig(sp);
                    } else if (cluster != null && proxy instanceof Cluster && p == ConfigSupport.getImpl(cluster)) {
                        return removeFromCluster(sp);
                    } else if (proxy instanceof Server && p == ConfigSupport.getImpl(server)) {
                        return removeFromServer(sp);
                    }
                }
            } else {
            // ignore other changes that are reported
            }
            return result;
        }
    }, logger);
    return unp;
}
Also used : UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) Server(com.sun.enterprise.config.serverbeans.Server) TranslatedConfigView(org.glassfish.config.support.TranslatedConfigView) ConfigView(org.jvnet.hk2.config.ConfigView) JavaConfig(com.sun.enterprise.config.serverbeans.JavaConfig) Config(com.sun.enterprise.config.serverbeans.Config) Cluster(com.sun.enterprise.config.serverbeans.Cluster) SystemProperty(com.sun.enterprise.config.serverbeans.SystemProperty) JavaConfig(com.sun.enterprise.config.serverbeans.JavaConfig) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) Profiler(com.sun.enterprise.config.serverbeans.Profiler) Changed(org.jvnet.hk2.config.Changed) NotProcessed(org.jvnet.hk2.config.NotProcessed) ArrayList(java.util.ArrayList) List(java.util.List) Domain(com.sun.enterprise.config.serverbeans.Domain) TYPE(org.jvnet.hk2.config.Changed.TYPE) Property(org.jvnet.hk2.config.types.Property) SystemProperty(com.sun.enterprise.config.serverbeans.SystemProperty) HashMap(java.util.HashMap) Map(java.util.Map)

Example 43 with ConfigBeanProxy

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

the class ApplicationLifecycle method registerAppInDomainXML.

// register application information in domain.xml
@Override
public void registerAppInDomainXML(final ApplicationInfo applicationInfo, final DeploymentContext context, Transaction t, boolean appRefOnly) throws TransactionFailure {
    final Properties appProps = context.getAppProps();
    final DeployCommandParameters deployParams = context.getCommandParameters(DeployCommandParameters.class);
    if (t != null) {
        try {
            if (!appRefOnly) {
                Application app_w = context.getTransientAppMetaData(ServerTags.APPLICATION, Application.class);
                // adding the application element
                setRestAppAttributes(app_w, appProps);
                Applications apps_w = t.enroll(applications);
                apps_w.getModules().add(app_w);
                if (applicationInfo != null) {
                    applicationInfo.save(app_w);
                }
            }
            List<String> targets = new ArrayList<String>();
            if (!DeploymentUtils.isDomainTarget(deployParams.target)) {
                targets.add(deployParams.target);
            } else {
                List<String> previousTargets = context.getTransientAppMetaData(DeploymentProperties.PREVIOUS_TARGETS, List.class);
                if (previousTargets == null) {
                    previousTargets = domain.getAllReferencedTargetsForApplication(deployParams.name);
                }
                targets = previousTargets;
            }
            String origVS = deployParams.virtualservers;
            Boolean origEnabled = deployParams.enabled;
            Properties previousVirtualServers = context.getTransientAppMetaData(DeploymentProperties.PREVIOUS_VIRTUAL_SERVERS, Properties.class);
            Properties previousEnabledAttributes = context.getTransientAppMetaData(DeploymentProperties.PREVIOUS_ENABLED_ATTRIBUTES, Properties.class);
            for (String target : targets) {
                // first reset the virtualservers, enabled attribute
                deployParams.virtualservers = origVS;
                deployParams.enabled = origEnabled;
                // applicable
                if (DeploymentUtils.isDomainTarget(deployParams.target)) {
                    String vs = previousVirtualServers.getProperty(target);
                    if (vs != null) {
                        deployParams.virtualservers = vs;
                    }
                    String enabledAttr = previousEnabledAttributes.getProperty(target);
                    if (enabledAttr != null) {
                        deployParams.enabled = Boolean.valueOf(enabledAttr);
                    }
                }
                if (deployParams.enabled == null) {
                    deployParams.enabled = Boolean.TRUE;
                }
                Server servr = domain.getServerNamed(target);
                if (servr != null) {
                    ApplicationRef instanceApplicationRef = domain.getApplicationRefInTarget(deployParams.name, servr.getName());
                    if (instanceApplicationRef == null) {
                        // adding the application-ref element to the standalone
                        // server instance
                        ConfigBeanProxy servr_w = t.enroll(servr);
                        // adding the application-ref element to the standalone
                        // server instance
                        ApplicationRef appRef = servr_w.createChild(ApplicationRef.class);
                        setAppRefAttributes(appRef, deployParams);
                        ((Server) servr_w).getApplicationRef().add(appRef);
                    }
                }
                Cluster cluster = domain.getClusterNamed(target);
                if (cluster != null) {
                    // adding the application-ref element to the cluster
                    // and instances
                    ConfigBeanProxy cluster_w = t.enroll(cluster);
                    ApplicationRef appRef = cluster_w.createChild(ApplicationRef.class);
                    setAppRefAttributes(appRef, deployParams);
                    ((Cluster) cluster_w).getApplicationRef().add(appRef);
                    for (Server svr : cluster.getInstances()) {
                        ConfigBeanProxy svr_w = t.enroll(svr);
                        ApplicationRef appRef2 = svr_w.createChild(ApplicationRef.class);
                        setAppRefAttributes(appRef2, deployParams);
                        ((Server) svr_w).getApplicationRef().add(appRef2);
                    }
                }
                DeploymentGroup dg = domain.getDeploymentGroupNamed(target);
                if (dg != null) {
                    ConfigBeanProxy dg_w = t.enroll(dg);
                    ApplicationRef appRef = dg_w.createChild(ApplicationRef.class);
                    setAppRefAttributes(appRef, deployParams);
                    ((DeploymentGroup) dg_w).getApplicationRef().add(appRef);
                    for (Server svr : dg.getInstances()) {
                        ApplicationRef instanceApplicationRef = domain.getApplicationRefInTarget(deployParams.name, svr.getName());
                        if (instanceApplicationRef == null) {
                            ConfigBeanProxy svr_w = t.enroll(svr);
                            ApplicationRef appRef2 = svr_w.createChild(ApplicationRef.class);
                            setAppRefAttributes(appRef2, deployParams);
                            ((Server) svr_w).getApplicationRef().add(appRef2);
                        }
                    }
                }
            }
        } catch (TransactionFailure e) {
            t.rollback();
            throw e;
        } catch (Exception e) {
            t.rollback();
            throw new TransactionFailure(e.getMessage(), e);
        }
        try {
            t.commit();
        } catch (RetryableException e) {
            System.out.println("Retryable...");
            // TODO : do something meaninful here
            t.rollback();
        } catch (TransactionFailure e) {
            t.rollback();
            throw e;
        }
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) PropertyVetoException(java.beans.PropertyVetoException) RetryableException(org.jvnet.hk2.config.RetryableException) MultiException(org.glassfish.hk2.api.MultiException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) IOException(java.io.IOException) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) RetryableException(org.jvnet.hk2.config.RetryableException) DeploymentGroup(fish.payara.enterprise.config.serverbeans.DeploymentGroup)

Example 44 with ConfigBeanProxy

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

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

the class SetCommand method setLeafElement.

public static void setLeafElement(final ConfigBean node, final String elementName, final String values) throws TransactionFailure {
    ConfigBeanProxy readableView = node.getProxy(node.getProxyType());
    ConfigSupport.apply(new SingleConfigCode<ConfigBeanProxy>() {

        /**
         * Runs the following command passing the configuration object. The
         * code will be run within a transaction, returning true will commit
         * the transaction, false will abort it.
         *
         * @param param is the configuration object protected by the
         * transaction
         * @return any object that should be returned from within the
         * transaction code
         * @throws java.beans.PropertyVetoException if the changes cannot be
         * applied to the configuration
         */
        @Override
        public Object run(ConfigBeanProxy param) throws PropertyVetoException, TransactionFailure {
            WriteableView writeableParent = (WriteableView) Proxy.getInvocationHandler(param);
            StringTokenizer st = new StringTokenizer(values, ",");
            List<String> valList = new ArrayList<>();
            while (st.hasMoreTokens()) {
                valList.add(st.nextToken());
            }
            ConfigBean bean = writeableParent.getMasterView();
            for (Method m : writeableParent.getProxyType().getMethods()) {
                // Check to see if the method is a setter for the element
                // An element setter has to have the right name, take a single
                // collection parameter that parameterized with the right type
                Class[] argClasses = m.getParameterTypes();
                Type[] argTypes = m.getGenericParameterTypes();
                ConfigModel.Property prop = bean.model.toProperty(m);
                if (prop == null || !prop.xmlName().equals(elementName) || argClasses.length != 1 || !Collection.class.isAssignableFrom(argClasses[0]) || argTypes.length != 1 || !(argTypes[0] instanceof ParameterizedType) || !Types.erasure(Types.getTypeArgument(argTypes[0], 0)).isAssignableFrom(values.getClass())) {
                    continue;
                }
                // we have the right method.  Now call it
                try {
                    m.invoke(writeableParent.getProxy(writeableParent.<ConfigBeanProxy>getProxyType()), valList);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    throw new TransactionFailure("Exception while setting element", e);
                }
                return node;
            }
            throw new TransactionFailure("No method found for setting element");
        }
    }, readableView);
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) ConfigBean(org.jvnet.hk2.config.ConfigBean) Method(java.lang.reflect.Method) PropertyVetoException(java.beans.PropertyVetoException) ParameterizedType(java.lang.reflect.ParameterizedType) WriteableView(org.jvnet.hk2.config.WriteableView) StringTokenizer(java.util.StringTokenizer) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) ArrayList(java.util.ArrayList) List(java.util.List) Property(org.jvnet.hk2.config.types.Property)

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