Search in sources :

Example 71 with TransactionFailure

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

the class ConfigurationParser method parseAndSetConfigBean.

/**
 * @param <T> the ConfigBeanProxy type we are looking for
 */
public <T extends ConfigBeanProxy> void parseAndSetConfigBean(List<ConfigBeanDefaultValue> values) {
    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) {
            return new GlassFishConfigBean(serviceLocator, this, dom, configModel, xmlStreamReader);
        }
    };
    // the solution is to put the loop into the apply method...  But it would be some fine amount of work
    for (final ConfigBeanDefaultValue configBeanDefaultValue : values) {
        final ConfigBeanProxy parent = configModularityUtils.getOwningObject(configBeanDefaultValue.getLocation());
        if (parent == null)
            continue;
        ConfigurationPopulator populator = null;
        if (replaceSystemProperties)
            try {
                populator = new ConfigurationPopulator(configModularityUtils.replacePropertiesWithCurrentValue(configBeanDefaultValue.getXmlConfiguration(), configBeanDefaultValue), doc, parent);
            } catch (Exception e) {
                LOG.log(Level.SEVERE, ConfigApiLoggerInfo.CFG_EXT_ADD_FAILED, e);
            }
        else {
            // Check that parent is not null!
            populator = new ConfigurationPopulator(configBeanDefaultValue.getXmlConfiguration(), doc, parent);
        }
        populator.run(configParser);
        synchronized (configModularityUtils) {
            boolean oldValue = configModularityUtils.isIgnorePersisting();
            try {
                Class configBeanClass = configModularityUtils.getClassForFullName(configBeanDefaultValue.getConfigBeanClassName());
                final ConfigBeanProxy pr = doc.getRoot().createProxy(configBeanClass);
                configModularityUtils.setIgnorePersisting(true);
                ConfigSupport.apply(new SingleConfigCode<ConfigBeanProxy>() {

                    public Object run(ConfigBeanProxy param) throws PropertyVetoException, TransactionFailure {
                        configModularityUtils.setConfigBean(pr, configBeanDefaultValue, param);
                        return param;
                    }
                }, parent);
            } catch (TransactionFailure e) {
                LOG.log(Level.SEVERE, ConfigApiLoggerInfo.CFG_EXT_ADD_FAILED, e);
            } finally {
                configModularityUtils.setIgnorePersisting(oldValue);
            }
        }
    }
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) XMLStreamReader(javax.xml.stream.XMLStreamReader) ConfigParser(org.jvnet.hk2.config.ConfigParser) PropertyVetoException(java.beans.PropertyVetoException) DomDocument(org.jvnet.hk2.config.DomDocument) ServiceLocator(org.glassfish.hk2.api.ServiceLocator) PropertyVetoException(java.beans.PropertyVetoException) ConfigModel(org.jvnet.hk2.config.ConfigModel) ConfigBeanDefaultValue(com.sun.enterprise.config.modularity.customization.ConfigBeanDefaultValue) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) GlassFishConfigBean(org.glassfish.config.support.GlassFishConfigBean)

Example 72 with TransactionFailure

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

the class CopyConfig method copyConfig.

public Config copyConfig(Configs configs, Config config, String destConfigName, Logger logger) throws PropertyVetoException, TransactionFailure {
    final Config destCopy = (Config) config.deepCopy(configs);
    if (systemproperties != null) {
        final Properties properties = GenericCrudCommand.convertStringToProperties(systemproperties, ':');
        for (final Object key : properties.keySet()) {
            final String propName = (String) key;
            // cannot update a system property so remove it first
            List<SystemProperty> sysprops = destCopy.getSystemProperty();
            for (SystemProperty sysprop : sysprops) {
                if (propName.equals(sysprop.getName())) {
                    sysprops.remove(sysprop);
                    break;
                }
            }
            SystemProperty newSysProp = destCopy.createChild(SystemProperty.class);
            newSysProp.setName(propName);
            newSysProp.setValue(properties.getProperty(propName));
            destCopy.getSystemProperty().add(newSysProp);
        }
    }
    final String configName = destConfigName;
    destCopy.setName(configName);
    configs.getConfig().add(destCopy);
    copyOfConfig = destCopy;
    String srcConfig = "";
    srcConfig = config.getName();
    File configConfigDir = new File(env.getConfigDirPath(), configName);
    for (Config c : configs.getConfig()) {
        File existingConfigConfigDir = new File(env.getConfigDirPath(), c.getName());
        if (!c.getName().equals(configName) && configConfigDir.equals(existingConfigConfigDir)) {
            throw new TransactionFailure(localStrings.getLocalString("config.duplicate.dir", "Config {0} is trying to use the same directory as config {1}", configName, c.getName()));
        }
    }
    try {
        if (!(new File(configConfigDir, "docroot").mkdirs() && new File(configConfigDir, "lib/ext").mkdirs())) {
            throw new IOException(localStrings.getLocalString("config.mkdirs", "error creating config specific directories"));
        }
        String srcConfigLoggingFile = env.getInstanceRoot().getAbsolutePath() + File.separator + "config" + File.separator + srcConfig + File.separator + ServerEnvironmentImpl.kLoggingPropertiesFileName;
        File src = new File(srcConfigLoggingFile);
        if (!src.exists()) {
            src = new File(env.getConfigDirPath(), ServerEnvironmentImpl.kLoggingPropertiesFileName);
        }
        File dest = new File(configConfigDir, ServerEnvironmentImpl.kLoggingPropertiesFileName);
        FileUtils.copy(src, dest);
    } catch (Exception e) {
        logger.log(Level.WARNING, ConfigApiLoggerInfo.copyConfigError, e.getLocalizedMessage());
    }
    return destCopy;
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) IOException(java.io.IOException) Properties(java.util.Properties) File(java.io.File) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException)

Example 73 with TransactionFailure

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

the class PortUtils method checkInternalConsistency.

/**
 * Make sure all ports that are specified by the user make sense.
 * @param server The new Server element
 * @return null if all went OK.  Otherwise return a String with the error message.
 */
static void checkInternalConsistency(Server server) throws TransactionFailure {
    // Make sure all the system properties for ports have different numbers.
    List<SystemProperty> sysProps = server.getSystemProperty();
    Set<Integer> ports = new TreeSet<Integer>();
    for (SystemProperty sp : sysProps) {
        String name = sp.getName();
        if (PORTSLIST.contains(name)) {
            String val = sp.getValue();
            try {
                boolean wasAdded = ports.add(Integer.parseInt(val));
                if (// TODO unit test
                !wasAdded)
                    throw new TransactionFailure(Strings.get("PortUtils.duplicate_port", val, server.getName()));
            } catch (TransactionFailure tf) {
                // don't re-wrap the same Exception type!
                throw tf;
            } catch (Exception e) {
                // TODO unit test
                throw new TransactionFailure(Strings.get("PortUtils.non_int_port", val, server.getName()));
            }
        }
    }
    checkForLegalPorts(ports, server.getName());
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) SystemProperty(com.sun.enterprise.config.serverbeans.SystemProperty)

Example 74 with TransactionFailure

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

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

Aggregations

TransactionFailure (org.jvnet.hk2.config.TransactionFailure)191 PropertyVetoException (java.beans.PropertyVetoException)132 ActionReport (org.glassfish.api.ActionReport)86 Property (org.jvnet.hk2.config.types.Property)61 Config (com.sun.enterprise.config.serverbeans.Config)52 HashMap (java.util.HashMap)30 Test (org.junit.Test)27 Resources (com.sun.enterprise.config.serverbeans.Resources)25 Map (java.util.Map)25 List (java.util.List)21 CommandTarget (org.glassfish.config.support.CommandTarget)21 NetworkListener (org.glassfish.grizzly.config.dom.NetworkListener)21 Target (org.glassfish.internal.api.Target)21 NetworkConfig (org.glassfish.grizzly.config.dom.NetworkConfig)20 Protocol (org.glassfish.grizzly.config.dom.Protocol)20 ConfigBean (org.jvnet.hk2.config.ConfigBean)20 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)18 ResourceStatus (org.glassfish.resourcebase.resources.api.ResourceStatus)17 SingleConfigCode (org.jvnet.hk2.config.SingleConfigCode)16 ParameterMap (org.glassfish.api.admin.ParameterMap)14