Search in sources :

Example 1 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)

Example 2 with Dom

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

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

the class ConfigModularityUtils method getCurrentConfigBeanForDefaultValue.

public <T extends ConfigBeanProxy> T getCurrentConfigBeanForDefaultValue(ConfigBeanDefaultValue defaultValue) throws InvocationTargetException, IllegalAccessException {
    // TODO make this method target aware!
    Class parentClass = getOwningClassForLocation(defaultValue.getLocation());
    Class configBeanClass = getClassForFullName(defaultValue.getConfigBeanClassName());
    Method m = findSuitableCollectionGetter(parentClass, configBeanClass);
    if (m != null) {
        ConfigParser configParser = new ConfigParser(serviceLocator);
        // I don't use the GlassFish document here as I don't need persistence
        final DomDocument doc = new DomDocument<GlassFishConfigBean>(serviceLocator) {

            @Override
            public Dom make(final ServiceLocator serviceLocator, XMLStreamReader xmlStreamReader, GlassFishConfigBean dom, ConfigModel configModel) {
                // by default, people get the translated view.
                return new GlassFishConfigBean(serviceLocator, this, dom, configModel, xmlStreamReader);
            }
        };
        ConfigBeanProxy parent = getOwningObject(defaultValue.getLocation());
        ConfigurationPopulator populator = new ConfigurationPopulator(defaultValue.getXmlConfiguration(), doc, parent);
        populator.run(configParser);
        ConfigBeanProxy configBean = doc.getRoot().createProxy(configBeanClass);
        Collection col = (Collection) m.invoke(parent);
        return (T) getConfigBeanFromCollection(col, configBean, configBeanClass);
    }
    return null;
}
Also used : ServiceLocator(org.glassfish.hk2.api.ServiceLocator) XMLStreamReader(javax.xml.stream.XMLStreamReader) ConfigModel(org.jvnet.hk2.config.ConfigModel) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) GlassFishConfigBean(org.glassfish.config.support.GlassFishConfigBean) ConfigurationPopulator(com.sun.enterprise.config.modularity.parser.ConfigurationPopulator) ConfigParser(org.jvnet.hk2.config.ConfigParser) Collection(java.util.Collection) Method(java.lang.reflect.Method) DomDocument(org.jvnet.hk2.config.DomDocument)

Example 4 with Dom

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

the class ConfigModularityUtils method serializeConfigBean.

public String serializeConfigBean(ConfigBeanProxy configBean) {
    if (configBean == null)
        return null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLOutputFactory xmlFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter writer = null;
    IndentingXMLStreamWriter indentingXMLStreamWriter = null;
    String s = null;
    try {
        writer = xmlFactory.createXMLStreamWriter(new BufferedOutputStream(bos));
        indentingXMLStreamWriter = new IndentingXMLStreamWriter(writer);
        Dom configBeanDom = Dom.unwrap(configBean);
        configBeanDom.writeTo(configBeanDom.model.getTagName(), indentingXMLStreamWriter);
        indentingXMLStreamWriter.flush();
        s = bos.toString();
    } catch (XMLStreamException e) {
        if (LOG.isLoggable(Level.FINE)) {
            LOG.log(Level.FINE, "Cannot serialize the configbean: " + configBean.toString(), e);
        }
        return null;
    } finally {
        try {
            if (bos != null)
                bos.close();
            if (writer != null)
                writer.close();
            if (indentingXMLStreamWriter != null)
                indentingXMLStreamWriter.close();
        } catch (IOException e) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.log(Level.FINE, "Cannot serialize the configbean: " + configBean.toString(), e);
            }
        } catch (XMLStreamException e) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.log(Level.FINE, "Cannot serialize the configbean: " + configBean.toString(), e);
            }
        }
    }
    return s;
}
Also used : IndentingXMLStreamWriter(org.jvnet.hk2.config.IndentingXMLStreamWriter) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) Dom(org.jvnet.hk2.config.Dom) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) IndentingXMLStreamWriter(org.jvnet.hk2.config.IndentingXMLStreamWriter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) BufferedOutputStream(java.io.BufferedOutputStream)

Example 5 with Dom

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

the class StatusGenerator method getPlain.

@GET
@Produces({ "text/plain" })
public String getPlain() {
    // status.append("Status of Command usage\n");
    try {
        Domain entity = serviceLocator.getService(Domain.class);
        Dom dom = Dom.unwrap(entity);
        DomDocument document = dom.document;
        ConfigModel rootModel = dom.document.getRoot().model;
        ResourcesGenerator resourcesGenerator = new NOOPResourcesGenerator(serviceLocator);
        resourcesGenerator.generateSingle(rootModel, document);
        resourcesGenerator.endGeneration();
    } catch (Exception ex) {
        RestLogging.restLogger.log(Level.SEVERE, null, ex);
    // retVal = "Exception encountered during generation process: " + ex.toString() + "\nPlease look at server.log for more information.";
    }
    status.append(DASHED_LINE);
    status.append("All Commands used in REST Admin:\n");
    for (String ss : commandsUsed) {
        status.append(ss).append("\n");
    }
    listOfCommands();
    for (String ss : commandsUsed) {
        allCommands.remove(ss);
    }
    status.append(DASHED_LINE);
    status.append("Missing Commands not used in REST Admin:\n");
    for (String ss : allCommands) {
        if (hasTargetParam(ss)) {
            status.append(ss).append("          has a target param \n");
        } else {
            status.append(ss).append("\n");
        }
    }
    status.append(DASHED_LINE);
    status.append("REST-REDIRECT Commands defined on ConfigBeans:\n");
    for (String ss : restRedirectCommands) {
        status.append(ss).append("\n");
    }
    status.append(DASHED_LINE);
    status.append("Commands to Resources Mapping Usage in REST Admin:\n");
    for (Entry<String, String> commandToResourceEntry : commandsToResources.entrySet()) {
        if (hasTargetParam(commandToResourceEntry.getKey())) {
            status.append(commandToResourceEntry.getKey()).append("   :::target:::   ").append(commandToResourceEntry.getValue()).append("\n");
        } else {
            status.append(commandToResourceEntry.getKey()).append("      :::      ").append(commandToResourceEntry.getValue()).append("\n");
        }
    }
    status.append(DASHED_LINE);
    status.append("Resources with Delete Commands in REST Admin (not counting RESTREDIRECT:\n");
    for (Entry<String, String> resourceToDeleteEntry : resourcesToDeleteCommands.entrySet()) {
        status.append(resourceToDeleteEntry.getKey()).append("      :::      ").append(resourceToDeleteEntry.getValue()).append("\n");
    }
    try (FileOutputStream f = new FileOutputStream(System.getProperty("user.home") + "/GlassFishI18NData.properties")) {
        propsI18N.store(f, "");
    } catch (Exception ex) {
        RestLogging.restLogger.log(Level.SEVERE, null, ex);
    }
    return status.toString();
}
Also used : Dom(org.jvnet.hk2.config.Dom) ConfigModel(org.jvnet.hk2.config.ConfigModel) FileOutputStream(java.io.FileOutputStream) ResourcesGenerator(org.glassfish.admin.rest.generator.ResourcesGenerator) Domain(com.sun.enterprise.config.serverbeans.Domain) MultiException(org.glassfish.hk2.api.MultiException) DomDocument(org.jvnet.hk2.config.DomDocument) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

Dom (org.jvnet.hk2.config.Dom)42 ConfigModel (org.jvnet.hk2.config.ConfigModel)14 Domain (com.sun.enterprise.config.serverbeans.Domain)11 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)11 ArrayList (java.util.ArrayList)9 DomDocument (org.jvnet.hk2.config.DomDocument)9 ServiceLocator (org.glassfish.hk2.api.ServiceLocator)8 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)8 HashMap (java.util.HashMap)7 Map (java.util.Map)7 PropertyVetoException (java.beans.PropertyVetoException)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 IOException (java.io.IOException)3 ResourcesGenerator (org.glassfish.admin.rest.generator.ResourcesGenerator)3 ConfigBean (org.jvnet.hk2.config.ConfigBean)3