Search in sources :

Example 21 with Dom

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

the class ResourceUtil method getResourceLinks.

public static Map<String, String> getResourceLinks(Dom dom, UriInfo uriInfo, boolean canShowDeprecated) {
    Map<String, String> links = new TreeMap<String, String>();
    for (String elementName : dom.model.getElementNames()) {
        // for each element
        if (elementName.equals("*")) {
            ConfigModel.Node node = (ConfigModel.Node) dom.model.getElement(elementName);
            ConfigModel childModel = node.getModel();
            List<ConfigModel> lcm = getRealChildConfigModels(childModel, dom.document);
            Collections.sort(lcm, new ConfigModelComparator());
            if (lcm != null) {
                for (ConfigModel cmodel : lcm) {
                    if ((!isDeprecated(cmodel) || canShowDeprecated)) {
                        links.put(cmodel.getTagName(), ProviderUtil.getElementLink(uriInfo, cmodel.getTagName()));
                    }
                }
            }
        } else {
            ConfigModel.Property childElement = dom.model.getElement(elementName);
            boolean deprec = false;
            if (childElement instanceof ConfigModel.Node) {
                ConfigModel.Node node = (ConfigModel.Node) childElement;
                deprec = isDeprecated(node.getModel());
            }
            for (String annotation : childElement.getAnnotations()) {
                if (annotation.equals(Deprecated.class.getName())) {
                    deprec = true;
                }
            }
            if ((!deprec || canShowDeprecated)) {
                links.put(elementName, ProviderUtil.getElementLink(uriInfo, elementName));
            }
        }
    }
    String beanName = getUnqualifiedTypeName(dom.model.targetTypeName);
    for (CommandResourceMetaData cmd : CommandResourceMetaData.getCustomResourceMapping(beanName)) {
        links.put(cmd.resourcePath, ProviderUtil.getElementLink(uriInfo, cmd.resourcePath));
    }
    return links;
}
Also used : ConfigModel(org.jvnet.hk2.config.ConfigModel) CommandResourceMetaData(org.glassfish.admin.rest.generator.CommandResourceMetaData) TreeMap(java.util.TreeMap)

Example 22 with Dom

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

the class SetConfigOrdinal method execute.

@Override
public void execute(AdminCommandContext context) {
    Config configVal = targetUtil.getConfig(target);
    MicroprofileConfigConfiguration serviceConfig = configVal.getExtensionByType(MicroprofileConfigConfiguration.class);
    if (serviceConfig != null) {
        try {
            // to perform a transaction on the domain.xml you need to use this construct
            // see https://github.com/hk2-project/hk2/blob/master/hk2-configuration/persistence/hk2-xml-dom/hk2-config/src/main/java/org/jvnet/hk2/config/ConfigSupport.java
            ConfigSupport.apply(new SingleConfigCode<MicroprofileConfigConfiguration>() {

                @Override
                public Object run(MicroprofileConfigConfiguration config) {
                    switch(source) {
                        case "domain":
                            {
                                config.setDomainOrdinality(Integer.toString(ordinal));
                                break;
                            }
                        case "config":
                            {
                                config.setConfigOrdinality(Integer.toString(ordinal));
                                break;
                            }
                        case "server":
                            {
                                config.setServerOrdinality(Integer.toString(ordinal));
                                break;
                            }
                        case "application":
                            {
                                config.setApplicationOrdinality(Integer.toString(ordinal));
                                break;
                            }
                        case "module":
                            {
                                config.setModuleOrdinality(Integer.toString(ordinal));
                                break;
                            }
                        case "cluster":
                            {
                                config.setClusterOrdinality(Integer.toString(ordinal));
                                break;
                            }
                        case "jndi":
                            {
                                config.setJNDIOrdinality(Integer.toString(ordinal));
                                break;
                            }
                        case "secrets":
                            {
                                config.setSecretDirOrdinality(Integer.toString(ordinal));
                                break;
                            }
                    }
                    return null;
                }
            }, serviceConfig);
        } catch (TransactionFailure ex) {
            // set failure
            context.getActionReport().failure(Logger.getLogger(SetConfigOrdinal.class.getName()), "Failed to update message", ex);
        }
    } else {
        context.getActionReport().failure(Logger.getLogger(SetConfigOrdinal.class.getName()), "No configuration with name " + target);
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) MicroprofileConfigConfiguration(fish.payara.nucleus.microprofile.config.spi.MicroprofileConfigConfiguration) Config(com.sun.enterprise.config.serverbeans.Config)

Example 23 with Dom

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

the class DeleteSystemProperty method execute.

/**
 * Executes the command with the command parameters passed as Properties
 * where the keys are the paramter names and the values the parameter values
 *
 * @param context information
 */
public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    Property domainProp = domain.getProperty("administrative.domain.name");
    String domainName = domainProp.getValue();
    if (!spb.containsProperty(propName)) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        String msg = localStrings.getLocalString("no.such.property", "System Property named {0} does not exist at the given target {1}", propName, target);
        report.setMessage(msg);
        return;
    }
    if (definitions(propName) == 1) {
        // implying user is deleting the "last" definition of this property
        List<String> refs = new ArrayList<String>();
        List<Dom> doms = new ArrayList<Dom>();
        if ("domain".equals(target) || target.equals(domainName)) {
            for (Server s : domain.getServers().getServer()) {
                Config config = s.getConfig();
                Cluster cluster = s.getCluster();
                if (!s.containsProperty(propName) && !config.containsProperty(propName)) {
                    if (cluster != null) {
                        if (!cluster.containsProperty(propName)) {
                            doms.add(Dom.unwrap(s));
                        }
                    } else {
                        doms.add(Dom.unwrap(s));
                    }
                }
            }
        } else {
            Config config = domain.getConfigNamed(target);
            if (config != null) {
                doms.add(Dom.unwrap(config));
                String configName = config.getName();
                for (Server s : domain.getServers().getServer()) {
                    String configRef = s.getConfigRef();
                    if (configRef.equals(configName)) {
                        if (!s.containsProperty(propName)) {
                            doms.add(Dom.unwrap(s));
                        }
                    }
                }
                for (Cluster c : domain.getClusters().getCluster()) {
                    String configRef = c.getConfigRef();
                    if (configRef.equals(configName)) {
                        if (!c.containsProperty(propName)) {
                            doms.add(Dom.unwrap(c));
                        }
                    }
                }
            } else {
                Cluster cluster = domain.getClusterNamed(target);
                if (cluster != null) {
                    doms.add(Dom.unwrap(cluster));
                    Config clusterConfig = domain.getConfigNamed(cluster.getConfigRef());
                    doms.add(Dom.unwrap(clusterConfig));
                    for (Server s : cluster.getInstances()) {
                        if (!s.containsProperty(propName)) {
                            doms.add(Dom.unwrap(s));
                        }
                    }
                } else {
                    Server server = domain.getServerNamed(target);
                    doms.add(Dom.unwrap(server));
                    doms.add(Dom.unwrap(domain.getConfigNamed(server.getConfigRef())));
                }
            }
        }
        String sysPropName = SystemPropertyConstants.getPropertyAsValue(propName);
        for (Dom d : doms) {
            listRefs(d, sysPropName, refs);
        }
        if (!refs.isEmpty()) {
            // there are some references
            String msg = localStrings.getLocalString("cant.delete.referenced.property", "System Property {0} is referenced by {1} in the configuration. Please remove the references first.", propName, Arrays.toString(refs.toArray()));
            report.setMessage(msg);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    // now we are sure that the target exits in the config, just remove the given property
    try {
        ConfigSupport.apply(new SingleConfigCode<SystemPropertyBag>() {

            public Object run(SystemPropertyBag param) throws PropertyVetoException, TransactionFailure {
                param.getSystemProperty().remove(param.getSystemProperty(propName));
                return param;
            }
        }, spb);
        report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        String msg = localStrings.getLocalString("delete.sysprops.ok", "System Property named {0} deleted from given target {1}. Make sure you check its references.", propName, target);
        report.setMessage(msg);
    } catch (TransactionFailure tf) {
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
        report.setFailureCause(tf);
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Dom(org.jvnet.hk2.config.Dom) ArrayList(java.util.ArrayList) ActionReport(org.glassfish.api.ActionReport) PropertyVetoException(java.beans.PropertyVetoException) Property(org.jvnet.hk2.config.types.Property)

Example 24 with Dom

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

the class ListCommand method execute.

public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    /* Issue 5918 Used in ManifestManager to keep output sorted */
    try {
        PropsFileActionReporter reporter = (PropsFileActionReporter) report;
        reporter.useMainChildrenAttribute(true);
    } catch (ClassCastException e) {
    // ignore, this is not a manifest output
    }
    if (monitor) {
        listMonitorElements(context);
        return;
    }
    List<Map.Entry> matchingNodesSorted = sortNodesByDottedName(matchingNodes);
    for (Map.Entry<Dom, String> node : matchingNodesSorted) {
        ActionReport.MessagePart part = report.getTopMessagePart().addChild();
        part.setChildrenType("DottedName");
        if (parentNodes[0].name.isEmpty()) {
            part.setMessage(node.getValue());
        } else {
            part.setMessage(parentNodes[0].name + "." + node.getValue());
        }
    }
}
Also used : Dom(org.jvnet.hk2.config.Dom) ActionReport(org.glassfish.api.ActionReport) PropsFileActionReporter(com.sun.enterprise.v3.common.PropsFileActionReporter) HashMap(java.util.HashMap) Map(java.util.Map)

Example 25 with Dom

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

Aggregations

Dom (org.jvnet.hk2.config.Dom)37 ConfigModel (org.jvnet.hk2.config.ConfigModel)14 Domain (com.sun.enterprise.config.serverbeans.Domain)12 DomDocument (org.jvnet.hk2.config.DomDocument)9 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)9 ServiceLocator (org.glassfish.hk2.api.ServiceLocator)8 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)8 PropertyVetoException (java.beans.PropertyVetoException)7 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)6 GET (javax.ws.rs.GET)5 Produces (javax.ws.rs.Produces)5 MultiException (org.glassfish.hk2.api.MultiException)5 Config (com.sun.enterprise.config.serverbeans.Config)4 TreeMap (java.util.TreeMap)4 ConfigParser (org.jvnet.hk2.config.ConfigParser)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ResourcesGenerator (org.glassfish.admin.rest.generator.ResourcesGenerator)3 ExampleServiceConfiguration (fish.payara.service.example.config.ExampleServiceConfiguration)2