Search in sources :

Example 6 with Attribute

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

the class MonitoredAttributeBagResource method setMonitoredAttributes.

/**
 * Sets the monitored attribute list to the specified list.
 *
 * @param attributes the intended list of attributes.
 * @throws TransactionFailure if an error occurs in removing or adding
 * attributes.
 */
public void setMonitoredAttributes(List<Map<String, String>> attributes) throws TransactionFailure {
    TranslatedConfigView.doSubstitution.set(false);
    List<Map<String, String>> existingAttributes = getMonitoredAttributes();
    // Get a list of attributes that need adding
    List<Map<String, String>> attributesToAdd = new ArrayList<>(attributes);
    // Start with the list of specified attributes, and remove any that are also in the existing list
    Iterator<Map<String, String>> iterator = attributesToAdd.iterator();
    while (iterator.hasNext()) {
        Map<String, String> attributeToAdd = iterator.next();
        for (Map<String, String> existingAttribute : existingAttributes) {
            if (attributesAreEqual(existingAttribute, attributeToAdd)) {
                iterator.remove();
            }
        }
    }
    // Get a list of attributes that need deleting
    List<Map<String, String>> attributesToDelete = new ArrayList<>(existingAttributes);
    // Start with the list of existing attributes, and remove any that aren't also in the specified list
    iterator = attributesToDelete.iterator();
    while (iterator.hasNext()) {
        Map<String, String> attributeToDelete = iterator.next();
        boolean specified = false;
        for (Map<String, String> specifiedAttribute : attributes) {
            if (attributesAreEqual(specifiedAttribute, attributeToDelete)) {
                specified = true;
            }
        }
        if (specified) {
            iterator.remove();
        }
    }
    try {
        // Add all required attributes
        for (Map<String, String> attribute : attributesToAdd) {
            Map<String, String> parameters = new HashMap<>();
            parameters.put("addattribute", String.format("attributeName=%s objectName=%s", attribute.get("attributeName"), attribute.get("objectName")));
            RestActionReporter reporter = ResourceUtil.runCommand("set-monitoring-configuration", parameters, getSubject());
            if (reporter.isFailure()) {
                throw new TransactionFailure(reporter.getMessage());
            }
        }
        // Delete all unrequired attributes
        for (Map<String, String> attribute : attributesToDelete) {
            Map<String, String> parameters = new HashMap<>();
            parameters.put("delattribute", String.format("attributeName=%s objectName=%s", attribute.get("attributeName"), attribute.get("objectName")));
            RestActionReporter reporter = ResourceUtil.runCommand("set-monitoring-configuration", parameters, getSubject());
            if (reporter.isFailure()) {
                throw new TransactionFailure(reporter.getMessage());
            }
        }
    } finally {
        TranslatedConfigView.doSubstitution.set(true);
    }
    synchronized (parent) {
        entity = parent.nodeElements("monitored-attributes");
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) RestActionReporter(org.glassfish.admin.rest.utils.xml.RestActionReporter)

Example 7 with Attribute

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

the class MonitoredAttributeBagResource method getMonitoredAttributes.

/**
 * Gets all of the monitored attributes in the entity.
 *
 * @return a list of the monitored attributes
 */
public List<Map<String, String>> getMonitoredAttributes() {
    List<Map<String, String>> attributes = new ArrayList<>();
    for (Dom child : entity) {
        Map<String, String> entry = new HashMap<>();
        entry.put("attributeName", child.attribute("attribute-name"));
        entry.put("objectName", child.attribute("object-name"));
        String description = child.attribute("description");
        if (description != null) {
            entry.put("description", description);
        }
        attributes.add(entry);
    }
    return attributes;
}
Also used : Dom(org.jvnet.hk2.config.Dom)

Example 8 with Attribute

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

the class MonitoredAttributeBagResource method put.

/**
 * Creates new monitored-attributes. This method deletes all of the existing
 * monitored-attributes.
 *
 * @param attributes the list of monitored-attributes to be created.
 * @return a list of the monitored-attributes after the transaction.
 */
@PUT
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.TEXT_HTML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public ActionReportResult put(List<Map<String, String>> attributes) {
    RestActionReporter ar = new RestActionReporter();
    ar.setActionExitCode(ActionReport.ExitCode.SUCCESS);
    ar.setActionDescription("monitored-attribute");
    try {
        setMonitoredAttributes(attributes);
        List monitoredAttributes = getMonitoredAttributes();
        Properties extraProperties = new Properties();
        extraProperties.put("monitoredAttributes", monitoredAttributes);
        ar.setExtraProperties(extraProperties);
    } catch (TransactionFailure ex) {
        ar.setActionExitCode(ActionReport.ExitCode.FAILURE);
        ar.setMessage(ex.getMessage());
    }
    return new ActionReportResult(tagName, ar, new OptionsResult(Util.getResourceName(uriInfo)));
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) ActionReportResult(org.glassfish.admin.rest.results.ActionReportResult) RestActionReporter(org.glassfish.admin.rest.utils.xml.RestActionReporter) OptionsResult(org.glassfish.admin.rest.results.OptionsResult) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) PUT(javax.ws.rs.PUT)

Example 9 with Attribute

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

the class DisableCommand method execute.

/**
 * Entry point from the framework into the command execution
 * @param context context for the command.
 */
public void execute(AdminCommandContext context) {
    if (origin == Origin.unload && command == Command.disable) {
        // we should only validate this for the disable command
        deployment.validateSpecifiedTarget(target);
    }
    InterceptorNotifier notifier = new InterceptorNotifier(habitat, null);
    final DeployCommandSupplementalInfo suppInfo = new DeployCommandSupplementalInfo();
    suppInfo.setAccessChecks(accessChecks);
    report.setResultType(DeployCommandSupplementalInfo.class, suppInfo);
    if (env.isDas() && DeploymentUtils.isDomainTarget(target)) {
        // for each distinct enabled version in all known targets
        Iterator it = enabledVersionsInTargets.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            appName = (String) entry.getKey();
            List<String> targets = new ArrayList<String>((Set<String>) entry.getValue());
            // replicate command to all referenced targets
            try {
                ParameterMapExtractor extractor = new ParameterMapExtractor(this);
                ParameterMap paramMap = extractor.extract(Collections.EMPTY_LIST);
                paramMap.set("DEFAULT", appName);
                notifier.ensureBeforeReported(ExtendedDeploymentContext.Phase.REPLICATION);
                ClusterOperationUtil.replicateCommand("disable", FailurePolicy.Error, FailurePolicy.Warn, FailurePolicy.Ignore, targets, context, paramMap, habitat);
            } catch (Exception e) {
                report.failure(logger, e.getMessage());
                return;
            }
        }
    } else if (isVersionExpressionWithWildcard) {
        try {
            if (matchedVersions == Collections.EMPTY_LIST) {
                // no version matched by the expression
                // nothing to do : success
                report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
                return;
            }
            String enabledVersion = versioningService.getEnabledVersion(appName, target);
            if (matchedVersions.contains(enabledVersion)) {
                // the enabled version is matched by the expression
                appName = enabledVersion;
            } else {
                // the enabled version is not matched by the expression
                // nothing to do : success
                report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
                return;
            }
        } catch (VersioningException e) {
            report.failure(logger, e.getMessage());
            return;
        }
    }
    if (target == null) {
        target = deployment.getDefaultTarget(appName, origin, _classicstyle);
    }
    if (env.isDas() || !isundeploy) {
        // on instance side for partial deployment case
        if (!deployment.isRegistered(appName)) {
            if (env.isDas()) {
                // let's only do this check for DAS to be more
                // tolerable of the partial deployment case
                report.setMessage(localStrings.getLocalString("application.notreg", "Application {0} not registered", appName));
                report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            }
            return;
        }
        if (!DeploymentUtils.isDomainTarget(target)) {
            ApplicationRef ref = domain.getApplicationRefInTarget(appName, target);
            if (ref == null) {
                if (env.isDas()) {
                    // let's only do this check for DAS to be more
                    // tolerable of the partial deployment case
                    report.setMessage(localStrings.getLocalString("ref.not.referenced.target", "Application {0} is not referenced by target {1}", appName, target));
                    report.setActionExitCode(ActionReport.ExitCode.FAILURE);
                }
                return;
            }
        }
    }
    /*
         * If the target is a cluster instance, the DAS will broadcast the command
         * to all instances in the cluster so they can all update their configs.
         */
    if (env.isDas()) {
        try {
            notifier.ensureBeforeReported(ExtendedDeploymentContext.Phase.REPLICATION);
            DeploymentCommandUtils.replicateEnableDisableToContainingCluster("disable", domain, target, appName, habitat, context, this);
        } catch (Exception e) {
            report.failure(logger, e.getMessage());
            return;
        }
    }
    try {
        Application app = applications.getApplication(appName);
        this.name = appName;
        // SHOULD CHECK THAT WE ARE THE CORRECT TARGET BEFORE DISABLING
        String serverName = server.getName();
        if (serverName.equals(target) || (server.getCluster() != null && server.getCluster().getName().equals(target))) {
            // wait until all applications are loaded. Otherwise we get "Application not registered"
            startupProvider.get();
            ApplicationInfo appInfo = deployment.get(appName);
            final DeploymentContext basicDC = deployment.disable(this, app, appInfo, report, logger);
            suppInfo.setDeploymentContext((ExtendedDeploymentContext) basicDC);
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error during disabling: ", e);
        if (env.isDas() || !isundeploy) {
            // we should let undeployment go through
            // on instance side for partial deployment case
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            report.setMessage(e.getMessage());
        }
    }
    if (enabledVersionsToDisable == Collections.EMPTY_SET) {
        enabledVersionsToDisable = new HashSet<String>();
        enabledVersionsToDisable.add(appName);
    }
    // iterating all the distinct enabled versions in all targets
    Iterator it = enabledVersionsToDisable.iterator();
    while (it.hasNext()) {
        appName = (String) it.next();
        if (!isundeploy && !report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            try {
                deployment.updateAppEnabledAttributeInDomainXML(appName, target, false);
            } catch (TransactionFailure e) {
                logger.warning("failed to set enable attribute for " + appName);
            }
        }
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) ArrayList(java.util.ArrayList) ApplicationInfo(org.glassfish.internal.data.ApplicationInfo) ParameterMap(org.glassfish.api.admin.ParameterMap) VersioningException(org.glassfish.deployment.versioning.VersioningException) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) ParameterMapExtractor(org.glassfish.common.util.admin.ParameterMapExtractor) Iterator(java.util.Iterator) VersioningException(org.glassfish.deployment.versioning.VersioningException) Map(java.util.Map) ParameterMap(org.glassfish.api.admin.ParameterMap) HashMap(java.util.HashMap)

Example 10 with Attribute

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

the class EnableCommand method execute.

/**
 * Entry point from the framework into the command execution
 * @param context context for the command.
 */
public void execute(AdminCommandContext context) {
    deployment.validateSpecifiedTarget(target);
    InterceptorNotifier notifier = new InterceptorNotifier(habitat, null);
    DeployCommandSupplementalInfo suppInfo = new DeployCommandSupplementalInfo();
    suppInfo.setDeploymentContext(notifier.dc());
    suppInfo.setAccessChecks(accessChecks);
    report.setResultType(DeployCommandSupplementalInfo.class, suppInfo);
    if (!deployment.isRegistered(name())) {
        report.setMessage(localStrings.getLocalString("application.notreg", "Application {0} not registered", name()));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    if (!DeploymentUtils.isDomainTarget(target)) {
        ApplicationRef applicationRef = domain.getApplicationRefInTarget(name(), target);
        if (applicationRef == null) {
            report.setMessage(localStrings.getLocalString("ref.not.referenced.target", "Application {0} is not referenced by target {1}", name(), target));
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    // return if the application is already in enabled state
    if (domain.isAppEnabledInTarget(name(), target)) {
        logger.fine("The application is already enabled");
        return;
    }
    if (env.isDas()) {
        // try to disable the enabled version, if exist
        try {
            versioningService.handleDisable(name(), target, report, context.getSubject());
        } catch (VersioningSyntaxException e) {
            report.failure(logger, e.getMessage());
            return;
        }
        if (DeploymentUtils.isDomainTarget(target)) {
            List<String> targets = domain.getAllReferencedTargetsForApplication(name());
            // replicate command to all referenced targets
            try {
                ParameterMapExtractor extractor = new ParameterMapExtractor(this);
                ParameterMap paramMap = extractor.extract(Collections.EMPTY_LIST);
                paramMap.set("DEFAULT", name());
                notifier.ensureBeforeReported(Phase.REPLICATION);
                ClusterOperationUtil.replicateCommand("enable", FailurePolicy.Error, FailurePolicy.Warn, FailurePolicy.Ignore, targets, context, paramMap, habitat);
            } catch (Exception e) {
                report.failure(logger, e.getMessage());
                return;
            }
        }
        try {
            notifier.ensureBeforeReported(Phase.REPLICATION);
            DeploymentCommandUtils.replicateEnableDisableToContainingCluster("enable", domain, target, name(), habitat, context, this);
        } catch (Exception e) {
            report.failure(logger, e.getMessage());
            return;
        }
    }
    try {
        Application app = applications.getApplication(name());
        ApplicationRef appRef = domain.getApplicationRefInServer(server.getName(), name());
        // application is enabled.
        try {
            deployment.updateAppEnabledAttributeInDomainXML(name(), target, true);
        } catch (TransactionFailure e) {
            logger.log(Level.WARNING, "failed to set enable attribute for " + name(), e);
        }
        DeploymentContext dc = deployment.enable(target, app, appRef, report, logger);
        suppInfo.setDeploymentContext((ExtendedDeploymentContext) dc);
        if (report.getActionExitCode().equals(ActionReport.ExitCode.FAILURE)) {
            // update the domain.xml
            try {
                deployment.updateAppEnabledAttributeInDomainXML(name(), target, false);
            } catch (TransactionFailure e) {
                logger.log(Level.WARNING, "failed to set enable attribute for " + name(), e);
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error during enabling: ", e);
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setMessage(e.getMessage());
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) DeploymentContext(org.glassfish.api.deployment.DeploymentContext) ExtendedDeploymentContext(org.glassfish.internal.deployment.ExtendedDeploymentContext) ParameterMapExtractor(org.glassfish.common.util.admin.ParameterMapExtractor) ParameterMap(org.glassfish.api.admin.ParameterMap) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException) VersioningSyntaxException(org.glassfish.deployment.versioning.VersioningSyntaxException)

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