Search in sources :

Example 1 with ConfigBean

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

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

the class TemplateRestResource method doDelete.

protected ExitCode doDelete(HashMap<String, String> data) {
    if (data == null) {
        data = new HashMap<String, String>();
    }
    if (entity == null) {
        // wrong resource
        // return Response.status(404).entity(ResourceUtil.getActionReportResult(ActionReport.ExitCode.FAILURE, errorMessage, requestHeaders, uriInfo)).build();
        throwError(Status.NOT_FOUND, localStrings.getLocalString("rest.resource.erromessage.noentity", "Resource not found."));
    }
    if (getDeleteCommand() == null) {
        String message = localStrings.getLocalString("rest.resource.delete.forbidden", "DELETE on \"{0}\" is forbidden.", new Object[] { uriInfo.getAbsolutePath() });
        throwError(Status.FORBIDDEN, message);
    }
    if (getDeleteCommand().equals("GENERIC-DELETE")) {
        try {
            ConfigBean p = (ConfigBean) parent;
            if (parent == null) {
                p = (ConfigBean) entity.parent();
            }
            ConfigSupport.deleteChild(p, (ConfigBean) entity);
            return ExitCode.SUCCESS;
        } catch (TransactionFailure ex) {
            throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }
    // do the delete via the command:
    if (data.containsKey("error")) {
        throwError(Status.BAD_REQUEST, localStrings.getLocalString("rest.request.parsing.error", "Unable to parse the input entity. Please check the syntax."));
    }
    ResourceUtil.addQueryString(uriInfo.getQueryParameters(), data);
    ResourceUtil.purgeEmptyEntries(data);
    ResourceUtil.adjustParameters(data);
    if (data.get("DEFAULT") == null) {
        addDefaultParameter(data);
    } else {
        String resourceName = getResourceName(uriInfo.getAbsolutePath().getPath(), "/");
        if (!data.get("DEFAULT").equals(resourceName)) {
            throwError(Status.FORBIDDEN, localStrings.getLocalString("rest.resource.not.deleted", "Resource not deleted. Value of \"name\" should be the name of this resource."));
        }
    }
    RestActionReporter actionReport = runCommand(getDeleteCommand(), data);
    if (actionReport != null) {
        ActionReport.ExitCode exitCode = actionReport.getActionExitCode();
        if (exitCode != ActionReport.ExitCode.FAILURE) {
            return exitCode;
        }
        throwError(Status.BAD_REQUEST, actionReport.getMessage());
    }
    throw new WebApplicationException(handleError(Status.BAD_REQUEST, localStrings.getLocalString("rest.resource.delete.forbidden", "DELETE on \"{0}\" is forbidden.", new Object[] { uriInfo.getAbsolutePath() })));
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) WebApplicationException(javax.ws.rs.WebApplicationException) RestActionReporter(org.glassfish.admin.rest.utils.xml.RestActionReporter) ConfigBean(org.jvnet.hk2.config.ConfigBean) ExitCode(org.glassfish.api.ActionReport.ExitCode) ActionReport(org.glassfish.api.ActionReport)

Example 3 with ConfigBean

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

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

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

the class ExtensionPatternInvocationImpl method handleExtension.

@Override
public ConfigBeanProxy handleExtension(Object owner, Class ownerType, Object[] params) {
    if (((Class) params[0]).getName().equals("com.sun.enterprise.config.serverbeans.SystemProperty"))
        return null;
    ConfigBeanProxy configExtension = null;
    List<ConfigBeanProxy> extensions = configModularityUtils.getExtensions(((ConfigBean) owner).createProxy(ownerType));
    for (ConfigBeanProxy extension : extensions) {
        try {
            configExtension = (ConfigBeanProxy) ((Class) params[0]).cast(extension);
            return configExtension;
        } catch (Exception e) {
        // ignore, not the right type.
        }
    }
    try {
        ConfigBeanProxy pr = ((ConfigBean) owner).createProxy(ownerType);
        ConfigBeanProxy returnValue = moduleConfigurationLoader.createConfigBeanForType((Class) params[0], pr);
        return returnValue;
    } catch (TransactionFailure transactionFailure) {
        LogHelper.log(LOG, Level.INFO, "Cannot get extension type {0} for {1}.", transactionFailure, new Object[] { owner.getClass().getName(), ownerType.getName() });
        return null;
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) ConfigBean(org.jvnet.hk2.config.ConfigBean)

Aggregations

ConfigBean (org.jvnet.hk2.config.ConfigBean)28 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)21 HashMap (java.util.HashMap)18 Map (java.util.Map)15 ConfigSupport (org.jvnet.hk2.config.ConfigSupport)12 Test (org.junit.Test)11 ConfigApiTest (com.sun.enterprise.configapi.tests.ConfigApiTest)8 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)8 Property (org.jvnet.hk2.config.types.Property)8 PropertyVetoException (java.beans.PropertyVetoException)7 Method (java.lang.reflect.Method)5 ConstraintViolationException (javax.validation.ConstraintViolationException)5 Dom (org.jvnet.hk2.config.Dom)5 Cluster (com.sun.enterprise.config.serverbeans.Cluster)4 Domain (com.sun.enterprise.config.serverbeans.Domain)4 ArrayList (java.util.ArrayList)4 List (java.util.List)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 RestActionReporter (org.glassfish.admin.rest.utils.xml.RestActionReporter)4 MultiException (org.glassfish.hk2.api.MultiException)4