Search in sources :

Example 31 with Dom

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

the class SetExampleServiceMessage method execute.

@Override
public void execute(AdminCommandContext context) {
    // obtain the correct configuration
    Config configVal = targetUtil.getConfig(target);
    ExampleServiceConfiguration serviceConfig = configVal.getExtensionByType(ExampleServiceConfiguration.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<ExampleServiceConfiguration>() {

                @Override
                public Object run(ExampleServiceConfiguration config) {
                    config.setMessage(message);
                    return null;
                }
            }, serviceConfig);
        } catch (TransactionFailure ex) {
            // set failure
            context.getActionReport().failure(Logger.getLogger(SetExampleServiceMessage.class.getName()), "Failed to update message", ex);
        }
    }
    // was targetted explicitly via the following code
    if (server.isDas()) {
        // you would need to do this if you now want to manipulate the service based on the command parameters
        if (targetUtil.getConfig(target).isDas()) {
            // this command was also targetted at the DAS
            service.doSomethingDirectly("Set message command was targetted at the DAS");
        // as below you can now directly manipulate the service as needed
        }
    } else {
        // if you are not the DAS then impoicitly this command was targeted to this instance
        service.doSomethingDirectly("Set config command targeted at the instance");
    // you can now directly manipulate the service remember though
    // if it is a config listener it has already been notified of the config change
    // however if it is not a config listener you can manipulate the service now
    }
}
Also used : ExampleServiceConfiguration(fish.payara.service.example.config.ExampleServiceConfiguration) TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Config(com.sun.enterprise.config.serverbeans.Config)

Example 32 with Dom

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

the class WriteableView method commit.

/**
 * Commit this Transaction.
 *
 * @param t the transaction commiting.
 * @throws TransactionFailure
 *          if the transaction commit failed
 */
public synchronized List<PropertyChangeEvent> commit(Transaction t) throws TransactionFailure {
    if (currentTx == t) {
        currentTx = null;
    }
    // a key attribute must be non-null and have length >= 1
    final ConfigBean master = getMasterView();
    final String keyStr = master.model.key;
    if (keyStr != null) {
        final String key = stripMarkers(keyStr);
        final String value = getPropertyValue(key);
        if (value == null) {
            throw new TransactionFailure("Key value cannot be null: " + key);
        }
        if (value.length() == 0) {
            throw new TransactionFailure("Key value cannot be empty string: " + key);
        }
    }
    try {
        List<PropertyChangeEvent> appliedChanges = new ArrayList<PropertyChangeEvent>();
        for (PropertyChangeEvent event : changedAttributes.values()) {
            ConfigModel.Property property = bean.model.findIgnoreCase(event.getPropertyName());
            ConfigBeanInterceptor interceptor = bean.getOptionalFeature(ConfigBeanInterceptor.class);
            try {
                if (interceptor != null) {
                    interceptor.beforeChange(event);
                }
            } catch (PropertyVetoException e) {
                throw new TransactionFailure(e.getMessage(), e);
            }
            property.set(bean, event.getNewValue());
            if (interceptor != null) {
                interceptor.afterChange(event, System.currentTimeMillis());
            }
            appliedChanges.add(event);
        }
        for (ProtectedList entry : changedCollections.values()) {
            List<Object> originalList = entry.readOnly;
            for (PropertyChangeEvent event : entry.changeEvents) {
                if (event.getOldValue() == null) {
                    originalList.add(event.getNewValue());
                } else {
                    final Object toBeRemovedObj = event.getOldValue();
                    if (toBeRemovedObj instanceof ConfigBeanProxy) {
                        final Dom toBeRemoved = Dom.unwrap((ConfigBeanProxy) toBeRemovedObj);
                        for (int index = 0; index < originalList.size(); index++) {
                            Object element = originalList.get(index);
                            Dom dom = Dom.unwrap((ConfigBeanProxy) element);
                            if (dom == toBeRemoved) {
                                Object newValue = event.getNewValue();
                                if (newValue == null) {
                                    originalList.remove(index);
                                } else {
                                    originalList.set(index, newValue);
                                }
                            }
                        }
                    } else if (toBeRemovedObj instanceof String) {
                        final String toBeRemoved = (String) toBeRemovedObj;
                        for (int index = 0; index < originalList.size(); index++) {
                            final String item = (String) originalList.get(index);
                            if (item.equals(toBeRemoved)) {
                                originalList.remove(index);
                            }
                        }
                    } else {
                        throw new IllegalArgumentException();
                    }
                }
                appliedChanges.add(event);
            }
        }
        changedAttributes.clear();
        changedCollections.clear();
        return appliedChanges;
    } catch (TransactionFailure e) {
        throw e;
    } catch (Exception e) {
        throw new TransactionFailure(e.getMessage(), e);
    } finally {
        bean.getLock().unlock();
    }
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) PropertyVetoException(java.beans.PropertyVetoException) PropertyVetoException(java.beans.PropertyVetoException) Property(org.jvnet.hk2.config.ConfigModel.Property)

Example 33 with Dom

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

the class ConfigTest method testDomTxReadOnlyAttributes.

// @Test
public void testDomTxReadOnlyAttributes() {
    SimpleConnector sc = habitat.getService(SimpleConnector.class);
    final EjbContainerAvailability ejb = sc.getEjbContainerAvailability();
    Dom ejbDom = Dom.unwrap(ejb);
    assert (ejbDom.getHabitat() != null);
    String origAVEnabled = ejb.getAvailabilityEnabled();
    final String origSFSBHaPersistenceType = ejb.getSfsbHaPersistenceType();
    try {
        ConfigSupport.apply(new SingleConfigCode<EjbContainerAvailability>() {

            @Override
            public Object run(EjbContainerAvailability param) throws PropertyVetoException, TransactionFailure {
                param.setSfsbHaPersistenceType("99999.999");
                param.setSfsbCheckpointEnabled("**MUST BE**");
                assert (origSFSBHaPersistenceType.equals(ejb.getSfsbHaPersistenceType()));
                assert (!ejb.getSfsbHaPersistenceType().equals(param.getSfsbHaPersistenceType()));
                return null;
            }
        }, ejb);
        // printEjb("AFTER CHANGES", ejb);
        assert (ejb.getSfsbHaPersistenceType().equals("99999.999") && ejb.getSfsbCheckpointEnabled().equals("**MUST BE**") && ejb.getAvailabilityEnabled().equals(origAVEnabled));
    } catch (Exception e) {
        e.printStackTrace();
        assert (false);
    }
}
Also used : PropertyVetoException(java.beans.PropertyVetoException) TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Dom(org.jvnet.hk2.config.Dom) PropertyVetoException(java.beans.PropertyVetoException)

Example 34 with Dom

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

the class SecureAdminClientManager method prepareDomain.

private Domain prepareDomain(final String serverName, final String nodeDir, final String node, final File nodeDirRoot) {
    /*
         * At least one of serverName, nodeDir, or node must be non-null.
         * Otherwise we'll have no way of figuring out which domain.xml to
         * look in to see if we should use client authentication.  This will
         * often be the case, for instance, if create-local-instance is
         * run directly (not from another command).  In such cases, if
         * secure admin is enabled the user should provide --user and
         * --passwordfile on the command line to authenticate to the DAS.
         */
    if (serverName == null && nodeDir == null && node == null) {
        return null;
    }
    final ServerDirsSelector selector;
    try {
        final String nodeDirToUse = (nodeDir != null ? nodeDir : nodeDirRoot.getAbsolutePath());
        selector = ServerDirsSelector.getInstance(null, serverName, nodeDirToUse, node);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    /*
         * If the caller did not pass any of the values we can use to locate
         * the domain.xml, then we cannot run in client-cert mode.
         */
    final ServerDirs dirs = selector.dirs();
    if (dirs == null) {
        return null;
    }
    final File domainXMLFile = dirs.getDomainXml();
    if (!domainXMLFile.exists()) {
        return null;
    }
    try {
        ServiceLocator habitat = Globals.getStaticHabitat();
        ConfigParser parser = new ConfigParser(habitat);
        URL domainURL = domainXMLFile.toURI().toURL();
        DomDocument doc = parser.parse(domainURL);
        Dom domDomain = doc.getRoot();
        Domain d = domDomain.createProxy(Domain.class);
        return d;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : ServiceLocator(org.glassfish.hk2.api.ServiceLocator) Dom(org.jvnet.hk2.config.Dom) ConfigParser(org.jvnet.hk2.config.ConfigParser) ServerDirs(com.sun.enterprise.util.io.ServerDirs) Domain(com.sun.enterprise.config.serverbeans.Domain) File(java.io.File) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) URL(java.net.URL) DomDocument(org.jvnet.hk2.config.DomDocument)

Example 35 with Dom

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

the class DomainXmlVerifier method checkDuplicate.

private void checkDuplicate(Collection<? extends Dom> beans) {
    if (beans == null || beans.size() <= 1) {
        return;
    }
    WeakHashMap keyBeanMap = new WeakHashMap();
    ArrayList<String> keys = new ArrayList<String>(beans.size());
    for (Dom b : beans) {
        String key = b.getKey();
        keyBeanMap.put(key, b);
        keys.add(key);
    }
    WeakHashMap<String, Class<ConfigBeanProxy>> errorKeyBeanMap = new WeakHashMap<String, Class<ConfigBeanProxy>>();
    String[] strKeys = keys.toArray(new String[beans.size()]);
    for (int i = 0; i < strKeys.length; i++) {
        boolean foundDuplicate = false;
        for (int j = i + 1; j < strKeys.length; j++) {
            // we have a duplicate. So output that error
            if ((strKeys[i].equals(strKeys[j]))) {
                foundDuplicate = true;
                errorKeyBeanMap.put(strKeys[i], ((Dom) keyBeanMap.get(strKeys[i])).getProxyType());
                error = true;
                break;
            }
        }
    }
    for (Map.Entry e : errorKeyBeanMap.entrySet()) {
        Result result = new Result(strings.get("VerifyDupKey", e.getKey(), e.getValue()));
        output(result);
    }
}
Also used : Dom(org.jvnet.hk2.config.Dom) ArrayList(java.util.ArrayList) Result(com.sun.enterprise.util.Result) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap) WeakHashMap(java.util.WeakHashMap)

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