Search in sources :

Example 1 with SingleConfigCode

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

the class BaseRequestTracingNotifierConfigurer method execute.

@Override
public void execute(AdminCommandContext context) {
    final ActionReport actionReport = context.getActionReport();
    Properties extraProperties = actionReport.getExtraProperties();
    if (extraProperties == null) {
        extraProperties = new Properties();
        actionReport.setExtraProperties(extraProperties);
    }
    Config config = targetUtil.getConfig(target);
    final RequestTracingServiceConfiguration configuration = config.getExtensionByType(RequestTracingServiceConfiguration.class);
    ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    notifierClass = (Class<C>) genericSuperclass.getActualTypeArguments()[0];
    C c = configuration.getNotifierByType(notifierClass);
    try {
        if (c == null) {
            ConfigSupport.apply(new SingleConfigCode<RequestTracingServiceConfiguration>() {

                @Override
                public Object run(final RequestTracingServiceConfiguration configurationProxy) throws PropertyVetoException, TransactionFailure {
                    C c = configurationProxy.createChild(notifierClass);
                    applyValues(c);
                    configurationProxy.getNotifierList().add(c);
                    actionReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
                    return configurationProxy;
                }
            }, configuration);
        } else {
            ConfigSupport.apply(new SingleConfigCode<C>() {

                public Object run(C cProxy) throws PropertyVetoException, TransactionFailure {
                    applyValues(cProxy);
                    actionReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
                    return cProxy;
                }
            }, c);
        }
        if (dynamic) {
            if (server.isDas()) {
                if (targetUtil.getConfig(target).isDas()) {
                    configureDynamically();
                }
            } else {
                configureDynamically();
            }
        }
    } catch (TransactionFailure ex) {
        logger.log(Level.WARNING, "Exception during command ", ex);
        actionReport.setMessage(ex.getCause().getMessage());
        actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
    }
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) PropertyVetoException(java.beans.PropertyVetoException) TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Config(com.sun.enterprise.config.serverbeans.Config) ActionReport(org.glassfish.api.ActionReport) Properties(java.util.Properties) RequestTracingServiceConfiguration(fish.payara.nucleus.requesttracing.configuration.RequestTracingServiceConfiguration)

Example 2 with SingleConfigCode

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

the class SetCommand method set.

private boolean set(AdminCommandContext context, SetOperation op) {
    String pattern = op.pattern;
    String value = op.value;
    String target = op.target;
    String attrName = op.attrName;
    boolean isProperty = op.isProperty;
    // now
    // first let's get the parent for this pattern.
    TreeNode[] parentNodes = getAliasedParent(domain, pattern);
    // reset the pattern.
    String prefix;
    boolean lookAtSubNodes = true;
    if (parentNodes[0].relativeName.length() == 0 || parentNodes[0].relativeName.equals("domain")) {
        // handle the case where the pattern references an attribute of the top-level node
        prefix = "";
        // pattern is already set properly
        lookAtSubNodes = false;
    } else if (!pattern.startsWith(parentNodes[0].relativeName)) {
        prefix = pattern.substring(0, pattern.indexOf(parentNodes[0].relativeName));
        pattern = parentNodes[0].relativeName;
    } else {
        prefix = "";
        pattern = parentNodes[0].relativeName;
    }
    String targetName = prefix + pattern;
    if (modularityHelper != null) {
        synchronized (utils) {
            boolean oldv = utils.isCommandInvocation();
            utils.setCommandInvocation(true);
            modularityHelper.getLocationForDottedName(targetName);
            utils.setCommandInvocation(oldv);
        }
    }
    Map<Dom, String> matchingNodes;
    boolean applyOverrideRules = false;
    Map<Dom, String> dottedNames = new HashMap<Dom, String>();
    if (lookAtSubNodes) {
        for (TreeNode parentNode : parentNodes) {
            dottedNames.putAll(getAllDottedNodes(parentNode.node));
        }
        matchingNodes = getMatchingNodes(dottedNames, pattern);
        applyOverrideRules = true;
    } else {
        matchingNodes = new HashMap<Dom, String>();
        for (TreeNode parentNode : parentNodes) {
            matchingNodes.put(parentNode.node, pattern);
        }
    }
    if (matchingNodes.isEmpty()) {
        // it's possible they are trying to create a property object.. lets check this.
        // strip out the property name
        pattern = target.substring(0, trueLastIndexOf(target, '.'));
        if (pattern.endsWith("property")) {
            // need to find the right parent.
            Dom parentNode = null;
            if ("property".equals(pattern)) {
                // create and set the property
                try {
                    final String fname = attrName;
                    final String fvalue = value;
                    ConfigSupport.apply(new SingleConfigCode<Domain>() {

                        @Override
                        public Object run(Domain domain) throws PropertyVetoException, TransactionFailure {
                            Property p = domain.createChild(Property.class);
                            p.setName(fname);
                            p.setValue(fvalue);
                            domain.getProperty().add(p);
                            return p;
                        }
                    }, domain);
                    success(context, targetName, value);
                    runLegacyChecks(context);
                    if (targetService.isThisDAS() && !replicateSetCommand(context, target, value)) {
                        return false;
                    }
                    return true;
                } catch (TransactionFailure transactionFailure) {
                    // fail(context, "Could not change the attributes: " +
                    // transactionFailure.getMessage(), transactionFailure);
                    fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", transactionFailure.getMessage()), transactionFailure);
                    return false;
                }
            } else {
                pattern = pattern.substring(0, trueLastIndexOf(pattern, '.'));
                parentNodes = getAliasedParent(domain, pattern);
            }
            pattern = parentNodes[0].relativeName;
            matchingNodes = getMatchingNodes(dottedNames, pattern);
            if (matchingNodes.isEmpty()) {
                // fail(context, "No configuration found for " + targetName);
                fail(context, localStrings.getLocalString("admin.set.configuration.notfound", "No configuration found for {0}", targetName));
                return false;
            }
            for (Map.Entry<Dom, String> node : matchingNodes.entrySet()) {
                if (node.getValue().equals(pattern)) {
                    parentNode = node.getKey();
                }
            }
            if (parentNode == null) {
                // fail(context, "No configuration found for " + targetName);
                fail(context, localStrings.getLocalString("admin.set.configuration.notfound", "No configuration found for {0}", targetName));
                return false;
            }
            if (value == null || value.length() == 0) {
                // setting to the empty string means to remove the property, so don't create it
                success(context, targetName, value);
                return true;
            }
            // create and set the property
            Map<String, String> attributes = new HashMap<String, String>();
            attributes.put("value", value);
            attributes.put("name", attrName);
            try {
                if (!(parentNode instanceof ConfigBean)) {
                    final ClassCastException cce = new ClassCastException(parentNode.getClass().getName());
                    fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", cce.getMessage(), cce));
                    return false;
                }
                ConfigSupport.createAndSet((ConfigBean) parentNode, Property.class, attributes);
                success(context, targetName, value);
                runLegacyChecks(context);
                if (targetService.isThisDAS() && !replicateSetCommand(context, target, value)) {
                    return false;
                }
                return true;
            } catch (TransactionFailure transactionFailure) {
                // fail(context, "Could not change the attributes: " +
                // transactionFailure.getMessage(), transactionFailure);
                fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", transactionFailure.getMessage()), transactionFailure);
                return false;
            }
        }
    }
    Map<ConfigBean, Map<String, String>> changes = new HashMap<ConfigBean, Map<String, String>>();
    boolean setElementSuccess = false;
    boolean delPropertySuccess = false;
    boolean delProperty = false;
    Map<String, String> attrChanges = new HashMap<String, String>();
    if (isProperty) {
        attrName = "value";
        if ((value == null) || (value.length() == 0)) {
            delProperty = true;
        }
        attrChanges.put(attrName, value);
    }
    List<Map.Entry> mNodes = new ArrayList(matchingNodes.entrySet());
    if (applyOverrideRules) {
        mNodes = applyOverrideRules(mNodes);
    }
    for (Map.Entry<Dom, String> node : mNodes) {
        final Dom targetNode = node.getKey();
        for (String name : targetNode.model.getAttributeNames()) {
            String finalDottedName = node.getValue() + "." + name;
            if (matches(finalDottedName, pattern)) {
                if (attrName.equals(name) || attrName.replace('_', '-').equals(name.replace('_', '-'))) {
                    if (isDeprecatedAttr(targetNode, name)) {
                        warning(context, localStrings.getLocalString("admin.set.deprecated", "Warning: The attribute {0} is deprecated.", finalDottedName));
                    }
                    if (!isProperty) {
                        targetName = prefix + finalDottedName;
                        if (value != null && value.length() > 0) {
                            attrChanges.put(name, value);
                        } else {
                            attrChanges.put(name, null);
                        }
                    } else {
                        targetName = prefix + node.getValue();
                    }
                    if (delProperty) {
                        // delete property element
                        String str = node.getValue();
                        if (trueLastIndexOf(str, '.') != -1) {
                            str = str.substring(trueLastIndexOf(str, '.') + 1);
                        }
                        try {
                            if (str != null) {
                                ConfigSupport.deleteChild((ConfigBean) targetNode.parent(), (ConfigBean) targetNode);
                                delPropertySuccess = true;
                            }
                        } catch (IllegalArgumentException ie) {
                            fail(context, localStrings.getLocalString("admin.set.delete.property.failure", "Could not delete the property: {0}", ie.getMessage()), ie);
                            return false;
                        } catch (TransactionFailure transactionFailure) {
                            fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", transactionFailure.getMessage()), transactionFailure);
                            return false;
                        }
                    } else {
                        changes.put((ConfigBean) node.getKey(), attrChanges);
                    }
                }
            }
        }
        for (String name : targetNode.model.getLeafElementNames()) {
            String finalDottedName = node.getValue() + "." + name;
            if (matches(finalDottedName, pattern)) {
                if (attrName.equals(name) || attrName.replace('_', '-').equals(name.replace('_', '-'))) {
                    if (isDeprecatedAttr(targetNode, name)) {
                        warning(context, localStrings.getLocalString("admin.set.elementdeprecated", "Warning: The element {0} is deprecated.", finalDottedName));
                    }
                    try {
                        setLeafElement((ConfigBean) targetNode, name, value);
                    } catch (TransactionFailure ex) {
                        fail(context, localStrings.getLocalString("admin.set.badelement", "Cannot change the element: {0}", ex.getMessage()), ex);
                        return false;
                    }
                    setElementSuccess = true;
                    break;
                }
            }
        }
    }
    if (!changes.isEmpty()) {
        try {
            config.apply(changes);
            success(context, targetName, value);
            runLegacyChecks(context);
        } catch (TransactionFailure transactionFailure) {
            // fail(context, "Could not change the attributes: " +
            // transactionFailure.getMessage(), transactionFailure);
            fail(context, localStrings.getLocalString("admin.set.attribute.change.failure", "Could not change the attributes: {0}", transactionFailure.getMessage()), transactionFailure);
            return false;
        }
    } else if (delPropertySuccess || setElementSuccess) {
        success(context, targetName, value);
    } else {
        fail(context, localStrings.getLocalString("admin.set.configuration.notfound", "No configuration found for {0}", targetName));
        return false;
    }
    if (targetService.isThisDAS() && !replicateSetCommand(context, target, value)) {
        return false;
    }
    return true;
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Property(org.jvnet.hk2.config.types.Property) Dom(org.jvnet.hk2.config.Dom) ConfigBean(org.jvnet.hk2.config.ConfigBean) PropertyVetoException(java.beans.PropertyVetoException) Domain(com.sun.enterprise.config.serverbeans.Domain) HashMap(java.util.HashMap) Map(java.util.Map) ParameterMap(org.glassfish.api.admin.ParameterMap)

Example 3 with SingleConfigCode

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

the class BaseNotificationConfigurer method execute.

@Override
public void execute(final AdminCommandContext context) {
    final ActionReport actionReport = context.getActionReport();
    Properties extraProperties = actionReport.getExtraProperties();
    if (extraProperties == null) {
        extraProperties = new Properties();
        actionReport.setExtraProperties(extraProperties);
    }
    Config configuration = targetUtil.getConfig(target);
    final NotificationServiceConfiguration notificationServiceConfiguration = configuration.getExtensionByType(NotificationServiceConfiguration.class);
    ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    notifierConfigurationClass = (Class<C>) genericSuperclass.getActualTypeArguments()[0];
    C c = notificationServiceConfiguration.getNotifierConfigurationByType(notifierConfigurationClass);
    try {
        if (c == null) {
            ConfigSupport.apply(new SingleConfigCode<NotificationServiceConfiguration>() {

                @Override
                public Object run(final NotificationServiceConfiguration notificationServiceConfigurationProxy) throws PropertyVetoException, TransactionFailure {
                    C c = notificationServiceConfigurationProxy.createChild(notifierConfigurationClass);
                    applyValues(c);
                    notificationServiceConfigurationProxy.getNotifierConfigurationList().add(c);
                    actionReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
                    ParameterMap params = new ParameterMap();
                    params.add("enabled", Boolean.TRUE.toString());
                    params.add("dynamic", Boolean.TRUE.toString());
                    params.add("target", target);
                    ActionReport healthCheckSubReport = actionReport.addSubActionsReport();
                    CommandRunner.CommandInvocation healthCheckCommandInvocation = commandRunner.getCommandInvocation(getHealthCheckNotifierCommandName(), healthCheckSubReport, context.getSubject());
                    healthCheckCommandInvocation.parameters(params);
                    healthCheckCommandInvocation.execute();
                    if (healthCheckSubReport.hasFailures()) {
                        logger.log(Level.SEVERE, "Error occurred while configuring notifier with command: " + getHealthCheckNotifierCommandName());
                    }
                    ActionReport requestTracingSubReport = actionReport.addSubActionsReport();
                    CommandRunner.CommandInvocation requestTracingCommandInvocation = commandRunner.getCommandInvocation(getRequestTracingNotifierCommandName(), requestTracingSubReport, context.getSubject());
                    requestTracingCommandInvocation.parameters(params);
                    requestTracingCommandInvocation.execute();
                    if (requestTracingSubReport.hasFailures()) {
                        logger.log(Level.SEVERE, "Error occurred while configuring notifier with command: " + getRequestTracingNotifierCommandName());
                    }
                    return notificationServiceConfigurationProxy;
                }
            }, notificationServiceConfiguration);
        } else {
            ConfigSupport.apply(new SingleConfigCode<C>() {

                public Object run(C cProxy) throws PropertyVetoException, TransactionFailure {
                    applyValues(cProxy);
                    actionReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
                    return cProxy;
                }
            }, c);
        }
        if (dynamic) {
            if (server.isDas()) {
                if (targetUtil.getConfig(target).isDas()) {
                    configureDynamically();
                }
            } else {
                configureDynamically();
            }
        }
    } catch (TransactionFailure ex) {
        logger.log(Level.WARNING, "Exception during command ", ex);
        actionReport.setMessage(ex.getCause().getMessage());
        actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Config(com.sun.enterprise.config.serverbeans.Config) ActionReport(org.glassfish.api.ActionReport) Properties(java.util.Properties) ParameterizedType(java.lang.reflect.ParameterizedType) PropertyVetoException(java.beans.PropertyVetoException) NotificationServiceConfiguration(fish.payara.nucleus.notification.configuration.NotificationServiceConfiguration)

Example 4 with SingleConfigCode

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

the class WebContainerImpl method bind.

private void bind(Port port, WebListener webListener, String vsId) {
    String protocol = Port.HTTP_PROTOCOL;
    final int portNumber = port.getPortNumber();
    final String defaultVS = vsId;
    final WebListener listener = webListener;
    if (webListener == null) {
        listenerName = getListenerName();
        webListener = new HttpListener();
        webListener.setId(listenerName);
        webListener.setPort(portNumber);
    } else {
        listenerName = webListener.getId();
        protocol = webListener.getProtocol();
    }
    listeners.add(webListener);
    if (protocol.equals(Port.HTTP_PROTOCOL)) {
        securityEnabled = "false";
    } else if (protocol.equals(Port.HTTPS_PROTOCOL)) {
        securityEnabled = "true";
    }
    try {
        ConfigSupport.apply(new SingleConfigCode<Protocols>() {

            public Object run(Protocols param) throws TransactionFailure {
                final Protocol protocol = param.createChild(Protocol.class);
                protocol.setName(listenerName);
                protocol.setSecurityEnabled(securityEnabled);
                param.getProtocol().add(protocol);
                final Http http = protocol.createChild(Http.class);
                http.setDefaultVirtualServer(defaultVS);
                http.setFileCache(http.createChild(FileCache.class));
                protocol.setHttp(http);
                return protocol;
            }
        }, networkConfig.getProtocols());
        ConfigSupport.apply(new ConfigCode() {

            public Object run(ConfigBeanProxy... params) throws TransactionFailure {
                NetworkListeners nls = (NetworkListeners) params[0];
                Transports transports = (Transports) params[1];
                final NetworkListener listener = nls.createChild(NetworkListener.class);
                listener.setName(listenerName);
                listener.setPort(Integer.toString(portNumber));
                listener.setProtocol(listenerName);
                listener.setThreadPool("http-thread-pool");
                if (listener.findThreadPool() == null) {
                    final ThreadPool pool = nls.createChild(ThreadPool.class);
                    pool.setName(listenerName);
                    listener.setThreadPool(listenerName);
                }
                listener.setTransport("tcp");
                if (listener.findTransport() == null) {
                    final Transport transport = transports.createChild(Transport.class);
                    transport.setName(listenerName);
                    listener.setTransport(listenerName);
                }
                nls.getNetworkListener().add(listener);
                return listener;
            }
        }, networkConfig.getNetworkListeners(), networkConfig.getTransports());
        if (webListener.getProtocol().equals("https")) {
            NetworkListener networkListener = networkConfig.getNetworkListener(listenerName);
            Protocol httpProtocol = networkListener.findHttpProtocol();
            ConfigSupport.apply(new SingleConfigCode<Protocol>() {

                public Object run(Protocol param) throws TransactionFailure {
                    Ssl newSsl = param.createChild(Ssl.class);
                    populateSslElement(newSsl, listener);
                    System.out.println("SSL " + newSsl.getKeyStore() + " " + newSsl.getKeyStorePassword() + " " + newSsl.getTrustStore() + " " + newSsl.getTrustStorePassword());
                    param.setSsl(newSsl);
                    return newSsl;
                }
            }, httpProtocol);
        }
        com.sun.enterprise.config.serverbeans.VirtualServer vs = httpService.getVirtualServerByName(config.getVirtualServerId());
        ConfigSupport.apply(new SingleConfigCode<com.sun.enterprise.config.serverbeans.VirtualServer>() {

            public Object run(com.sun.enterprise.config.serverbeans.VirtualServer avs) throws PropertyVetoException {
                avs.addNetworkListener(listenerName);
                return avs;
            }
        }, vs);
    } catch (Exception e) {
        if (listeners.contains(webListener)) {
            listeners.remove(webListener);
        }
        e.printStackTrace();
    }
}
Also used : Protocols(org.glassfish.grizzly.config.dom.Protocols) ThreadPool(org.glassfish.grizzly.config.dom.ThreadPool) Http(org.glassfish.grizzly.config.dom.Http) NetworkListeners(org.glassfish.grizzly.config.dom.NetworkListeners) HttpListener(org.glassfish.embeddable.web.HttpListener) Protocol(org.glassfish.grizzly.config.dom.Protocol) Transports(org.glassfish.grizzly.config.dom.Transports) Ssl(org.glassfish.grizzly.config.dom.Ssl) VirtualServer(org.glassfish.embeddable.web.VirtualServer) PropertyVetoException(java.beans.PropertyVetoException) ConfigException(org.glassfish.embeddable.web.ConfigException) GlassFishException(org.glassfish.embeddable.GlassFishException) PropertyVetoException(java.beans.PropertyVetoException) WebListener(org.glassfish.embeddable.web.WebListener) Transport(org.glassfish.grizzly.config.dom.Transport) org.jvnet.hk2.config(org.jvnet.hk2.config) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener)

Example 5 with SingleConfigCode

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

the class GrizzlyConfigSchemaMigrator method promoteVirtualServerProperties.

private void promoteVirtualServerProperties(HttpService service) throws TransactionFailure {
    for (VirtualServer virtualServer : service.getVirtualServer()) {
        ConfigSupport.apply(new SingleConfigCode<VirtualServer>() {

            @Override
            public Object run(VirtualServer param) throws PropertyVetoException {
                if (param.getHttpListeners() != null && !"".equals(param.getHttpListeners())) {
                    param.setNetworkListeners(param.getHttpListeners());
                }
                param.setHttpListeners(null);
                final List<Property> propertyList = new ArrayList<Property>(param.getProperty());
                final Iterator<Property> it = propertyList.iterator();
                while (it.hasNext()) {
                    final Property property = it.next();
                    if ("docroot".equals(property.getName())) {
                        param.setDocroot(property.getValue());
                        it.remove();
                    } else if ("accesslog".equals(property.getName())) {
                        param.setAccessLog(property.getValue());
                        it.remove();
                    } else if ("sso-enabled".equals(property.getName())) {
                        param.setSsoEnabled(property.getValue());
                        it.remove();
                    }
                }
                param.getProperty().clear();
                param.getProperty().addAll(propertyList);
                return null;
            }
        }, virtualServer);
    }
}
Also used : PropertyVetoException(java.beans.PropertyVetoException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) Property(org.jvnet.hk2.config.types.Property) VirtualServer(com.sun.enterprise.config.serverbeans.VirtualServer)

Aggregations

TransactionFailure (org.jvnet.hk2.config.TransactionFailure)153 PropertyVetoException (java.beans.PropertyVetoException)130 ActionReport (org.glassfish.api.ActionReport)76 Config (com.sun.enterprise.config.serverbeans.Config)47 Property (org.jvnet.hk2.config.types.Property)27 Resources (com.sun.enterprise.config.serverbeans.Resources)25 List (java.util.List)23 SingleConfigCode (org.jvnet.hk2.config.SingleConfigCode)19 ResourceStatus (org.glassfish.resourcebase.resources.api.ResourceStatus)17 CommandTarget (org.glassfish.config.support.CommandTarget)15 NetworkListener (org.glassfish.grizzly.config.dom.NetworkListener)15 Protocol (org.glassfish.grizzly.config.dom.Protocol)15 Target (org.glassfish.internal.api.Target)15 Test (org.junit.Test)15 NetworkConfig (org.glassfish.grizzly.config.dom.NetworkConfig)13 ArrayList (java.util.ArrayList)11 Protocols (org.glassfish.grizzly.config.dom.Protocols)11 Resource (com.sun.enterprise.config.serverbeans.Resource)9 SecurityService (com.sun.enterprise.config.serverbeans.SecurityService)9 Properties (java.util.Properties)9