diff options
| author | Robert Godfrey <rgodfrey@apache.org> | 2014-04-04 22:34:26 +0000 |
|---|---|---|
| committer | Robert Godfrey <rgodfrey@apache.org> | 2014-04-04 22:34:26 +0000 |
| commit | 7344c8879c319c4ca6ab57963e6147d878a4e154 (patch) | |
| tree | 230bbd0d3b9aa28b0a6298ae5156a40c996ddcdb /qpid/java/broker-core/src | |
| parent | db86d03af2ce0f704398c2a9392e91e9637154ec (diff) | |
| download | qpid-python-7344c8879c319c4ca6ab57963e6147d878a4e154.tar.gz | |
QPID-5615 : [Java Broker] Migrate broker config store to use same API as VirtualHost config store
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1584931 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'qpid/java/broker-core/src')
139 files changed, 5337 insertions, 5238 deletions
diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/Broker.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/Broker.java index 0ec6a31253..810f2d43c7 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/Broker.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/Broker.java @@ -29,21 +29,26 @@ import java.util.List; import java.util.Properties; import java.util.Set; +import javax.security.auth.Subject; + import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; + import org.apache.qpid.server.configuration.BrokerConfigurationStoreCreator; import org.apache.qpid.server.configuration.store.ManagementModeStoreHandler; +import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.logging.EventLogger; +import org.apache.qpid.server.logging.LogRecorder; import org.apache.qpid.server.logging.SystemOutMessageLogger; import org.apache.qpid.server.logging.log4j.LoggingManagementFacade; import org.apache.qpid.server.logging.messages.BrokerMessages; +import org.apache.qpid.server.model.ConfiguredObjectFactory; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.IApplicationRegistry; import org.apache.qpid.server.security.SecurityManager; - -import javax.security.auth.Subject; +import org.apache.qpid.server.store.DurableConfigurationStore; public class Broker { @@ -126,8 +131,14 @@ public class Broker configureLogging(new File(options.getLogConfigFileLocation()), options.getLogWatchFrequency()); } + LogRecorder logRecorder = new LogRecorder(); + TaskExecutor taskExecutor = new TaskExecutor(); + taskExecutor.start(); + ConfiguredObjectFactory configuredObjectFactory = new ConfiguredObjectFactory(); + SystemContext systemContext = new SystemContext(taskExecutor, configuredObjectFactory, _eventLogger, logRecorder, options); + BrokerConfigurationStoreCreator storeCreator = new BrokerConfigurationStoreCreator(); - ConfigurationEntryStore store = storeCreator.createStore(storeLocation, storeType, options.getInitialConfigurationLocation(), + DurableConfigurationStore store = storeCreator.createStore(systemContext, storeType, options.getInitialConfigurationLocation(), options.isOverwriteConfigurationStore(), options.getConfigProperties()); if (options.isManagementMode()) @@ -135,7 +146,7 @@ public class Broker store = new ManagementModeStoreHandler(store, options); } - _applicationRegistry = new ApplicationRegistry(store,_eventLogger); + _applicationRegistry = new ApplicationRegistry(store,systemContext); try { _applicationRegistry.initialise(options); diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/binding/BindingImpl.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/binding/BindingImpl.java index 9fdae72188..c5e6a01749 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/binding/BindingImpl.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/binding/BindingImpl.java @@ -30,7 +30,7 @@ import org.apache.qpid.server.model.Exchange; import org.apache.qpid.server.model.LifetimePolicy; import org.apache.qpid.server.model.Queue; import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.adapter.AbstractConfiguredObject; +import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.util.StateChangeListener; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreator.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreator.java index 2d42d60039..dd33d9ab09 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreator.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreator.java @@ -26,6 +26,7 @@ import java.util.HashMap; import java.util.Map; import org.apache.qpid.server.configuration.store.MemoryConfigurationEntryStore; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.server.plugin.ConfigurationStoreFactory; import org.apache.qpid.server.plugin.QpidServiceLoader; @@ -57,22 +58,22 @@ public class BrokerConfigurationStoreCreator /** * Create broker configuration store for a given store location, store type, initial json config location * - * @param storeLocation store location + * @param systemContext applicationContext * @param storeType store type * @param initialConfigLocation initial store location * @param overwrite whether to overwrite an existing configuration store with the initial configuration * @param configProperties a map of configuration properties the store can use to resolve configuration variables * @throws IllegalConfigurationException if store type is unknown */ - public ConfigurationEntryStore createStore(String storeLocation, String storeType, String initialConfigLocation, boolean overwrite, Map<String, String> configProperties) + public ConfigurationEntryStore createStore(SystemContext systemContext, String storeType, String initialConfigLocation, boolean overwrite, Map<String, String> configProperties) { - ConfigurationEntryStore initialStore = new MemoryConfigurationEntryStore(initialConfigLocation, null, configProperties); + ConfigurationEntryStore initialStore = new MemoryConfigurationEntryStore(systemContext, initialConfigLocation, null, configProperties); ConfigurationStoreFactory factory = _factories.get(storeType.toLowerCase()); if (factory == null) { throw new IllegalConfigurationException("Unknown store type: " + storeType); } - return factory.createStore(storeLocation, initialStore, overwrite, configProperties); + return factory.createStore(systemContext, initialStore, overwrite, configProperties); } public Collection<String> getStoreTypes() diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntry.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntry.java index 8afb1af24d..02451ad94c 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntry.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntry.java @@ -20,184 +20,26 @@ */ package org.apache.qpid.server.configuration; -import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; -public class ConfigurationEntry +public interface ConfigurationEntry { - public static final String ATTRIBUTE_NAME = "name"; + String ATTRIBUTE_NAME = "name"; - private final UUID _id; - private final String _type; - private final Map<String, Object> _attributes; - private final Set<UUID> _childrenIds; - private final ConfigurationEntryStore _store; + UUID getId(); - public ConfigurationEntry(UUID id, String type, Map<String, Object> attributes, Set<UUID> childrenIds, - ConfigurationEntryStore store) - { - super(); - _id = id; - _type = type; - _attributes = attributes; - _childrenIds = childrenIds; - _store = store; - } + String getType(); - public UUID getId() - { - return _id; - } + Map<String, Object> getAttributes(); - public String getType() - { - return _type; - } + Set<UUID> getChildrenIds(); - public Map<String, Object> getAttributes() - { - return _attributes; - } + ConfigurationEntryStore getStore(); - public Set<UUID> getChildrenIds() - { - return _childrenIds; - } - - public ConfigurationEntryStore getStore() - { - return _store; - } - - /** - * Returns this entry's children. The collection should not be modified. - */ - public Map<String, Collection<ConfigurationEntry>> getChildren() - { - Map<String, Collection<ConfigurationEntry>> children = null; - if (_childrenIds == null) - { - children = Collections.emptyMap(); - } - else - { - children = new HashMap<String, Collection<ConfigurationEntry>>(); - for (UUID childId : _childrenIds) - { - ConfigurationEntry entry = _store.getEntry(childId); - String type = entry.getType(); - Collection<ConfigurationEntry> childrenOfType = children.get(type); - if (childrenOfType == null) - { - childrenOfType = new ArrayList<ConfigurationEntry>(); - children.put(type, childrenOfType); - } - childrenOfType.add(entry); - } - } - return Collections.unmodifiableMap(children); - } - - public boolean hasChild(UUID id) - { - return _childrenIds.contains(id); - } - - @Override - public int hashCode() - { - return _id.hashCode(); - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - { - return true; - } - if (obj == null) - { - return false; - } - if (getClass() != obj.getClass()) - { - return false; - } - - ConfigurationEntry other = (ConfigurationEntry) obj; - if (_id == null) - { - if (other._id != null) - { - return false; - } - } - else if (!_id.equals(other._id)) - { - return false; - } - - if (_type == null) - { - if (other._type != null) - { - return false; - } - } - else if (!_type.equals(other._type)) - { - return false; - } - - if (_store == null) - { - if (other._store != null) - { - return false; - } - } - else if (!_store.equals(other._store)) - { - return false; - } - - if (_childrenIds == null) - { - if (other._childrenIds != null) - { - return false; - } - } - else if (!_childrenIds.equals(other._childrenIds)) - { - return false; - } - - if (_attributes == null) - { - if (other._attributes != null) - { - return false; - } - } - else if (!_attributes.equals(other._attributes)) - { - return false; - } - return true; - } - - @Override - public String toString() - { - return "ConfigurationEntry [id=" + _id + ", type=" + _type + ", attributes=" + _attributes + ", childrenIds=" - + _childrenIds + "]"; - } + Map<String, Collection<ConfigurationEntry>> getChildren(); + boolean hasChild(UUID id); } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryImpl.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryImpl.java new file mode 100644 index 0000000000..46fd5e0e0a --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryImpl.java @@ -0,0 +1,211 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.configuration; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.apache.qpid.server.configuration.store.MemoryConfigurationEntryStore; + +public class ConfigurationEntryImpl implements ConfigurationEntry +{ + + private final UUID _id; + private final String _type; + private final Map<String, Object> _attributes; + private final Set<UUID> _childrenIds; + private final MemoryConfigurationEntryStore _store; + + public ConfigurationEntryImpl(UUID id, String type, Map<String, Object> attributes, Set<UUID> childrenIds, + MemoryConfigurationEntryStore store) + { + super(); + _id = id; + _type = type; + _attributes = attributes; + _childrenIds = childrenIds; + _store = store; + } + + @Override + public UUID getId() + { + return _id; + } + + @Override + public String getType() + { + return _type; + } + + @Override + public Map<String, Object> getAttributes() + { + return _attributes; + } + + @Override + public Set<UUID> getChildrenIds() + { + return _childrenIds; + } + + @Override + public ConfigurationEntryStore getStore() + { + return _store; + } + + /** + * Returns this entry's children. The collection should not be modified. + */ + @Override + public Map<String, Collection<ConfigurationEntry>> getChildren() + { + Map<String, Collection<ConfigurationEntry>> children = null; + if (_childrenIds == null) + { + children = Collections.emptyMap(); + } + else + { + children = new HashMap<String, Collection<ConfigurationEntry>>(); + for (UUID childId : _childrenIds) + { + ConfigurationEntry entry = _store.getEntry(childId); + String type = entry.getType(); + Collection<ConfigurationEntry> childrenOfType = children.get(type); + if (childrenOfType == null) + { + childrenOfType = new ArrayList<ConfigurationEntry>(); + children.put(type, childrenOfType); + } + childrenOfType.add(entry); + } + } + return Collections.unmodifiableMap(children); + } + + @Override + public boolean hasChild(UUID id) + { + return _childrenIds.contains(id); + } + + @Override + public int hashCode() + { + return _id.hashCode(); + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) + { + return true; + } + if (obj == null) + { + return false; + } + if (getClass() != obj.getClass()) + { + return false; + } + + ConfigurationEntryImpl other = (ConfigurationEntryImpl) obj; + if (_id == null) + { + if (other._id != null) + { + return false; + } + } + else if (!_id.equals(other._id)) + { + return false; + } + + if (_type == null) + { + if (other._type != null) + { + return false; + } + } + else if (!_type.equals(other._type)) + { + return false; + } + + if (_store == null) + { + if (other._store != null) + { + return false; + } + } + else if (!_store.equals(other._store)) + { + return false; + } + + if (_childrenIds == null) + { + if (other._childrenIds != null) + { + return false; + } + } + else if (!_childrenIds.equals(other._childrenIds)) + { + return false; + } + + if (_attributes == null) + { + if (other._attributes != null) + { + return false; + } + } + else if (!_attributes.equals(other._attributes)) + { + return false; + } + return true; + } + + @Override + public String toString() + { + return "ConfigurationEntry [id=" + _id + ", type=" + _type + ", attributes=" + _attributes + ", childrenIds=" + + _childrenIds + "]"; + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryStore.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryStore.java index 5f3589c7ef..11e92fcff9 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryStore.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryStore.java @@ -20,43 +20,12 @@ */ package org.apache.qpid.server.configuration; -import java.util.UUID; +import org.apache.qpid.server.store.DurableConfigurationStore; -public interface ConfigurationEntryStore +public interface ConfigurationEntryStore extends DurableConfigurationStore { /** - * Returns stored root configuration entry - * - * @return root entry - */ - ConfigurationEntry getRootEntry(); - - /** - * Returns the configuration entry with a given id. - * - * @return entry with a given id or null if entry does not exists - */ - ConfigurationEntry getEntry(UUID id); - - /** - * Saves given entries in the store. - * - * @param entries entries to store - * @throws IllegalConfigurationException if save operation fails - */ - void save(ConfigurationEntry... entries); - - /** - * Removes the entries with given IDs and all their children - * - * @param entryIds IDs of entries to remove - * @return IDs of removed entries - * @throws IllegalConfigurationException if remove operation fails - */ - UUID[] remove(UUID... entryIds); - - /** * Copies the store into the given location * * @param target location to copy store into diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfiguredObjectRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfiguredObjectRecoverer.java index 65d97e6db1..21e27f363e 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfiguredObjectRecoverer.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfiguredObjectRecoverer.java @@ -24,5 +24,4 @@ import org.apache.qpid.server.model.ConfiguredObject; public interface ConfiguredObjectRecoverer<T extends ConfiguredObject> { - T create(RecovererProvider recovererProvider, ConfigurationEntry entry, ConfiguredObject... parents); } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/AccessControlProviderRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/AccessControlProviderRecoverer.java deleted file mode 100644 index df80b9fe5f..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/AccessControlProviderRecoverer.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import java.util.Map; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.adapter.AccessControlProviderFactory; - -public class AccessControlProviderRecoverer implements ConfiguredObjectRecoverer<AccessControlProvider> -{ - private final AccessControlProviderFactory _accessControlProviderFactory; - - public AccessControlProviderRecoverer(AccessControlProviderFactory authenticationProviderFactory) - { - _accessControlProviderFactory = authenticationProviderFactory; - } - - @Override - public AccessControlProvider create(RecovererProvider recovererProvider, ConfigurationEntry configurationEntry, ConfiguredObject... parents) - { - Broker broker = RecovererHelper.verifyOnlyBrokerIsParent(parents); - Map<String, Object> attributes = configurationEntry.getAttributes(); - AccessControlProvider authenticationProvider = _accessControlProviderFactory.recover( - configurationEntry.getId(), - broker, - attributes); - - return authenticationProvider; - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecoverer.java deleted file mode 100644 index 46f3cd458b..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecoverer.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import java.util.Collection; -import java.util.Map; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.User; -import org.apache.qpid.server.model.adapter.AuthenticationProviderFactory; - -public class AuthenticationProviderRecoverer implements ConfiguredObjectRecoverer<AuthenticationProvider> -{ - private final AuthenticationProviderFactory _authenticationProviderFactory; - private final StoreConfigurationChangeListener _storeChangeListener; - - public AuthenticationProviderRecoverer(AuthenticationProviderFactory authenticationProviderFactory, StoreConfigurationChangeListener storeChangeListener) - { - _authenticationProviderFactory = authenticationProviderFactory; - _storeChangeListener = storeChangeListener; - } - - @Override - public AuthenticationProvider create(RecovererProvider recovererProvider, ConfigurationEntry configurationEntry, ConfiguredObject... parents) - { - Broker broker = RecovererHelper.verifyOnlyBrokerIsParent(parents); - Map<String, Object> attributes = configurationEntry.getAttributes(); - AuthenticationProvider authenticationProvider = _authenticationProviderFactory.recover(configurationEntry.getId(), attributes, broker); - - Map<String, Collection<ConfigurationEntry>> childEntries = configurationEntry.getChildren(); - - for (String type : childEntries.keySet()) - { - recoverType(recovererProvider, _storeChangeListener, authenticationProvider, childEntries, type); - } - - return authenticationProvider; - } - - private void recoverType(RecovererProvider recovererProvider, - StoreConfigurationChangeListener storeChangeListener, - AuthenticationProvider authenticationProvider, - Map<String, Collection<ConfigurationEntry>> childEntries, - String type) - { - ConfiguredObjectRecoverer<?> recoverer = null; - - if(authenticationProvider instanceof RecovererProvider) - { - recoverer = ((RecovererProvider)authenticationProvider).getRecoverer(type); - } - - if(recoverer == null) - { - recoverer = recovererProvider.getRecoverer(type); - } - - if (recoverer == null) - { - if(authenticationProvider instanceof RecovererProvider) - { - ((RecovererProvider)authenticationProvider).getRecoverer(type); - } - throw new IllegalConfigurationException("Cannot recover entry for the type '" + type + "' from broker"); - } - Collection<ConfigurationEntry> entries = childEntries.get(type); - for (ConfigurationEntry childEntry : entries) - { - ConfiguredObject object = recoverer.create(recovererProvider, childEntry, authenticationProvider); - if (object == null) - { - throw new IllegalConfigurationException("Cannot create configured object for the entry " + childEntry); - } - if (object instanceof PreferencesProvider) - { - authenticationProvider.setPreferencesProvider((PreferencesProvider)object); - } - else if(object instanceof User) - { - authenticationProvider.recoverUser((User)object); - } - else - { - throw new IllegalConfigurationException("Cannot associate " + object + " with authentication provider " + authenticationProvider); - } - object.addChangeListener(storeChangeListener); - } - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/BrokerRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/BrokerRecoverer.java deleted file mode 100644 index 838cb80103..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/BrokerRecoverer.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.adapter.AccessControlProviderFactory; -import org.apache.qpid.server.model.adapter.AuthenticationProviderFactory; -import org.apache.qpid.server.model.adapter.BrokerAdapter; -import org.apache.qpid.server.model.adapter.GroupProviderFactory; -import org.apache.qpid.server.model.adapter.PortFactory; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.util.MapValueConverter; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -public class BrokerRecoverer implements ConfiguredObjectRecoverer<Broker> -{ - private static final Pattern MODEL_VERSION_PATTERN = Pattern.compile("^\\d+\\.\\d+$"); - - private final StatisticsGatherer _statisticsGatherer; - private final VirtualHostRegistry _virtualHostRegistry; - private final LogRecorder _logRecorder; - private final AuthenticationProviderFactory _authenticationProviderFactory; - private final AccessControlProviderFactory _accessControlProviderFactory; - private final PortFactory _portFactory; - private final TaskExecutor _taskExecutor; - private final BrokerOptions _brokerOptions; - private final GroupProviderFactory _groupProviderFactory; - private final StoreConfigurationChangeListener _storeChangeListener; - - public BrokerRecoverer(AuthenticationProviderFactory authenticationProviderFactory, - GroupProviderFactory groupProviderFactory, - AccessControlProviderFactory accessControlProviderFactory, - PortFactory portFactory, - StatisticsGatherer statisticsGatherer, - VirtualHostRegistry virtualHostRegistry, - LogRecorder logRecorder, - TaskExecutor taskExecutor, - BrokerOptions brokerOptions, - StoreConfigurationChangeListener storeChangeListener) - { - _groupProviderFactory = groupProviderFactory; - _portFactory = portFactory; - _authenticationProviderFactory = authenticationProviderFactory; - _accessControlProviderFactory = accessControlProviderFactory; - _statisticsGatherer = statisticsGatherer; - _virtualHostRegistry = virtualHostRegistry; - _logRecorder = logRecorder; - _taskExecutor = taskExecutor; - _brokerOptions = brokerOptions; - _storeChangeListener = storeChangeListener; - } - - @Override - public BrokerAdapter create(RecovererProvider recovererProvider, ConfigurationEntry entry, ConfiguredObject... parents) - { - Map<String, Object> attributesCopy = validateAttributes(entry); - - attributesCopy.put(Broker.MODEL_VERSION, Model.MODEL_VERSION); - - BrokerAdapter broker = new BrokerAdapter(entry.getId(), attributesCopy, _statisticsGatherer, _virtualHostRegistry, - _logRecorder, - _authenticationProviderFactory,_groupProviderFactory, _accessControlProviderFactory, - _portFactory, _taskExecutor, entry.getStore(), _brokerOptions); - - broker.addChangeListener(_storeChangeListener); - - Map<String, Collection<ConfigurationEntry>> childEntries = new HashMap<String, Collection<ConfigurationEntry>>(entry.getChildren()); - - List<String> types = makePrioritisedListOfTypes(childEntries.keySet(), TrustStore.class.getSimpleName(), KeyStore.class.getSimpleName(), AuthenticationProvider.class.getSimpleName()); - - for (String type : types) - { - recoverType(recovererProvider, _storeChangeListener, broker, childEntries, type); - } - - return broker; - } - - private List<String> makePrioritisedListOfTypes(Set<String> allTypes, String... priorityOrderedTypes) - { - List<String> prioritisedList = new ArrayList<String>(allTypes.size()); - Set<String> remainder = new HashSet<String>(allTypes); - - for (String type : priorityOrderedTypes) - { - Set<String> singleton = Collections.singleton(type); - Set<String> intersection = new HashSet<String>(allTypes); - intersection.retainAll(singleton); - remainder.removeAll(singleton); - prioritisedList.addAll(intersection); - } - - prioritisedList.addAll(remainder); - return prioritisedList; - } - - private Map<String, Object> validateAttributes(ConfigurationEntry entry) - { - Map<String, Object> attributes = entry.getAttributes(); - - String modelVersion = null; - if (attributes.containsKey(Broker.MODEL_VERSION)) - { - modelVersion = MapValueConverter.getStringAttribute(Broker.MODEL_VERSION, attributes, null); - } - - if (modelVersion == null) - { - throw new IllegalConfigurationException("Broker " + Broker.MODEL_VERSION + " must be specified"); - } - - if (!MODEL_VERSION_PATTERN.matcher(modelVersion).matches()) - { - throw new IllegalConfigurationException("Broker " + Broker.MODEL_VERSION + " is specified in incorrect format: " - + modelVersion); - } - - int versionSeparatorPosition = modelVersion.indexOf("."); - String majorVersionPart = modelVersion.substring(0, versionSeparatorPosition); - int majorModelVersion = Integer.parseInt(majorVersionPart); - int minorModelVersion = Integer.parseInt(modelVersion.substring(versionSeparatorPosition + 1)); - - if (majorModelVersion != Model.MODEL_MAJOR_VERSION || minorModelVersion > Model.MODEL_MINOR_VERSION) - { - throw new IllegalConfigurationException("The model version '" + modelVersion - + "' in configuration is incompatible with the broker model version '" + Model.MODEL_VERSION + "'"); - } - - if(!Model.MODEL_VERSION.equals(modelVersion)) - { - String oldVersion; - do - { - oldVersion = modelVersion; - StoreUpgrader.upgrade(entry.getStore()); - entry = entry.getStore().getRootEntry(); - attributes = entry.getAttributes(); - modelVersion = MapValueConverter.getStringAttribute(Broker.MODEL_VERSION, attributes, null); - } - while(!(modelVersion.equals(oldVersion) || modelVersion.equals(Model.MODEL_VERSION))); - } - - return new HashMap<String, Object>(attributes); - } - - private void recoverType(RecovererProvider recovererProvider, - StoreConfigurationChangeListener storeChangeListener, - BrokerAdapter broker, - Map<String, Collection<ConfigurationEntry>> childEntries, - String type) - { - ConfiguredObjectRecoverer<?> recoverer = recovererProvider.getRecoverer(type); - if (recoverer == null) - { - throw new IllegalConfigurationException("Cannot recover entry for the type '" + type + "' from broker"); - } - Collection<ConfigurationEntry> entries = childEntries.get(type); - for (ConfigurationEntry childEntry : entries) - { - ConfiguredObject object = recoverer.create(recovererProvider, childEntry, broker); - if (object == null) - { - throw new IllegalConfigurationException("Cannot create configured object for the entry " + childEntry); - } - broker.recoverChild(object); - object.addChangeListener(storeChangeListener); - } - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/BrokerStoreUpgrader.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/BrokerStoreUpgrader.java new file mode 100644 index 0000000000..b7b672fd58 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/BrokerStoreUpgrader.java @@ -0,0 +1,764 @@ +package org.apache.qpid.server.configuration.startup;/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.apache.log4j.Logger; + +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.Model; +import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.ConfiguredObjectRecordImpl; +import org.apache.qpid.server.store.DurableConfigurationStore; +import org.apache.qpid.server.store.DurableConfigurationStoreUpgrader; +import org.apache.qpid.server.store.NonNullUpgrader; +import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; + +public class BrokerStoreUpgrader +{ + private static Logger LOGGER = Logger.getLogger(BrokerStoreUpgrader.class); + + private static Map<String, UpgraderPhaseFactory> _upgraders = new HashMap<String, UpgraderPhaseFactory>(); + private final SystemContext _systemContext; + + public BrokerStoreUpgrader(SystemContext systemContext) + { + _systemContext = systemContext; + } + + private static abstract class UpgraderPhaseFactory + { + private final String _toVersion; + + protected UpgraderPhaseFactory(String fromVersion, String toVersion) + { + _upgraders.put(fromVersion, this); + _toVersion = toVersion; + } + + public String getToVersion() + { + return _toVersion; + } + + public abstract BrokerStoreUpgraderPhase newInstance(); + } + + private static abstract class BrokerStoreUpgraderPhase extends NonNullUpgrader + { + private final String _toVersion; + + protected BrokerStoreUpgraderPhase(String toVersion) + { + _toVersion = toVersion; + } + + + protected ConfiguredObjectRecord upgradeBrokerRecord(ConfiguredObjectRecord record) + { + Map<String, Object> updatedAttributes = new HashMap<String, Object>(record.getAttributes()); + updatedAttributes.put(Broker.MODEL_VERSION, _toVersion); + record = createModifiedRecord(record, updatedAttributes); + getUpdateMap().put(record.getId(), record); + return record; + } + } + + // Note: don't use externally defined constants in upgraders in case they change, the values here MUST stay the same + // no matter what changes are made to the code in the future + + private final static UpgraderPhaseFactory UPGRADE_1_0 = new UpgraderPhaseFactory("1.0", "1.1") + { + @Override + public BrokerStoreUpgraderPhase newInstance() + { + return new BrokerStoreUpgraderPhase(getToVersion()) + { + @Override + public void configuredObject(ConfiguredObjectRecord record) + { + if (record.getType().equals("Broker")) + { + record = upgradeBrokerRecord(record); + } + else if (record.getType().equals("VirtualHost") && record.getAttributes().containsKey("storeType")) + { + Map<String, Object> updatedAttributes = new HashMap<String, Object>(record.getAttributes()); + updatedAttributes.put("type", "STANDARD"); + record = createModifiedRecord(record, updatedAttributes); + getUpdateMap().put(record.getId(), record); + } + + getNextUpgrader().configuredObject(record); + } + + + @Override + public void complete() + { + getNextUpgrader().complete(); + } + }; + } + + + }; + + + protected static ConfiguredObjectRecordImpl createModifiedRecord(final ConfiguredObjectRecord record, + final Map<String, Object> updatedAttributes) + { + + return new ConfiguredObjectRecordImpl(record.getId(), record.getType(), updatedAttributes, record.getParents()); + } + + private final static UpgraderPhaseFactory UPGRADE_1_1 = new UpgraderPhaseFactory("1.1", "1.2") + { + @Override + public BrokerStoreUpgraderPhase newInstance() + { + return new BrokerStoreUpgraderPhase(getToVersion()) + { + + @Override + public void configuredObject(ConfiguredObjectRecord record) + { + if (record.getType().equals("Broker")) + { + record = upgradeBrokerRecord(record); + } + + getNextUpgrader().configuredObject(record); + + } + + @Override + public void complete() + { + getNextUpgrader().complete(); + } + }; + } + }; + + + private final static UpgraderPhaseFactory UPGRADE_1_2 = new UpgraderPhaseFactory("1.2", "1.3") + { + @Override + public BrokerStoreUpgraderPhase newInstance() + { + return new BrokerStoreUpgraderPhase(getToVersion()) + { + + @Override + public void configuredObject(ConfiguredObjectRecord record) + { + if (record.getType().equals("TrustStore") && record.getAttributes().containsKey("type")) + { + Map<String, Object> updatedAttributes = new HashMap<String, Object>(record.getAttributes()); + updatedAttributes.put("trustStoreType", updatedAttributes.remove("type")); + record = createModifiedRecord(record, updatedAttributes); + getUpdateMap().put(record.getId(), record); + + } + else if (record.getType().equals("KeyStore") && record.getAttributes().containsKey("type")) + { + Map<String, Object> updatedAttributes = new HashMap<String, Object>(record.getAttributes()); + updatedAttributes.put("keyStoreType", updatedAttributes.remove("type")); + record = createModifiedRecord(record, updatedAttributes); + getUpdateMap().put(record.getId(), record); + + } + else if (record.getType().equals("Broker")) + { + record = upgradeBrokerRecord(record); + } + + getNextUpgrader().configuredObject(record); + + } + + @Override + public void complete() + { + getNextUpgrader().complete(); + } + }; + } + }; + + + private final static UpgraderPhaseFactory UPGRADE_1_3 = new UpgraderPhaseFactory("1.3", "1.4") + { + @Override + public BrokerStoreUpgraderPhase newInstance() + { + return new BrokerStoreUpgraderPhase(getToVersion()) + { + + private Map<String, VirtualHostEntryUpgrader> _vhostUpgraderMap = new HashMap<String, VirtualHostEntryUpgrader>() + {{ + put("BDB_HA", new BdbHaVirtualHostUpgrader()); + put("STANDARD", new StandardVirtualHostUpgrader()); + }}; + + @Override + public void configuredObject(ConfiguredObjectRecord record) + { + if (record.getType().equals("VirtualHost")) + { + Map<String, Object> attributes = record.getAttributes(); + if (attributes.containsKey("configPath")) + { + throw new IllegalConfigurationException("Auto-upgrade of virtual host " + attributes.get("name") + " having XML configuration is not supported. Virtual host configuration file is " + attributes.get("configPath")); + } + + String type = (String) attributes.get("type"); + VirtualHostEntryUpgrader vhostUpgrader = _vhostUpgraderMap.get(type); + if (vhostUpgrader == null) + { + throw new IllegalConfigurationException("Don't know how to perform an upgrade from version for virtualhost type " + type); + } + record = vhostUpgrader.upgrade(record); + getUpdateMap().put(record.getId(), record); + } + else if (record.getType().equals("Plugin") && record.getAttributes().containsKey("pluginType")) + { + Map<String, Object> updatedAttributes = new HashMap<String, Object>(record.getAttributes()); + updatedAttributes.put("type", updatedAttributes.remove("pluginType")); + record = createModifiedRecord(record, updatedAttributes); + getUpdateMap().put(record.getId(), record); + + } + else if (record.getType().equals("Broker")) + { + record = upgradeBrokerRecord(record); + } + + getNextUpgrader().configuredObject(record); + + } + + @Override + public void complete() + { + getNextUpgrader().complete(); + } + }; + } + + + }; + + private static interface VirtualHostEntryUpgrader + { + ConfiguredObjectRecord upgrade(ConfiguredObjectRecord vhost); + } + + private static class StandardVirtualHostUpgrader implements VirtualHostEntryUpgrader + { + Map<String, AttributesTransformer> _messageStoreAttributeTransformers = new HashMap<String, AttributesTransformer>() + {{ + put("DERBY", new AttributesTransformer(). + addAttributeTransformer("storePath", copyAttribute()). + addAttributeTransformer("storeUnderfullSize", copyAttribute()). + addAttributeTransformer("storeOverfullSize", copyAttribute()). + addAttributeTransformer("storeType", mutateAttributeValue("DERBY"))); + put("MEMORY", new AttributesTransformer(). + addAttributeTransformer("storeType", mutateAttributeValue("Memory"))); + put("BDB", new AttributesTransformer(). + addAttributeTransformer("storePath", copyAttribute()). + addAttributeTransformer("storeUnderfullSize", copyAttribute()). + addAttributeTransformer("storeOverfullSize", copyAttribute()). + addAttributeTransformer("bdbEnvironmentConfig", copyAttribute()). + addAttributeTransformer("storeType", mutateAttributeValue("BDB"))); + put("JDBC", new AttributesTransformer(). + addAttributeTransformer("storePath", mutateAttributeName("connectionURL")). + addAttributeTransformer("connectionURL", copyAttribute()). + addAttributeTransformer("connectionPool", copyAttribute()). + addAttributeTransformer("jdbcBigIntType", copyAttribute()). + addAttributeTransformer("jdbcBytesForBlob", copyAttribute()). + addAttributeTransformer("jdbcBlobType", copyAttribute()). + addAttributeTransformer("jdbcVarbinaryType", copyAttribute()). + addAttributeTransformer("partitionCount", copyAttribute()). + addAttributeTransformer("maxConnectionsPerPartition", copyAttribute()). + addAttributeTransformer("minConnectionsPerPartition", copyAttribute()). + addAttributeTransformer("storeType", mutateAttributeValue("JDBC"))); + }}; + + Map<String, AttributesTransformer> _configurationStoreAttributeTransformers = new HashMap<String, AttributesTransformer>() + {{ + put("DERBY", new AttributesTransformer(). + addAttributeTransformer("configStorePath", mutateAttributeName("storePath")). + addAttributeTransformer("configStoreType", mutateAttributeName("storeType"), mutateAttributeValue("DERBY"))); + put("MEMORY", new AttributesTransformer(). + addAttributeTransformer("configStoreType", mutateAttributeValue("Memory"))); + put("JSON", new AttributesTransformer(). + addAttributeTransformer("configStorePath", mutateAttributeName("storePath")). + addAttributeTransformer("configStoreType", mutateAttributeName("storeType"), mutateAttributeValue("JSON"))); + put("BDB", new AttributesTransformer(). + addAttributeTransformer("configStorePath", mutateAttributeName("storePath")). + addAttributeTransformer("bdbEnvironmentConfig", copyAttribute()). + addAttributeTransformer("configStoreType", mutateAttributeName("storeType"), mutateAttributeValue("BDB"))); + put("JDBC", new AttributesTransformer(). + addAttributeTransformer("configStorePath", mutateAttributeName("connectionURL")). + addAttributeTransformer("configConnectionURL", mutateAttributeName("connectionURL")). + addAttributeTransformer("connectionPool", copyAttribute()). + addAttributeTransformer("jdbcBigIntType", copyAttribute()). + addAttributeTransformer("jdbcBytesForBlob", copyAttribute()). + addAttributeTransformer("jdbcBlobType", copyAttribute()). + addAttributeTransformer("jdbcVarbinaryType", copyAttribute()). + addAttributeTransformer("partitionCount", copyAttribute()). + addAttributeTransformer("maxConnectionsPerPartition", copyAttribute()). + addAttributeTransformer("minConnectionsPerPartition", copyAttribute()). + addAttributeTransformer("configStoreType", mutateAttributeName("storeType"), mutateAttributeValue("JDBC"))); + }}; + + @Override + public ConfiguredObjectRecord upgrade(ConfiguredObjectRecord vhost) + { + Map<String, Object> attributes = vhost.getAttributes(); + Map<String, Object> newAttributes = new HashMap<String, Object>(attributes); + + String capitalisedStoreType = String.valueOf(attributes.get("storeType")).toUpperCase(); + AttributesTransformer vhAttrsToMessageStoreSettings = _messageStoreAttributeTransformers.get(capitalisedStoreType); + Map<String, Object> messageStoreSettings = null; + if (vhAttrsToMessageStoreSettings != null) + { + messageStoreSettings = vhAttrsToMessageStoreSettings.upgrade(attributes); + } + + if (attributes.containsKey("configStoreType")) + { + String capitaliseConfigStoreType = ((String) attributes.get("configStoreType")).toUpperCase(); + AttributesTransformer vhAttrsToConfigurationStoreSettings = _configurationStoreAttributeTransformers + .get(capitaliseConfigStoreType); + Map<String, Object> configurationStoreSettings = vhAttrsToConfigurationStoreSettings.upgrade(attributes); + newAttributes.keySet().removeAll(vhAttrsToConfigurationStoreSettings.getNamesToBeDeleted()); + newAttributes.put("configurationStoreSettings", configurationStoreSettings); + } + + if (vhAttrsToMessageStoreSettings != null) + { + newAttributes.keySet().removeAll(vhAttrsToMessageStoreSettings.getNamesToBeDeleted()); + newAttributes.put("messageStoreSettings", messageStoreSettings); + } + + return new ConfiguredObjectRecordImpl(vhost.getId(), vhost.getType(), newAttributes, vhost.getParents()); + } + } + + private static class BdbHaVirtualHostUpgrader implements VirtualHostEntryUpgrader + { + + private final AttributesTransformer haAttributesTransformer = new AttributesTransformer(). + addAttributeTransformer("storePath", copyAttribute()). + addAttributeTransformer("storeUnderfullSize", copyAttribute()). + addAttributeTransformer("storeOverfullSize", copyAttribute()). + addAttributeTransformer("haNodeName", copyAttribute()). + addAttributeTransformer("haGroupName", copyAttribute()). + addAttributeTransformer("haHelperAddress", copyAttribute()). + addAttributeTransformer("haCoalescingSync", copyAttribute()). + addAttributeTransformer("haNodeAddress", copyAttribute()). + addAttributeTransformer("haDurability", copyAttribute()). + addAttributeTransformer("haDesignatedPrimary", copyAttribute()). + addAttributeTransformer("haReplicationConfig", copyAttribute()). + addAttributeTransformer("bdbEnvironmentConfig", copyAttribute()). + addAttributeTransformer("storeType", removeAttribute()); + + @Override + public ConfiguredObjectRecord upgrade(ConfiguredObjectRecord vhost) + { + Map<String, Object> attributes = vhost.getAttributes(); + + Map<String, Object> messageStoreSettings = haAttributesTransformer.upgrade(attributes); + + Map<String, Object> newAttributes = new HashMap<String, Object>(attributes); + newAttributes.keySet().removeAll(haAttributesTransformer.getNamesToBeDeleted()); + newAttributes.put("messageStoreSettings", messageStoreSettings); + + return new ConfiguredObjectRecordImpl(vhost.getId(), vhost.getType(), newAttributes, vhost.getParents()); + } + } + + private static class AttributesTransformer + { + private final Map<String, List<AttributeTransformer>> _transformers = new HashMap<String, List<AttributeTransformer>>(); + private Set<String> _namesToBeDeleted = new HashSet<String>(); + + public AttributesTransformer addAttributeTransformer(String string, AttributeTransformer... attributeTransformers) + { + _transformers.put(string, Arrays.asList(attributeTransformers)); + return this; + } + + public Map<String, Object> upgrade(Map<String, Object> attributes) + { + Map<String, Object> settings = new HashMap<String, Object>(); + for (Map.Entry<String, List<AttributeTransformer>> entry : _transformers.entrySet()) + { + String attributeName = entry.getKey(); + if (attributes.containsKey(attributeName)) + { + Object attributeValue = attributes.get(attributeName); + MutableEntry newEntry = new MutableEntry(attributeName, attributeValue); + + List<AttributeTransformer> transformers = entry.getValue(); + for (AttributeTransformer attributeTransformer : transformers) + { + newEntry = attributeTransformer.transform(newEntry); + if (newEntry == null) + { + break; + } + } + if (newEntry != null) + { + settings.put(newEntry.getKey(), newEntry.getValue()); + } + + _namesToBeDeleted.add(attributeName); + } + } + return settings; + } + + public Set<String> getNamesToBeDeleted() + { + return _namesToBeDeleted; + } + } + + private static AttributeTransformer copyAttribute() + { + return CopyAttribute.INSTANCE; + } + + private static AttributeTransformer removeAttribute() + { + return RemoveAttribute.INSTANCE; + } + + private static AttributeTransformer mutateAttributeValue(Object newValue) + { + return new MutateAttributeValue(newValue); + } + + private static AttributeTransformer mutateAttributeName(String newName) + { + return new MutateAttributeName(newName); + } + + private static interface AttributeTransformer + { + MutableEntry transform(MutableEntry entry); + } + + private static class CopyAttribute implements AttributeTransformer + { + private static final CopyAttribute INSTANCE = new CopyAttribute(); + + private CopyAttribute() + { + } + + @Override + public MutableEntry transform(MutableEntry entry) + { + return entry; + } + } + + private static class RemoveAttribute implements AttributeTransformer + { + private static final RemoveAttribute INSTANCE = new RemoveAttribute(); + + private RemoveAttribute() + { + } + + @Override + public MutableEntry transform(MutableEntry entry) + { + return null; + } + } + + private static class MutateAttributeName implements AttributeTransformer + { + private final String _newName; + + public MutateAttributeName(String newName) + { + _newName = newName; + } + + @Override + public MutableEntry transform(MutableEntry entry) + { + entry.setKey(_newName); + return entry; + } + } + + private static class MutateAttributeValue implements AttributeTransformer + { + private final Object _newValue; + + public MutateAttributeValue(Object newValue) + { + _newValue = newValue; + } + + @Override + public MutableEntry transform(MutableEntry entry) + { + entry.setValue(_newValue); + return entry; + } + } + + private static class MutableEntry + { + private String _key; + private Object _value; + + public MutableEntry(String key, Object value) + { + _key = key; + _value = value; + } + + public String getKey() + { + return _key; + } + + public void setKey(String key) + { + _key = key; + } + + public Object getValue() + { + return _value; + } + + public void setValue(Object value) + { + _value = value; + } + } + + + + + public Broker upgrade(DurableConfigurationStore store) + { + final BrokerStoreRecoveryHandler recoveryHandler = new BrokerStoreRecoveryHandler(_systemContext, store); + store.openConfigurationStore(_systemContext, Collections.<String,Object>emptyMap()); + store.visitConfiguredObjectRecords(recoveryHandler); + + return recoveryHandler.getBroker(); + } + + + private static class BrokerStoreRecoveryHandler implements ConfiguredObjectRecordHandler + { + private static Logger LOGGER = Logger.getLogger(BrokerStoreRecoveryHandler.class); + + private DurableConfigurationStoreUpgrader _upgrader; + private DurableConfigurationStore _store; + private final Map<UUID, ConfiguredObjectRecord> _records = new HashMap<UUID, ConfiguredObjectRecord>(); + private int _version; + private final SystemContext _systemContext; + + private BrokerStoreRecoveryHandler(final SystemContext systemContext, DurableConfigurationStore store) + { + _systemContext = systemContext; + _store = store; + } + + + @Override + public void begin(final int configVersion) + { + _version = configVersion; + } + + @Override + public boolean handle(final ConfiguredObjectRecord object) + { + _records.put(object.getId(), object); + return true; + } + + @Override + public int end() + { + String version = getCurrentVersion(); + + while(!Model.MODEL_VERSION.equals(version)) + { + LOGGER.debug("Adding broker store upgrader from model version: " + version); + final UpgraderPhaseFactory upgraderPhaseFactory = _upgraders.get(version); + BrokerStoreUpgraderPhase upgrader = upgraderPhaseFactory.newInstance(); + if(_upgrader == null) + { + _upgrader = upgrader; + } + else + { + _upgrader.setNextUpgrader(upgrader); + } + version = upgraderPhaseFactory.getToVersion(); + } + + if(_upgrader == null) + { + _upgrader = new DurableConfigurationStoreUpgrader() + { + + @Override + public void configuredObject(final ConfiguredObjectRecord record) + { + } + + @Override + public void complete() + { + } + + @Override + public void setNextUpgrader(final DurableConfigurationStoreUpgrader upgrader) + { + } + + @Override + public Map<UUID, ConfiguredObjectRecord> getUpdatedRecords() + { + return Collections.emptyMap(); + } + + @Override + public Map<UUID, ConfiguredObjectRecord> getDeletedRecords() + { + return Collections.emptyMap(); + } + }; + } + else + { + _upgrader.setNextUpgrader(new DurableConfigurationStoreUpgrader() + { + @Override + public void configuredObject(final ConfiguredObjectRecord record) + { + } + + @Override + public void complete() + { + + } + + @Override + public void setNextUpgrader(final DurableConfigurationStoreUpgrader upgrader) + { + } + + @Override + public Map<UUID, ConfiguredObjectRecord> getUpdatedRecords() + { + return Collections.emptyMap(); + } + + @Override + public Map<UUID, ConfiguredObjectRecord> getDeletedRecords() + { + return Collections.emptyMap(); + } + }); + } + + for(ConfiguredObjectRecord record : _records.values()) + { + _upgrader.configuredObject(record); + } + + Map<UUID, ConfiguredObjectRecord> deletedRecords = _upgrader.getDeletedRecords(); + Map<UUID, ConfiguredObjectRecord> updatedRecords = _upgrader.getUpdatedRecords(); + + LOGGER.debug("Broker store upgrade: " + deletedRecords.size() + " records deleted"); + LOGGER.debug("Broker store upgrade: " + updatedRecords.size() + " records updated"); + LOGGER.debug("Broker store upgrade: " + _records.size() + " total records"); + + _store.update(true, updatedRecords.values().toArray(new ConfiguredObjectRecord[updatedRecords.size()])); + _store.remove(deletedRecords.values().toArray(new ConfiguredObjectRecord[deletedRecords.size()])); + + + + + _records.keySet().removeAll(deletedRecords.keySet()); + _records.putAll(updatedRecords); + + _systemContext.resolveObjects(_records.values().toArray(new ConfiguredObjectRecord[_records.size()])); + + _systemContext.getBroker().addChangeListener(new StoreConfigurationChangeListener(_store)); + + return _version; + } + + private String getCurrentVersion() + { + for(ConfiguredObjectRecord record : _records.values()) + { + if(record.getType().equals("Broker")) + { + String version = (String) record.getAttributes().get(Broker.MODEL_VERSION); + if(version == null) + { + version = "1.0"; + } + return version; + } + } + return Model.MODEL_VERSION; + } + + public Broker getBroker() + { + return _systemContext.getBroker(); + } + } + + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProvider.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProvider.java deleted file mode 100644 index da47f0c916..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProvider.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.logging.EventLogger; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.adapter.AccessControlProviderFactory; -import org.apache.qpid.server.model.adapter.AuthenticationProviderFactory; -import org.apache.qpid.server.model.adapter.GroupProviderFactory; -import org.apache.qpid.server.model.adapter.PortFactory; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.plugin.AccessControlFactory; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.plugin.GroupManagerFactory; -import org.apache.qpid.server.plugin.PluginFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -public class DefaultRecovererProvider implements RecovererProvider -{ - - private final StatisticsGatherer _brokerStatisticsGatherer; - private final VirtualHostRegistry _virtualHostRegistry; - private final LogRecorder _logRecorder; - private final AuthenticationProviderFactory _authenticationProviderFactory; - private final AccessControlProviderFactory _accessControlProviderFactory; - private final PortFactory _portFactory; - private final GroupProviderFactory _groupProviderFactory; - private final QpidServiceLoader<PluginFactory> _pluginFactoryServiceLoader; - private final TaskExecutor _taskExecutor; - private final BrokerOptions _brokerOptions; - private final StoreConfigurationChangeListener _storeChangeListener; - - public DefaultRecovererProvider(StatisticsGatherer brokerStatisticsGatherer, - VirtualHostRegistry virtualHostRegistry, - LogRecorder logRecorder, - TaskExecutor taskExecutor, - BrokerOptions brokerOptions, - StoreConfigurationChangeListener storeChangeListener) - { - _authenticationProviderFactory = new AuthenticationProviderFactory(new QpidServiceLoader<AuthenticationManagerFactory>()); - _accessControlProviderFactory = new AccessControlProviderFactory(new QpidServiceLoader<AccessControlFactory>()); - _groupProviderFactory = new GroupProviderFactory(new QpidServiceLoader<GroupManagerFactory>()); - _portFactory = new PortFactory(); - _brokerStatisticsGatherer = brokerStatisticsGatherer; - _virtualHostRegistry = virtualHostRegistry; - _logRecorder = logRecorder; - _pluginFactoryServiceLoader = new QpidServiceLoader<PluginFactory>(); - _taskExecutor = taskExecutor; - _brokerOptions = brokerOptions; - _storeChangeListener = storeChangeListener; - } - - @Override - public ConfiguredObjectRecoverer<?> getRecoverer(String type) - { - if (Broker.class.getSimpleName().equals(type)) - { - return new BrokerRecoverer(_authenticationProviderFactory, _groupProviderFactory, _accessControlProviderFactory, _portFactory, - _brokerStatisticsGatherer, _virtualHostRegistry, _logRecorder, - _taskExecutor, _brokerOptions, _storeChangeListener); - } - else if(VirtualHost.class.getSimpleName().equals(type)) - { - return new VirtualHostRecoverer(_brokerStatisticsGatherer); - } - else if(AccessControlProvider.class.getSimpleName().equals(type)) - { - return new AccessControlProviderRecoverer(_accessControlProviderFactory); - } - else if(AuthenticationProvider.class.getSimpleName().equals(type)) - { - return new AuthenticationProviderRecoverer(_authenticationProviderFactory, _storeChangeListener); - } - else if(Port.class.getSimpleName().equals(type)) - { - return new PortRecoverer(_portFactory); - } - else if(GroupProvider.class.getSimpleName().equals(type)) - { - return new GroupProviderRecoverer(_groupProviderFactory); - } - else if(KeyStore.class.getSimpleName().equals(type)) - { - return new KeyStoreRecoverer(); - } - else if(TrustStore.class.getSimpleName().equals(type)) - { - return new TrustStoreRecoverer(); - } - else if(PreferencesProvider.class.getSimpleName().equals(type)) - { - return new PreferencesProviderRecoverer(); - } - else if(Plugin.class.getSimpleName().equals(type)) - { - return new PluginRecoverer(_pluginFactoryServiceLoader); - } - - return null; - } - -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/GroupProviderRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/GroupProviderRecoverer.java deleted file mode 100644 index 00f23b3c1c..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/GroupProviderRecoverer.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import java.util.Map; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.adapter.GroupProviderFactory; - -public class GroupProviderRecoverer implements ConfiguredObjectRecoverer<GroupProvider> -{ - private GroupProviderFactory _groupProviderFactory; - - public GroupProviderRecoverer(GroupProviderFactory groupProviderFactory) - { - super(); - _groupProviderFactory = groupProviderFactory; - } - - @Override - public GroupProvider create(RecovererProvider recovererProvider, ConfigurationEntry configurationEntry, ConfiguredObject... parents) - { - Broker broker = RecovererHelper.verifyOnlyBrokerIsParent(parents); - Map<String, Object> attributes = configurationEntry.getAttributes(); - - GroupProvider groupProvider = _groupProviderFactory.recover(configurationEntry.getId(), broker, attributes); - - return groupProvider; - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PluginRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PluginRecoverer.java deleted file mode 100644 index ddc4482953..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PluginRecoverer.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.plugin.PluginFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; - -public class PluginRecoverer implements ConfiguredObjectRecoverer<ConfiguredObject> -{ - private QpidServiceLoader<PluginFactory> _serviceLoader; - - public PluginRecoverer(QpidServiceLoader<PluginFactory> serviceLoader) - { - _serviceLoader = serviceLoader; - } - - @Override - public ConfiguredObject create(RecovererProvider recovererProvider, ConfigurationEntry configurationEntry, ConfiguredObject... parents) - { - Broker broker = RecovererHelper.verifyOnlyBrokerIsParent(parents); - Map<String, Object> attributes = configurationEntry.getAttributes(); - Iterable<PluginFactory> factories = _serviceLoader.instancesOf(PluginFactory.class); - for (PluginFactory pluginFactory : factories) - { - UUID configurationId = configurationEntry.getId(); - ConfiguredObject pluginObject = pluginFactory.createInstance(configurationId, attributes, broker); - if (pluginObject != null) - { - UUID pluginId = pluginObject.getId(); - if (!configurationId.equals(pluginId)) - { - throw new IllegalStateException("Plugin object id '" + pluginId + "' does not equal expected id " + configurationId); - } - return pluginObject; - } - } - throw new IllegalConfigurationException("Cannot create a plugin object for " + attributes + " with factories " + factories); - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PortRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PortRecoverer.java deleted file mode 100644 index 147e835a8d..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PortRecoverer.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.adapter.BrokerAdapter; -import org.apache.qpid.server.model.adapter.PortFactory; - -public class PortRecoverer implements ConfiguredObjectRecoverer<Port> -{ - /** - * delegates to a {@link PortFactory} so that the logic can be shared by - * {@link BrokerAdapter} - */ - private final PortFactory _portFactory; - - public PortRecoverer(PortFactory portFactory) - { - _portFactory = portFactory; - } - - @Override - public Port create(RecovererProvider recovererProvider, ConfigurationEntry configurationEntry, ConfiguredObject... parents) - { - Broker broker = RecovererHelper.verifyOnlyBrokerIsParent(parents); - return _portFactory.createPort(configurationEntry.getId(), broker, configurationEntry.getAttributes()); - } - -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PreferencesProviderRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PreferencesProviderRecoverer.java deleted file mode 100644 index 3953f6c91d..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/PreferencesProviderRecoverer.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import java.util.Map; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.plugin.PreferencesProviderFactory; -import org.apache.qpid.server.util.MapValueConverter; - -public class PreferencesProviderRecoverer implements ConfiguredObjectRecoverer<PreferencesProvider> -{ - - @Override - public PreferencesProvider create(RecovererProvider recovererProvider, ConfigurationEntry entry, - ConfiguredObject... parents) - { - AuthenticationProvider authenticationProvider = RecovererHelper.verifyOnlyParentIsOfType(AuthenticationProvider.class, parents); - Map<String, Object> attributes = entry.getAttributes(); - String type = MapValueConverter.getStringAttribute(PreferencesProvider.TYPE, attributes); - PreferencesProviderFactory factory = PreferencesProviderFactory.FACTORY_LOADER.get(type); - return factory.createInstance(entry.getId(), attributes, authenticationProvider); - } - -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/StoreUpgrader.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/StoreUpgrader.java deleted file mode 100644 index 1cadf270d7..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/StoreUpgrader.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.server.configuration.startup; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.model.Broker; - -public abstract class StoreUpgrader -{ - - - private static Map<String, StoreUpgrader> _upgraders = new HashMap<String, StoreUpgrader>(); - - // Note: don't use externally defined constants in upgraders in case they change, the values here MUST stay the same - // no matter what changes are made to the code in the future - - private final static StoreUpgrader UPGRADE_1_0 = new StoreUpgrader("1.0") - { - @Override - protected void doUpgrade(ConfigurationEntryStore store) - { - ConfigurationEntry root = store.getRootEntry(); - Map<String, Collection<ConfigurationEntry>> children = root.getChildren(); - Collection<ConfigurationEntry> vhosts = children.get("VirtualHost"); - Collection<ConfigurationEntry> changed = new HashSet<ConfigurationEntry>(); - for(ConfigurationEntry vhost : vhosts) - { - Map<String, Object> attributes = vhost.getAttributes(); - if(attributes.containsKey("storeType")) - { - attributes = new HashMap<String, Object>(attributes); - attributes.put("type", "STANDARD"); - - changed.add(new ConfigurationEntry(vhost.getId(),vhost.getType(),attributes,vhost.getChildrenIds(),store)); - - } - - } - Map<String, Object> attributes = new HashMap<String, Object>(root.getAttributes()); - attributes.put(Broker.MODEL_VERSION, "1.1"); - changed.add(new ConfigurationEntry(root.getId(),root.getType(),attributes,root.getChildrenIds(),store)); - - store.save(changed.toArray(new ConfigurationEntry[changed.size()])); - - } - }; - - private final static StoreUpgrader UPGRADE_1_1 = new StoreUpgrader("1.1") - { - @Override - protected void doUpgrade(ConfigurationEntryStore store) - { - ConfigurationEntry root = store.getRootEntry(); - - Map<String, Object> attributes = new HashMap<String, Object>(root.getAttributes()); - attributes.put(Broker.MODEL_VERSION, "1.2"); - ConfigurationEntry newRoot = new ConfigurationEntry(root.getId(),root.getType(),attributes,root.getChildrenIds(),store); - - store.save(newRoot); - - } - }; - - - private final static StoreUpgrader UPGRADE_1_2 = new StoreUpgrader("1.2") - { - @Override - protected void doUpgrade(ConfigurationEntryStore store) - { - ConfigurationEntry root = store.getRootEntry(); - Map<String, Collection<ConfigurationEntry>> children = root.getChildren(); - Collection<ConfigurationEntry> changed = new HashSet<ConfigurationEntry>(); - Collection<ConfigurationEntry> keyStores = children.get("KeyStore"); - if(keyStores != null) - { - for(ConfigurationEntry keyStore : keyStores) - { - Map<String, Object> attributes = keyStore.getAttributes(); - if(attributes.containsKey("type")) - { - attributes = new HashMap<String, Object>(attributes); - attributes.put("keyStoreType", attributes.remove("type")); - - changed.add(new ConfigurationEntry(keyStore.getId(),keyStore.getType(),attributes,keyStore.getChildrenIds(),store)); - - } - - } - } - Collection<ConfigurationEntry> trustStores = children.get("TrustStore"); - if(trustStores != null) - { - for(ConfigurationEntry trustStore : trustStores) - { - Map<String, Object> attributes = trustStore.getAttributes(); - if(attributes.containsKey("type")) - { - attributes = new HashMap<String, Object>(attributes); - attributes.put("trustStoreType", attributes.remove("type")); - - changed.add(new ConfigurationEntry(trustStore.getId(),trustStore.getType(),attributes,trustStore.getChildrenIds(),store)); - - } - - } - } - Map<String, Object> attributes = new HashMap<String, Object>(root.getAttributes()); - attributes.put(Broker.MODEL_VERSION, "1.3"); - changed.add(new ConfigurationEntry(root.getId(),root.getType(),attributes,root.getChildrenIds(),store)); - - store.save(changed.toArray(new ConfigurationEntry[changed.size()])); - - } - }; - - final static StoreUpgrader UPGRADE_1_3 = new StoreUpgrader1_3("1.3"); - - protected StoreUpgrader(String version) - { - _upgraders.put(version, this); - } - - public static void upgrade(ConfigurationEntryStore store) - { - StoreUpgrader upgrader = null; - while ((upgrader = _upgraders.get(store.getRootEntry().getAttributes().get(Broker.MODEL_VERSION).toString())) != null) - { - upgrader.doUpgrade(store); - } - } - - protected abstract void doUpgrade(ConfigurationEntryStore store); - - -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/StoreUpgrader1_3.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/StoreUpgrader1_3.java deleted file mode 100644 index 9d30ce754e..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/StoreUpgrader1_3.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; - -@SuppressWarnings("serial") -public final class StoreUpgrader1_3 extends StoreUpgrader -{ - - public static final String VERSION = "1.3"; - - private Map<String, VirtualHostEntryUpgrader> _vhostUpgraderMap = new HashMap<String, VirtualHostEntryUpgrader>() - {{ - put("BDB_HA", new BdbHaVirtualHostUpgrader()); - put("STANDARD", new StandardVirtualHostUpgrader()); - }}; - - StoreUpgrader1_3(String version) - { - super(version); - } - - @Override - protected void doUpgrade(ConfigurationEntryStore store) - { - ConfigurationEntry root = store.getRootEntry(); - Map<String, Collection<ConfigurationEntry>> children = root.getChildren(); - Collection<ConfigurationEntry> vhosts = children.get("VirtualHost"); - Collection<ConfigurationEntry> changed = new ArrayList<ConfigurationEntry>(); - - for (ConfigurationEntry vhost : vhosts) - { - Map<String, Object> attributes = vhost.getAttributes(); - if (attributes.containsKey("configPath")) - { - throw new IllegalConfigurationException("Auto-upgrade of virtual host " + attributes.get("name") + " having XML configuration is not supported. Virtual host configuration file is " + attributes.get("configPath")); - } - - String type = (String) attributes.get("type"); - VirtualHostEntryUpgrader vhostUpgrader = _vhostUpgraderMap.get(type); - if (vhostUpgrader == null) - { - throw new IllegalConfigurationException("Don't know how to perform an upgrade from version " + VERSION - + " for virtualhost type " + type); - } - ConfigurationEntry newVirtualHostConfigurationEntry = vhostUpgrader.upgrade(store, vhost); - changed.add(newVirtualHostConfigurationEntry); - } - - Map<String, Object> attributes = new HashMap<String, Object>(root.getAttributes()); - attributes.put(Broker.MODEL_VERSION, "1.4"); - changed.add(new ConfigurationEntry(root.getId(), root.getType(), attributes, root.getChildrenIds(), store)); - store.save(changed.toArray(new ConfigurationEntry[changed.size()])); - } - - private interface VirtualHostEntryUpgrader - { - ConfigurationEntry upgrade(ConfigurationEntryStore store, ConfigurationEntry vhost); - } - - private class StandardVirtualHostUpgrader implements VirtualHostEntryUpgrader - { - Map<String, AttributesTransformer> _messageStoreAttributeTransformers = new HashMap<String, AttributesTransformer>() - {{ - put("DERBY", new AttributesTransformer(). - addAttributeTransformer("storePath", copyAttribute()). - addAttributeTransformer("storeUnderfullSize", copyAttribute()). - addAttributeTransformer("storeOverfullSize", copyAttribute()). - addAttributeTransformer("storeType", mutateAttributeValue("DERBY"))); - put("MEMORY", new AttributesTransformer(). - addAttributeTransformer("storeType", mutateAttributeValue("Memory"))); - put("BDB", new AttributesTransformer(). - addAttributeTransformer("storePath", copyAttribute()). - addAttributeTransformer("storeUnderfullSize", copyAttribute()). - addAttributeTransformer("storeOverfullSize", copyAttribute()). - addAttributeTransformer("bdbEnvironmentConfig", copyAttribute()). - addAttributeTransformer("storeType", mutateAttributeValue("BDB"))); - put("JDBC", new AttributesTransformer(). - addAttributeTransformer("storePath", mutateAttributeName("connectionURL")). - addAttributeTransformer("connectionURL", copyAttribute()). - addAttributeTransformer("connectionPool", copyAttribute()). - addAttributeTransformer("jdbcBigIntType", copyAttribute()). - addAttributeTransformer("jdbcBytesForBlob", copyAttribute()). - addAttributeTransformer("jdbcBlobType", copyAttribute()). - addAttributeTransformer("jdbcVarbinaryType", copyAttribute()). - addAttributeTransformer("partitionCount", copyAttribute()). - addAttributeTransformer("maxConnectionsPerPartition", copyAttribute()). - addAttributeTransformer("minConnectionsPerPartition", copyAttribute()). - addAttributeTransformer("storeType", mutateAttributeValue("JDBC"))); - }}; - - Map<String, AttributesTransformer> _configurationStoreAttributeTransformers = new HashMap<String, AttributesTransformer>() - {{ - put("DERBY", new AttributesTransformer(). - addAttributeTransformer("configStorePath", mutateAttributeName("storePath")). - addAttributeTransformer("configStoreType", mutateAttributeName("storeType"), mutateAttributeValue("DERBY"))); - put("MEMORY", new AttributesTransformer(). - addAttributeTransformer("configStoreType", mutateAttributeValue("Memory"))); - put("JSON", new AttributesTransformer(). - addAttributeTransformer("configStorePath", mutateAttributeName("storePath")). - addAttributeTransformer("configStoreType", mutateAttributeName("storeType"), mutateAttributeValue("JSON"))); - put("BDB", new AttributesTransformer(). - addAttributeTransformer("configStorePath", mutateAttributeName("storePath")). - addAttributeTransformer("bdbEnvironmentConfig", copyAttribute()). - addAttributeTransformer("configStoreType", mutateAttributeName("storeType"), mutateAttributeValue("BDB"))); - put("JDBC", new AttributesTransformer(). - addAttributeTransformer("configStorePath", mutateAttributeName("connectionURL")). - addAttributeTransformer("configConnectionURL", mutateAttributeName("connectionURL")). - addAttributeTransformer("connectionPool", copyAttribute()). - addAttributeTransformer("jdbcBigIntType", copyAttribute()). - addAttributeTransformer("jdbcBytesForBlob", copyAttribute()). - addAttributeTransformer("jdbcBlobType", copyAttribute()). - addAttributeTransformer("jdbcVarbinaryType", copyAttribute()). - addAttributeTransformer("partitionCount", copyAttribute()). - addAttributeTransformer("maxConnectionsPerPartition", copyAttribute()). - addAttributeTransformer("minConnectionsPerPartition", copyAttribute()). - addAttributeTransformer("configStoreType", mutateAttributeName("storeType"), mutateAttributeValue("JDBC"))); - }}; - - @Override - public ConfigurationEntry upgrade(ConfigurationEntryStore store, ConfigurationEntry vhost) - { - Map<String, Object> attributes = vhost.getAttributes(); - Map<String, Object> newAttributes = new HashMap<String, Object>(attributes); - - String capitalisedStoreType = String.valueOf(attributes.get("storeType")).toUpperCase(); - AttributesTransformer vhAttrsToMessageStoreSettings = _messageStoreAttributeTransformers.get(capitalisedStoreType); - Map<String, Object> messageStoreSettings = null; - if (vhAttrsToMessageStoreSettings != null) - { - messageStoreSettings = vhAttrsToMessageStoreSettings.upgrade(attributes); - } - - if (attributes.containsKey("configStoreType")) - { - String capitaliseConfigStoreType = ((String) attributes.get("configStoreType")).toUpperCase(); - AttributesTransformer vhAttrsToConfigurationStoreSettings = _configurationStoreAttributeTransformers - .get(capitaliseConfigStoreType); - Map<String, Object> configurationStoreSettings = vhAttrsToConfigurationStoreSettings.upgrade(attributes); - newAttributes.keySet().removeAll(vhAttrsToConfigurationStoreSettings.getNamesToBeDeleted()); - newAttributes.put("configurationStoreSettings", configurationStoreSettings); - } - - if (vhAttrsToMessageStoreSettings != null) - { - newAttributes.keySet().removeAll(vhAttrsToMessageStoreSettings.getNamesToBeDeleted()); - newAttributes.put("messageStoreSettings", messageStoreSettings); - } - - return new ConfigurationEntry(vhost.getId(), vhost.getType(), newAttributes, vhost.getChildrenIds(), store); - } - } - - private class BdbHaVirtualHostUpgrader implements VirtualHostEntryUpgrader - { - - private final AttributesTransformer haAttributesTransformer = new AttributesTransformer(). - addAttributeTransformer("storePath", copyAttribute()). - addAttributeTransformer("storeUnderfullSize", copyAttribute()). - addAttributeTransformer("storeOverfullSize", copyAttribute()). - addAttributeTransformer("haNodeName", copyAttribute()). - addAttributeTransformer("haGroupName", copyAttribute()). - addAttributeTransformer("haHelperAddress", copyAttribute()). - addAttributeTransformer("haCoalescingSync", copyAttribute()). - addAttributeTransformer("haNodeAddress", copyAttribute()). - addAttributeTransformer("haDurability", copyAttribute()). - addAttributeTransformer("haDesignatedPrimary", copyAttribute()). - addAttributeTransformer("haReplicationConfig", copyAttribute()). - addAttributeTransformer("bdbEnvironmentConfig", copyAttribute()). - addAttributeTransformer("storeType", removeAttribute()); - - @Override - public ConfigurationEntry upgrade(ConfigurationEntryStore store, ConfigurationEntry vhost) - { - Map<String, Object> attributes = vhost.getAttributes(); - - Map<String, Object> messageStoreSettings = haAttributesTransformer.upgrade(attributes); - - Map<String, Object> newAttributes = new HashMap<String, Object>(attributes); - newAttributes.keySet().removeAll(haAttributesTransformer.getNamesToBeDeleted()); - newAttributes.put("messageStoreSettings", messageStoreSettings); - - return new ConfigurationEntry(vhost.getId(), vhost.getType(), newAttributes, vhost.getChildrenIds(), store); - } - } - - private class AttributesTransformer - { - private final Map<String, List<AttributeTransformer>> _transformers = new HashMap<String, List<AttributeTransformer>>(); - private Set<String> _namesToBeDeleted = new HashSet<String>(); - - public AttributesTransformer addAttributeTransformer(String string, AttributeTransformer... attributeTransformers) - { - _transformers.put(string, Arrays.asList(attributeTransformers)); - return this; - } - - public Map<String, Object> upgrade(Map<String, Object> attributes) - { - Map<String, Object> settings = new HashMap<String, Object>(); - for (Entry<String, List<AttributeTransformer>> entry : _transformers.entrySet()) - { - String attributeName = entry.getKey(); - if (attributes.containsKey(attributeName)) - { - Object attributeValue = attributes.get(attributeName); - MutatableEntry newEntry = new MutatableEntry(attributeName, attributeValue); - - List<AttributeTransformer> transformers = entry.getValue(); - for (AttributeTransformer attributeTransformer : transformers) - { - newEntry = attributeTransformer.transform(newEntry); - if (newEntry == null) - { - break; - } - } - if (newEntry != null) - { - settings.put(newEntry.getKey(), newEntry.getValue()); - } - - _namesToBeDeleted.add(attributeName); - } - } - return settings; - } - - public Set<String> getNamesToBeDeleted() - { - return _namesToBeDeleted; - } - } - - private AttributeTransformer copyAttribute() - { - return CopyAttribute.INSTANCE; - } - - private AttributeTransformer removeAttribute() - { - return RemoveAttribute.INSTANCE; - } - - private AttributeTransformer mutateAttributeValue(Object newValue) - { - return new MutateAttributeValue(newValue); - } - - private AttributeTransformer mutateAttributeName(String newName) - { - return new MutateAttributeName(newName); - } - - private interface AttributeTransformer - { - MutatableEntry transform(MutatableEntry entry); - } - - private static class CopyAttribute implements AttributeTransformer - { - private static final CopyAttribute INSTANCE = new CopyAttribute(); - - private CopyAttribute() - { - } - - @Override - public MutatableEntry transform(MutatableEntry entry) - { - return entry; - } - } - - private static class RemoveAttribute implements AttributeTransformer - { - private static final RemoveAttribute INSTANCE = new RemoveAttribute(); - - private RemoveAttribute() - { - } - - @Override - public MutatableEntry transform(MutatableEntry entry) - { - return null; - } - } - - private class MutateAttributeName implements AttributeTransformer - { - private final String _newName; - - public MutateAttributeName(String newName) - { - _newName = newName; - } - - @Override - public MutatableEntry transform(MutatableEntry entry) - { - entry.setKey(_newName); - return entry; - } - } - - private static class MutateAttributeValue implements AttributeTransformer - { - private final Object _newValue; - - public MutateAttributeValue(Object newValue) - { - _newValue = newValue; - } - - @Override - public MutatableEntry transform(MutatableEntry entry) - { - entry.setValue(_newValue); - return entry; - } - } - - private static class MutatableEntry - { - private String _key; - private Object _value; - - public MutatableEntry(String key, Object value) - { - _key = key; - _value = value; - } - - public String getKey() - { - return _key; - } - - public void setKey(String key) - { - _key = key; - } - - public Object getValue() - { - return _value; - } - - public void setValue(Object value) - { - _value = value; - } - } - -}
\ No newline at end of file diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/KeyStoreRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/UnresolvedObjectWithParents.java index 8efedd37b5..4b2655e8c5 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/KeyStoreRecoverer.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/UnresolvedObjectWithParents.java @@ -20,21 +20,11 @@ */ package org.apache.qpid.server.configuration.startup; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.adapter.KeyStoreAdapter; +import org.apache.qpid.server.store.UnresolvedObject; -public class KeyStoreRecoverer implements ConfiguredObjectRecoverer<KeyStore> +public interface UnresolvedObjectWithParents<X> extends UnresolvedObject<X> { - @Override - public KeyStore create(RecovererProvider recovererProvider, ConfigurationEntry entry, ConfiguredObject... parents) - { - Broker broker = RecovererHelper.verifyOnlyBrokerIsParent(parents); - return new KeyStoreAdapter(entry.getId(), broker, entry.getAttributes()); - } - + void resolvedParent(final UnresolvedParentDependency<?> unresolvedParentDependency, + final ConfiguredObject<?> dependency); } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/UnresolvedParentDependency.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/UnresolvedParentDependency.java new file mode 100644 index 0000000000..ae10106270 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/UnresolvedParentDependency.java @@ -0,0 +1,61 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.configuration.startup; + +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.UnresolvedDependency; + +import java.util.UUID; + +class UnresolvedParentDependency<X extends ConfiguredObject<X>> implements UnresolvedDependency<X> +{ + private final UUID _id; + private final String _type; + private final UnresolvedObjectWithParents _unresolvedObject; + + public UnresolvedParentDependency(final UnresolvedObjectWithParents unresolvedObject, + final String type, + final ConfiguredObjectRecord record) + { + _type = type; + _id = record.getId(); + _unresolvedObject = unresolvedObject; + } + + @Override + public UUID getId() + { + return _id; + } + + @Override + public String getType() + { + return _type; + } + + @Override + public void resolve(final X dependency) + { + _unresolvedObject.resolvedParent(this, dependency); + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/VirtualHostRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/VirtualHostRecoverer.java deleted file mode 100644 index 4f863adfb5..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/VirtualHostRecoverer.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.adapter.VirtualHostAdapter; -import org.apache.qpid.server.stats.StatisticsGatherer; - -public class VirtualHostRecoverer implements ConfiguredObjectRecoverer<VirtualHost> -{ - private StatisticsGatherer _brokerStatisticsGatherer; - - public VirtualHostRecoverer(StatisticsGatherer brokerStatisticsGatherer) - { - super(); - _brokerStatisticsGatherer = brokerStatisticsGatherer; - } - - @Override - public VirtualHost create(RecovererProvider recovererProvider, ConfigurationEntry entry, ConfiguredObject... parents) - { - Broker broker = RecovererHelper.verifyOnlyBrokerIsParent(parents); - - return new VirtualHostAdapter(entry.getId(), entry.getAttributes(), broker, _brokerStatisticsGatherer, broker.getTaskExecutor()); - } - -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStore.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStore.java index d6c46ee7d9..59f248c9f5 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStore.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStore.java @@ -21,24 +21,32 @@ package org.apache.qpid.server.configuration.store; import java.io.File; -import java.util.HashMap; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.Map; import java.util.UUID; import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.StoreException; +import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; public class JsonConfigurationEntryStore extends MemoryConfigurationEntryStore { public static final String STORE_TYPE = "json"; + private final ConfiguredObject<?> _parentObject; private File _storeFile; - public JsonConfigurationEntryStore(String storeLocation, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties) + public JsonConfigurationEntryStore(ConfiguredObject<?> parentObject, DurableConfigurationStore initialStore, boolean overwrite, Map<String, String> configProperties) { super(configProperties); + _parentObject = parentObject; + String storeLocation = (String) parentObject.getAttribute("storePath"); _storeFile = new File(storeLocation); if(_storeFile.isDirectory()) @@ -58,7 +66,10 @@ public class JsonConfigurationEntryStore extends MemoryConfigurationEntryStore { initialiseStore(_storeFile, initialStore); } - load(getConfigurationEntryStoreUtil().fileToURL(_storeFile)); + else + { + load(getConfigurationEntryStoreUtil().fileToURL(_storeFile)); + } if(isGeneratedObjectIdDuringLoad()) { saveAsTree(_storeFile); @@ -66,9 +77,9 @@ public class JsonConfigurationEntryStore extends MemoryConfigurationEntryStore } @Override - public synchronized UUID[] remove(UUID... entryIds) + public synchronized UUID[] remove(final ConfiguredObjectRecord... records) { - UUID[] removedIds = super.remove(entryIds); + UUID[] removedIds = super.remove(records); if (removedIds.length > 0) { saveAsTree(_storeFile); @@ -103,7 +114,7 @@ public class JsonConfigurationEntryStore extends MemoryConfigurationEntryStore return "JsonConfigurationEntryStore [_storeFile=" + _storeFile + ", _rootId=" + getRootEntry().getId() + "]"; } - private void initialiseStore(File storeFile, ConfigurationEntryStore initialStore) + private void initialiseStore(File storeFile, DurableConfigurationStore initialStore) { createFileIfNotExist(storeFile); if (initialStore == null) @@ -112,17 +123,34 @@ public class JsonConfigurationEntryStore extends MemoryConfigurationEntryStore } else { - if (initialStore instanceof MemoryConfigurationEntryStore && initialStore.getStoreLocation() != null) - { - getConfigurationEntryStoreUtil().copyInitialConfigFile(initialStore.getStoreLocation(), storeFile); - } - else + final Collection<ConfiguredObjectRecord> records = new ArrayList<ConfiguredObjectRecord>(); + final ConfiguredObjectRecordHandler replayHandler = new ConfiguredObjectRecordHandler() { - ConfigurationEntry rootEntry = initialStore.getRootEntry(); - Map<UUID, ConfigurationEntry> entries = new HashMap<UUID, ConfigurationEntry>(); - copyEntry(rootEntry.getId(), initialStore, entries); - saveAsTree(rootEntry.getId(), entries, getObjectMapper(), storeFile, getVersion()); - } + private int _configVersion; + @Override + public void begin(final int configVersion) + { + _configVersion = configVersion; + } + + @Override + public boolean handle(ConfiguredObjectRecord record) + { + records.add(record); + return true; + } + + @Override + public int end() + { + return _configVersion; + } + }; + + initialStore.openConfigurationStore(_parentObject, Collections.<String,Object>emptyMap()); + initialStore.visitConfiguredObjectRecords(replayHandler); + + update(true, records.toArray(new ConfiguredObjectRecord[records.size()])); } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandler.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandler.java index 7144c179ca..cdf44822ef 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandler.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandler.java @@ -20,25 +20,32 @@ */ package org.apache.qpid.server.configuration.store; +import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.log4j.Logger; + import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.State; import org.apache.qpid.server.model.VirtualHost; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.ConfiguredObjectRecordImpl; +import org.apache.qpid.server.store.DurableConfigurationStore; +import org.apache.qpid.server.store.StoreException; +import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; import org.apache.qpid.server.util.MapValueConverter; -public class ManagementModeStoreHandler implements ConfigurationEntryStore +public class ManagementModeStoreHandler implements DurableConfigurationStore { private static final Logger LOGGER = Logger.getLogger(ManagementModeStoreHandler.class); @@ -49,141 +56,230 @@ public class ManagementModeStoreHandler implements ConfigurationEntryStore private static final Object MANAGEMENT_MODE_AUTH_PROVIDER = "mm-auth"; - private final ConfigurationEntryStore _store; - private final Map<UUID, ConfigurationEntry> _cliEntries; - private final Map<UUID, Object> _quiescedEntries; - private final UUID _rootId; + private final DurableConfigurationStore _store; + private Map<UUID, ConfiguredObjectRecord> _cliEntries; + private final Map<UUID, Object> _quiescedEntriesOriginalState; + private final BrokerOptions _options; + private ConfiguredObject<?> _parent; + private HashMap<UUID, ConfiguredObjectRecord> _records; - public ManagementModeStoreHandler(ConfigurationEntryStore store, BrokerOptions options) + public ManagementModeStoreHandler(DurableConfigurationStore store, + BrokerOptions options) { - ConfigurationEntry storeRoot = store.getRootEntry(); + _options = options; _store = store; - _rootId = storeRoot.getId(); - _cliEntries = createPortsFromCommandLineOptions(options); - _quiescedEntries = quiesceEntries(storeRoot, options); + _quiescedEntriesOriginalState = quiesceEntries(options); } @Override - public ConfigurationEntry getRootEntry() + public void openConfigurationStore(final ConfiguredObject<?> parent, final Map<String, Object> storeSettings) + throws StoreException { - return getEntry(_rootId); - } + _parent = parent; + _store.openConfigurationStore(parent,storeSettings); - @Override - public ConfigurationEntry getEntry(UUID id) - { - synchronized (_store) + + _records = new HashMap<UUID, ConfiguredObjectRecord>(); + final ConfiguredObjectRecordHandler localRecoveryHandler = new ConfiguredObjectRecordHandler() { - if (_cliEntries.containsKey(id)) - { - return _cliEntries.get(id); - } + private int _version; + private boolean _quiesceRmiPort = _options.getManagementModeRmiPortOverride() > 0; + private boolean _quiesceJmxPort = _options.getManagementModeJmxPortOverride() > 0; + private boolean _quiesceHttpPort = _options.getManagementModeHttpPortOverride() > 0; - ConfigurationEntry entry = _store.getEntry(id); - if (_quiescedEntries.containsKey(id)) + @Override + public void begin(final int configVersion) { - entry = createEntryWithState(entry, State.QUIESCED); + _version = configVersion; } - else if (id == _rootId) - { - entry = createRootWithCLIEntries(entry); - } - return entry; - } - } - - @Override - public void save(ConfigurationEntry... entries) - { - synchronized (_store) - { - ConfigurationEntry[] entriesToSave = new ConfigurationEntry[entries.length]; - for (int i = 0; i < entries.length; i++) + @Override + public boolean handle(final ConfiguredObjectRecord object) { - ConfigurationEntry entry = entries[i]; - UUID id = entry.getId(); - if (_cliEntries.containsKey(id)) + String entryType = object.getType(); + Map<String, Object> attributes = object.getAttributes(); + boolean quiesce = false; + if (VIRTUAL_HOST_TYPE.equals(entryType) && _options.isManagementModeQuiesceVirtualHosts()) { - throw new IllegalConfigurationException("Cannot save configuration provided as command line argument:" - + entry); + quiesce = true; } - else if (_quiescedEntries.containsKey(id)) + else if (PORT_TYPE.equals(entryType)) { - // save entry with the original state - entry = createEntryWithState(entry, _quiescedEntries.get(id)); + if (attributes == null) + { + throw new IllegalConfigurationException("Port attributes are not set in " + object); + } + Set<Protocol> protocols = getPortProtocolsAttribute(attributes); + if (protocols == null) + { + quiesce = true; + } + else + { + for (Protocol protocol : protocols) + { + switch (protocol) + { + case JMX_RMI: + quiesce = _quiesceJmxPort || _quiesceRmiPort ; + break; + case RMI: + quiesce = _quiesceRmiPort; + break; + case HTTP: + quiesce = _quiesceHttpPort; + break; + default: + quiesce = true; + } + } + } } - else if (_rootId.equals(id)) + if (quiesce) { - // save root without command line entries - Set<UUID> childrenIds = new HashSet<UUID>(entry.getChildrenIds()); - if (!_cliEntries.isEmpty()) + if (LOGGER.isDebugEnabled()) { - childrenIds.removeAll(_cliEntries.keySet()); + LOGGER.debug("Management mode quiescing entry " + object); } - HashMap<String, Object> attributes = new HashMap<String, Object>(entry.getAttributes()); - entry = new ConfigurationEntry(entry.getId(), entry.getType(), attributes, childrenIds, this); + + // save original state + _quiescedEntriesOriginalState.put(object.getId(), attributes.get(ATTRIBUTE_STATE)); + Map<String,Object> modifiedAttributes = new HashMap<String, Object>(attributes); + modifiedAttributes.put(ATTRIBUTE_STATE, State.QUIESCED); + ConfiguredObjectRecord record = new ConfiguredObjectRecordImpl(object.getId(), object.getType(), modifiedAttributes, object.getParents()); + _records.put(record.getId(), record); + } - entriesToSave[i] = entry; + else + { + _records.put(object.getId(), object); + } + return true; + } + + + @Override + public int end() + { + return _version; } + }; + + - _store.save(entriesToSave); + + _store.visitConfiguredObjectRecords(localRecoveryHandler); + + _cliEntries = createPortsFromCommandLineOptions(_options); + + for(ConfiguredObjectRecord entry : _cliEntries.values()) + { + _records.put(entry.getId(),entry); } + + } @Override - public UUID[] remove(UUID... entryIds) + public void visitConfiguredObjectRecords(final ConfiguredObjectRecordHandler recoveryHandler) throws StoreException { - synchronized (_store) + + + recoveryHandler.begin(0); + + for(ConfiguredObjectRecord record : _records.values()) { - for (UUID id : entryIds) + if(!recoveryHandler.handle(record)) { - if (_cliEntries.containsKey(id)) - { - throw new IllegalConfigurationException("Cannot change configuration for command line entry:" - + _cliEntries.get(id)); - } + break; } - UUID[] result = _store.remove(entryIds); - for (UUID id : entryIds) - { - if (_quiescedEntries.containsKey(id)) - { - _quiescedEntries.remove(id); - } - } - return result; } + recoveryHandler.end(); } + @Override - public void copyTo(String copyLocation) + public void create(final ConfiguredObjectRecord object) { synchronized (_store) { - _store.copyTo(copyLocation); + _store.create(object); } + _records.put(object.getId(), object); } @Override - public String getStoreLocation() + public void update(final boolean createIfNecessary, final ConfiguredObjectRecord... records) throws StoreException { - return _store.getStoreLocation(); + synchronized (_store) + { + + Collection<ConfiguredObjectRecord> actualUpdates = new ArrayList<ConfiguredObjectRecord>(); + + for(ConfiguredObjectRecord record : records) + { + if (_cliEntries.containsKey(record.getId())) + { + throw new IllegalConfigurationException("Cannot save configuration provided as command line argument:" + + record); + } + else if (_quiescedEntriesOriginalState.containsKey(record.getId())) + { + // save entry with the original state + record = createEntryWithState(record, _quiescedEntriesOriginalState.get(record.getId())); + } + actualUpdates.add(record); + } + _store.update(createIfNecessary, actualUpdates.toArray(new ConfiguredObjectRecord[actualUpdates.size()])); + } + for(ConfiguredObjectRecord record : records) + { + _records.put(record.getId(), record); + } } @Override - public int getVersion() + public void closeConfigurationStore() throws StoreException { - return _store.getVersion(); } + @Override - public String getType() + public synchronized UUID[] remove(final ConfiguredObjectRecord... records) { - return _store.getType(); + synchronized (_store) + { + UUID[] idsToRemove = new UUID[records.length]; + for(int i = 0; i < records.length; i++) + { + idsToRemove[i] = records[i].getId(); + } + + for (UUID id : idsToRemove) + { + if (_cliEntries.containsKey(id)) + { + throw new IllegalConfigurationException("Cannot change configuration for command line entry:" + + _cliEntries.get(id)); + } + } + UUID[] result = _store.remove(records); + for (UUID id : idsToRemove) + { + if (_quiescedEntriesOriginalState.containsKey(id)) + { + _quiescedEntriesOriginalState.remove(id); + } + } + for(ConfiguredObjectRecord record : records) + { + _records.remove(record.getId()); + } + return result; + } } - private Map<UUID, ConfigurationEntry> createPortsFromCommandLineOptions(BrokerOptions options) + private Map<UUID, ConfiguredObjectRecord> createPortsFromCommandLineOptions(BrokerOptions options) { int managementModeRmiPortOverride = options.getManagementModeRmiPortOverride(); if (managementModeRmiPortOverride < 0) @@ -200,32 +296,34 @@ public class ManagementModeStoreHandler implements ConfigurationEntryStore { throw new IllegalConfigurationException("Invalid http port is specified: " + managementModeHttpPortOverride); } - Map<UUID, ConfigurationEntry> cliEntries = new HashMap<UUID, ConfigurationEntry>(); + Map<UUID, ConfiguredObjectRecord> cliEntries = new HashMap<UUID, ConfiguredObjectRecord>(); if (managementModeRmiPortOverride != 0) { - ConfigurationEntry entry = createCLIPortEntry(managementModeRmiPortOverride, Protocol.RMI); + ConfiguredObjectRecord entry = createCLIPortEntry(managementModeRmiPortOverride, Protocol.RMI); cliEntries.put(entry.getId(), entry); if (managementModeJmxPortOverride == 0) { - ConfigurationEntry connectorEntry = createCLIPortEntry(managementModeRmiPortOverride + 100, Protocol.JMX_RMI); + ConfiguredObjectRecord connectorEntry = createCLIPortEntry(managementModeRmiPortOverride + 100, Protocol.JMX_RMI); cliEntries.put(connectorEntry.getId(), connectorEntry); } } if (managementModeJmxPortOverride != 0) { - ConfigurationEntry entry = createCLIPortEntry(managementModeJmxPortOverride, Protocol.JMX_RMI); + ConfiguredObjectRecord entry = createCLIPortEntry(managementModeJmxPortOverride, Protocol.JMX_RMI); cliEntries.put(entry.getId(), entry); } if (managementModeHttpPortOverride != 0) { - ConfigurationEntry entry = createCLIPortEntry(managementModeHttpPortOverride, Protocol.HTTP); + ConfiguredObjectRecord entry = createCLIPortEntry(managementModeHttpPortOverride, Protocol.HTTP); cliEntries.put(entry.getId(), entry); } return cliEntries; } - private ConfigurationEntry createCLIPortEntry(int port, Protocol protocol) + private ConfiguredObjectRecord createCLIPortEntry(int port, Protocol protocol) { + ConfiguredObjectRecord parent = findBroker(); + Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.PORT, port); attributes.put(Port.PROTOCOLS, Collections.singleton(protocol)); @@ -234,8 +332,8 @@ public class ManagementModeStoreHandler implements ConfigurationEntryStore { attributes.put(Port.AUTHENTICATION_PROVIDER, MANAGEMENT_MODE_AUTH_PROVIDER); } - ConfigurationEntry portEntry = new ConfigurationEntry(UUID.randomUUID(), PORT_TYPE, attributes, - Collections.<UUID> emptySet(), this); + ConfiguredObjectRecord portEntry = new ConfiguredObjectRecordImpl(UUID.randomUUID(), PORT_TYPE, attributes, + Collections.singletonMap(parent.getType(),parent)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Add management mode port configuration " + portEntry + " for port " + port + " and protocol " @@ -244,79 +342,98 @@ public class ManagementModeStoreHandler implements ConfigurationEntryStore return portEntry; } - private ConfigurationEntry createRootWithCLIEntries(ConfigurationEntry storeRoot) + private ConfiguredObjectRecord findBroker() { - Set<UUID> childrenIds = new HashSet<UUID>(storeRoot.getChildrenIds()); - if (!_cliEntries.isEmpty()) + for(ConfiguredObjectRecord record : _records.values()) { - childrenIds.addAll(_cliEntries.keySet()); + if(record.getType().equals(Broker.class.getSimpleName())) + { + return record; + } } - ConfigurationEntry root = new ConfigurationEntry(storeRoot.getId(), storeRoot.getType(), new HashMap<String, Object>( - storeRoot.getAttributes()), childrenIds, this); - return root; + return null; } - private Map<UUID, Object> quiesceEntries(ConfigurationEntry storeRoot, BrokerOptions options) + + private Map<UUID, Object> quiesceEntries(final BrokerOptions options) { - Map<UUID, Object> quiescedEntries = new HashMap<UUID, Object>(); - Set<UUID> childrenIds; - int managementModeRmiPortOverride = options.getManagementModeRmiPortOverride(); - int managementModeJmxPortOverride = options.getManagementModeJmxPortOverride(); - int managementModeHttpPortOverride = options.getManagementModeHttpPortOverride(); - childrenIds = storeRoot.getChildrenIds(); - for (UUID id : childrenIds) + final Map<UUID, Object> quiescedEntries = new HashMap<UUID, Object>(); + final int managementModeRmiPortOverride = options.getManagementModeRmiPortOverride(); + final int managementModeJmxPortOverride = options.getManagementModeJmxPortOverride(); + final int managementModeHttpPortOverride = options.getManagementModeHttpPortOverride(); + + _store.visitConfiguredObjectRecords(new ConfiguredObjectRecordHandler() { - ConfigurationEntry entry = _store.getEntry(id); - String entryType = entry.getType(); - Map<String, Object> attributes = entry.getAttributes(); - boolean quiesce = false; - if (VIRTUAL_HOST_TYPE.equals(entryType) && options.isManagementModeQuiesceVirtualHosts()) + @Override + public void begin(final int configVersion) { - quiesce = true; + } - else if (PORT_TYPE.equals(entryType)) + + @Override + public boolean handle(final ConfiguredObjectRecord entry) { - if (attributes == null) - { - throw new IllegalConfigurationException("Port attributes are not set in " + entry); - } - Set<Protocol> protocols = getPortProtocolsAttribute(attributes); - if (protocols == null) + String entryType = entry.getType(); + Map<String, Object> attributes = entry.getAttributes(); + boolean quiesce = false; + if (VIRTUAL_HOST_TYPE.equals(entryType) && options.isManagementModeQuiesceVirtualHosts()) { quiesce = true; } - else + else if (PORT_TYPE.equals(entryType)) { - for (Protocol protocol : protocols) + if (attributes == null) + { + throw new IllegalConfigurationException("Port attributes are not set in " + entry); + } + Set<Protocol> protocols = getPortProtocolsAttribute(attributes); + if (protocols == null) { - switch (protocol) + quiesce = true; + } + else + { + for (Protocol protocol : protocols) { - case JMX_RMI: - quiesce = managementModeJmxPortOverride > 0 || managementModeRmiPortOverride > 0; - break; - case RMI: - quiesce = managementModeRmiPortOverride > 0; - break; - case HTTP: - quiesce = managementModeHttpPortOverride > 0; - break; - default: - quiesce = true; + switch (protocol) + { + case JMX_RMI: + quiesce = managementModeJmxPortOverride > 0 || managementModeRmiPortOverride > 0; + break; + case RMI: + quiesce = managementModeRmiPortOverride > 0; + break; + case HTTP: + quiesce = managementModeHttpPortOverride > 0; + break; + default: + quiesce = true; + } } } } - } - if (quiesce) - { - if (LOGGER.isDebugEnabled()) + if (quiesce) { - LOGGER.debug("Management mode quiescing entry " + entry); + if (LOGGER.isDebugEnabled()) + { + LOGGER.debug("Management mode quiescing entry " + entry); + } + + // save original state + quiescedEntries.put(entry.getId(), attributes.get(ATTRIBUTE_STATE)); } + return true; + } - // save original state - quiescedEntries.put(entry.getId(), attributes.get(ATTRIBUTE_STATE)); + + @Override + public int end() + { + return 0; } - } + }); + + return quiescedEntries; } @@ -330,7 +447,7 @@ public class ManagementModeStoreHandler implements ConfigurationEntryStore return MapValueConverter.getEnumSetAttribute(Port.PROTOCOLS, attributes, Protocol.class); } - private ConfigurationEntry createEntryWithState(ConfigurationEntry entry, Object state) + private ConfiguredObjectRecord createEntryWithState(ConfiguredObjectRecord entry, Object state) { Map<String, Object> attributes = new HashMap<String, Object>(entry.getAttributes()); if (state == null) @@ -341,13 +458,7 @@ public class ManagementModeStoreHandler implements ConfigurationEntryStore { attributes.put(ATTRIBUTE_STATE, state); } - Set<UUID> originalChildren = entry.getChildrenIds(); - Set<UUID> children = null; - if (originalChildren != null) - { - children = new HashSet<UUID>(originalChildren); - } - return new ConfigurationEntry(entry.getId(), entry.getType(), attributes, children, entry.getStore()); + return new ConfiguredObjectRecordImpl(entry.getId(), entry.getType(), attributes, entry.getParents()); } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStore.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStore.java index 7b03946680..d534814410 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStore.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStore.java @@ -40,23 +40,29 @@ import java.util.TreeMap; import java.util.TreeSet; import java.util.UUID; +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.JsonProcessingException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.SerializationConfig; +import org.codehaus.jackson.node.ArrayNode; + import org.apache.qpid.server.configuration.ConfigurationEntry; +import org.apache.qpid.server.configuration.ConfigurationEntryImpl; import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.Model; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.server.model.UUIDGenerator; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.StoreException; +import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; import org.apache.qpid.util.Strings; import org.apache.qpid.util.Strings.ChainedResolver; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.JsonNode; -import org.codehaus.jackson.JsonParser; -import org.codehaus.jackson.JsonProcessingException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.codehaus.jackson.node.ArrayNode; public class MemoryConfigurationEntryStore implements ConfigurationEntryStore { @@ -80,6 +86,7 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore private boolean _generatedObjectIdDuringLoad; private ChainedResolver _resolver; + private ConfiguredObject<?> _parent; protected MemoryConfigurationEntryStore(Map<String, String> configProperties) { @@ -105,22 +112,49 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore } } - public MemoryConfigurationEntryStore(String initialStoreLocation, ConfigurationEntryStore initialStore, Map<String, String> configProperties) + public MemoryConfigurationEntryStore(ConfiguredObject parentObject, String initialStoreLocation, ConfigurationEntryStore initialStore, Map<String, String> configProperties) { this(configProperties); if (initialStore == null && (initialStoreLocation == null || "".equals(initialStoreLocation) )) { throw new IllegalConfigurationException("Cannot instantiate the memory broker store as neither initial store nor initial store location is provided"); } - + _parent = parentObject; if (initialStore != null) { if (initialStore instanceof MemoryConfigurationEntryStore) { _storeLocation = initialStore.getStoreLocation(); } - _rootId = initialStore.getRootEntry().getId(); - copyEntry(_rootId, initialStore, _entries); + final Collection<ConfiguredObjectRecord> records = new ArrayList<ConfiguredObjectRecord>(); + final ConfiguredObjectRecordHandler replayHandler = new ConfiguredObjectRecordHandler() + { + private int _configVersion; + @Override + public void begin(final int configVersion) + { + _configVersion = configVersion; + } + + @Override + public boolean handle(ConfiguredObjectRecord record) + { + records.add(record); + return true; + } + + @Override + public int end() + { + return _configVersion; + } + }; + + initialStore.openConfigurationStore(parentObject, Collections.<String,Object>emptyMap()); + initialStore.visitConfiguredObjectRecords(replayHandler); + + update(true, records.toArray(new ConfiguredObjectRecord[records.size()])); + } else { @@ -129,9 +163,16 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore } } + @Override - public synchronized UUID[] remove(UUID... entryIds) + public synchronized UUID[] remove(final ConfiguredObjectRecord... records) { + UUID[] entryIds = new UUID[records.length]; + for(int i = 0; i < records.length; i++) + { + entryIds[i] = records[i].getId(); + } + List<UUID> removedIds = new ArrayList<UUID>(); for (UUID uuid : entryIds) { @@ -151,7 +192,7 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore { Set<UUID> children = new HashSet<UUID>(entry.getChildrenIds()); children.remove(uuid); - ConfigurationEntry referral = new ConfigurationEntry(entry.getId(), entry.getType(), + ConfigurationEntry referral = new ConfigurationEntryImpl(entry.getId(), entry.getType(), entry.getAttributes(), children, this); _entries.put(entry.getId(), referral); } @@ -163,19 +204,16 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore return removedIds.toArray(new UUID[removedIds.size()]); } - @Override public synchronized void save(ConfigurationEntry... entries) { replaceEntries(entries); } - @Override public ConfigurationEntry getRootEntry() { return getEntry(_rootId); } - @Override public synchronized ConfigurationEntry getEntry(UUID id) { return _entries.get(id); @@ -184,7 +222,7 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore /** * Copies the store into the given location * - * @param target location to copy store into + * @param copyLocation location to copy store into * @throws IllegalConfigurationException if store cannot be copied into given location */ public void copyTo(String copyLocation) @@ -221,6 +259,191 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore return "MemoryConfigurationEntryStore [_rootId=" + _rootId + "]"; } + @Override + public synchronized void create(final ConfiguredObjectRecord object) + { + Collection<ConfigurationEntry> entriesToSave = new ArrayList<ConfigurationEntry>(); + entriesToSave.add(new ConfigurationEntryImpl(object.getId(), object.getType(), object.getAttributes(), Collections.<UUID>emptySet(), this)); + for(ConfiguredObjectRecord parent : object.getParents().values()) + { + ConfigurationEntry parentEntry = getEntry(parent.getId()); + Set<UUID> children = new HashSet<UUID>(parentEntry.getChildrenIds()); + children.add(object.getId()); + ConfigurationEntry replacementEntry = new ConfigurationEntryImpl(parentEntry.getId(), parent.getType(), parent.getAttributes(), children, this); + entriesToSave.add(replacementEntry); + } + save(entriesToSave.toArray(new ConfigurationEntry[entriesToSave.size()])); + } + + @Override + public synchronized void update(final boolean createIfNecessary, final ConfiguredObjectRecord... records) throws StoreException + { + + Map<UUID, ConfigurationEntry> updates = new HashMap<UUID, ConfigurationEntry>(); + + + for (ConfiguredObjectRecord record : records) + { + Set<UUID> currentChildren; + + final ConfigurationEntry entry = getEntry(record.getId()); + + if (entry == null) + { + if (createIfNecessary) + { + currentChildren = new HashSet<UUID>(); + } + else + { + throw new StoreException("Cannot update record with id " + + record.getId() + + " as it does not exist"); + } + } + else + { + currentChildren = new HashSet<UUID>(entry.getChildrenIds()); + } + + updates.put(record.getId(), + new ConfigurationEntryImpl(record.getId(), + record.getType(), + record.getAttributes(), + currentChildren, + this)); + } + + for (ConfiguredObjectRecord record : records) + { + for (ConfiguredObjectRecord parent : record.getParents().values()) + { + ConfigurationEntry existingParentEntry = updates.get(parent.getId()); + if(existingParentEntry == null) + { + existingParentEntry = getEntry(parent.getId()); + if (existingParentEntry == null) + { + if (parent.getType().equals(SystemContext.class.getSimpleName())) + { + if(_rootId == null) + { + _rootId = record.getId(); + } + continue; + } + throw new StoreException("Unknown parent of type " + + parent.getType() + + " with id " + + parent.getId()); + } + } + Set<UUID> children = new HashSet<UUID>(existingParentEntry.getChildrenIds()); + if(!children.contains(record.getId())) + { + children.add(record.getId()); + ConfigurationEntry newParentEntry = new ConfigurationEntryImpl(existingParentEntry.getId(), existingParentEntry.getType(), existingParentEntry.getAttributes(), children, this); + updates.put(newParentEntry.getId(), newParentEntry); + } + + } + + } + save(updates.values().toArray(new ConfigurationEntry[updates.size()])); + } + + @Override + public void closeConfigurationStore() throws StoreException + { + } + + @Override + public void openConfigurationStore(final ConfiguredObject<?> parent, final Map<String, Object> storeSettings) + throws StoreException + { + _parent = parent; + } + + @Override + public void visitConfiguredObjectRecords(final ConfiguredObjectRecordHandler recoveryHandler) throws StoreException + { + + recoveryHandler.begin(0); + + final Map<UUID,Map<String,UUID>> parentMap = new HashMap<UUID, Map<String, UUID>>(); + + for(ConfigurationEntry entry : _entries.values()) + { + if(entry.getChildrenIds() != null) + { + for(UUID childId : entry.getChildrenIds()) + { + Map<String, UUID> parents = parentMap.get(childId); + if(parents == null) + { + parents = new HashMap<String, UUID>(); + parentMap.put(childId, parents); + } + parents.put(entry.getType(), entry.getId()); + } + } + } + + final Map<UUID, ConfiguredObjectRecord> records = new HashMap<UUID, ConfiguredObjectRecord>(); + for(final ConfigurationEntry entry : _entries.values()) + { + records.put(entry.getId(), new ConfiguredObjectRecord() + { + @Override + public UUID getId() + { + return entry.getId(); + } + + @Override + public String getType() + { + return entry.getType(); + } + + @Override + public Map<String, Object> getAttributes() + { + return entry.getAttributes(); + } + + @Override + public Map<String, ConfiguredObjectRecord> getParents() + { + Map<String,ConfiguredObjectRecord> parents = new HashMap<String, ConfiguredObjectRecord>(); + Map<String, UUID> calculatedParents = parentMap.get(getId()); + if(calculatedParents != null) + { + for(Map.Entry<String,UUID> entry : calculatedParents.entrySet()) + { + parents.put(entry.getKey(), records.get(entry.getValue())); + } + } + else + { + ConfiguredObjectRecord parent = _parent.asObjectRecord(); + parents.put(parent.getType(),parent); + } + return parents; + } + }); + } + for(ConfiguredObjectRecord record : records.values()) + { + if(!recoveryHandler.handle(record)) + { + break; + } + } + recoveryHandler.end(); + + } + protected boolean replaceEntries(ConfigurationEntry... entries) { boolean anySaved = false; @@ -336,31 +559,6 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore } } - protected void copyEntry(UUID entryId, ConfigurationEntryStore initialStore, Map<UUID,ConfigurationEntry> entries) - { - ConfigurationEntry entry = initialStore.getEntry(entryId); - if (entry != null) - { - if (entries.containsKey(entryId)) - { - throw new IllegalConfigurationException("Duplicate id is found: " + entryId - + "! The following configuration entries have the same id: " + entries.get(entryId) + ", " + entry); - } - - Set<UUID> children = entry.getChildrenIds(); - Set<UUID> childrenCopy = children == null? null : new HashSet<UUID>(children); - ConfigurationEntry copy = new ConfigurationEntry(entryId, entry.getType(), new HashMap<String, Object>(entry.getAttributes()), childrenCopy, this); - entries.put(entryId, copy); - if (children != null) - { - for (UUID uuid : children) - { - copyEntry(uuid, initialStore, entries); - } - } - } - } - private void loadFromJson(String json) { ByteArrayInputStream bais = null; @@ -394,7 +592,7 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore private void createRootEntry() { - ConfigurationEntry brokerEntry = new ConfigurationEntry(UUIDGenerator.generateRandomUUID(), + ConfigurationEntry brokerEntry = new ConfigurationEntryImpl(UUIDGenerator.generateRandomUUID(), Broker.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), this); _rootId = brokerEntry.getId(); _entries.put(_rootId, brokerEntry); @@ -610,7 +808,7 @@ public class MemoryConfigurationEntryStore implements ConfigurationEntryStore "ID attribute value does not conform to UUID format for configuration entry " + parent); } } - ConfigurationEntry entry = new ConfigurationEntry(id, type, attributes, childrenIds, this); + ConfigurationEntry entry = new ConfigurationEntryImpl(id, type, attributes, childrenIds, this); if (entries.containsKey(id)) { throw new IllegalConfigurationException("Duplicate id is found: " + id diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListener.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListener.java index addc42e6f9..b76041dcce 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListener.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListener.java @@ -22,28 +22,25 @@ package org.apache.qpid.server.configuration.store; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import org.apache.qpid.server.configuration.ConfigurationEntry; +import org.apache.qpid.server.configuration.ConfigurationEntryImpl; import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ConfigurationChangeListener; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.Model; -import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.State; import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.store.StoreException; +import org.apache.qpid.server.store.DurableConfigurationStore; public class StoreConfigurationChangeListener implements ConfigurationChangeListener { - private ConfigurationEntryStore _store; + private DurableConfigurationStore _store; - public StoreConfigurationChangeListener(ConfigurationEntryStore store) + public StoreConfigurationChangeListener(DurableConfigurationStore store) { super(); _store = store; @@ -54,7 +51,7 @@ public class StoreConfigurationChangeListener implements ConfigurationChangeList { if (newState == State.DELETED) { - _store.remove(object.getId()); + _store.remove(object.asObjectRecord()); object.removeChangeListener(this); } } @@ -66,9 +63,7 @@ public class StoreConfigurationChangeListener implements ConfigurationChangeList if (!(object instanceof VirtualHost)) { child.addChangeListener(this); - ConfigurationEntry parentEntry = toConfigurationEntry(object); - ConfigurationEntry childEntry = toConfigurationEntry(child); - _store.save(parentEntry, childEntry); + _store.update(true,child.asObjectRecord()); } } @@ -76,48 +71,13 @@ public class StoreConfigurationChangeListener implements ConfigurationChangeList @Override public void childRemoved(ConfiguredObject object, ConfiguredObject child) { - _store.save(toConfigurationEntry(object)); + _store.remove(child.asObjectRecord()); } @Override public void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue) { - _store.save(toConfigurationEntry(object)); - } - - private ConfigurationEntry toConfigurationEntry(ConfiguredObject object) - { - Class<? extends ConfiguredObject> objectType = object.getCategoryClass(); - Set<UUID> childrenIds = getChildrenIds(object, objectType); - ConfigurationEntry entry = new ConfigurationEntry(object.getId(), objectType.getSimpleName(), - object.getActualAttributes(), childrenIds, _store); - return entry; - } - - private Set<UUID> getChildrenIds(ConfiguredObject object, Class<? extends ConfiguredObject> objectType) - { - // Virtual Host children's IDs should not be stored in broker store - if (object instanceof VirtualHost) - { - return Collections.emptySet(); - } - Set<UUID> childrenIds = new TreeSet<UUID>(); - Collection<Class<? extends ConfiguredObject>> childClasses = Model.getInstance().getChildTypes(objectType); - if (childClasses != null) - { - for (Class<? extends ConfiguredObject> childClass : childClasses) - { - Collection<? extends ConfiguredObject> children = object.getChildren(childClass); - if (children != null) - { - for (ConfiguredObject childObject : children) - { - childrenIds.add(childObject.getId()); - } - } - } - } - return childrenIds; + _store.update(false, object.asObjectRecord()); } @Override diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/JsonConfigurationStoreFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/JsonConfigurationStoreFactory.java index de007e68d7..517672f74b 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/JsonConfigurationStoreFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/JsonConfigurationStoreFactory.java @@ -24,14 +24,15 @@ import java.util.Map; import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.configuration.store.JsonConfigurationEntryStore; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.server.plugin.ConfigurationStoreFactory; public class JsonConfigurationStoreFactory implements ConfigurationStoreFactory { @Override - public ConfigurationEntryStore createStore(String storeLocation, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties) + public ConfigurationEntryStore createStore(SystemContext systemContext, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties) { - return new JsonConfigurationEntryStore(storeLocation, initialStore, overwrite, configProperties); + return new JsonConfigurationEntryStore(systemContext, initialStore, overwrite, configProperties); } @Override diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/MemoryConfigurationStoreFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/MemoryConfigurationStoreFactory.java index f7a9157144..8af654084b 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/MemoryConfigurationStoreFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/MemoryConfigurationStoreFactory.java @@ -24,14 +24,15 @@ import java.util.Map; import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.configuration.store.MemoryConfigurationEntryStore; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.server.plugin.ConfigurationStoreFactory; public class MemoryConfigurationStoreFactory implements ConfigurationStoreFactory { @Override - public ConfigurationEntryStore createStore(String storeLocation, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties) + public ConfigurationEntryStore createStore(SystemContext systemContext, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties) { - return new MemoryConfigurationEntryStore(null, initialStore, configProperties); + return new MemoryConfigurationEntryStore(systemContext, null, initialStore, configProperties); } @Override diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java index 25f20ba1ee..2625fe83bc 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java @@ -38,7 +38,7 @@ import org.apache.qpid.server.model.Publisher; import org.apache.qpid.server.model.Queue; import org.apache.qpid.server.model.State; import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.model.adapter.AbstractConfiguredObject; +import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.plugin.ExchangeType; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.BaseQueue; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AbstractConfiguredObject.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObject.java index 7c28ac7e1f..a31a4f0ab7 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AbstractConfiguredObject.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObject.java @@ -18,18 +18,8 @@ * under the License. * */ -package org.apache.qpid.server.model.adapter; +package org.apache.qpid.server.model; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.security.AccessControlException; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.*; - -import org.apache.qpid.server.model.*; import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.configuration.updater.ChangeAttributesTask; import org.apache.qpid.server.configuration.updater.ChangeStateTask; @@ -42,6 +32,14 @@ import org.apache.qpid.server.store.ConfiguredObjectRecord; import org.apache.qpid.server.util.ServerScopedRuntimeException; import javax.security.auth.Subject; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.security.AccessControlException; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.*; public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> implements ConfiguredObject<X> { @@ -151,9 +149,12 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im boolean filterAttributes) { _taskExecutor = taskExecutor; - _id = (UUID)attributes.get(ID); + final UUID uuid = (UUID) attributes.get(ID); + _id = uuid == null ? UUID.randomUUID() : uuid; _attributeTypes = getAttributeTypes(getClass()); _automatedFields = getAutomatedFields(getClass()); + + for(Map.Entry<Class<? extends ConfiguredObject>, ConfiguredObject<?>> entry : parents.entrySet()) { addParent((Class<ConfiguredObject>) entry.getKey(), entry.getValue()); @@ -227,6 +228,15 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im throw new IllegalArgumentException("Mandatory attribute " + attr.getName() + " not supplied for instance of " + getClass().getName()); } } + + for(ConfiguredObject<?> parent : parents.values()) + { + if(parent instanceof AbstractConfiguredObject<?>) + { + ((AbstractConfiguredObject<?>)parent).instantiateChild(this); + } + } + } private void automatedSetValue(final String name, final Object value) @@ -414,7 +424,11 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im } } - <T extends ConfiguredObject<?>> Object getAttribute(String name, T parent, String parentAttributeName) + protected void create() + { + } + + protected <T extends ConfiguredObject<?>> Object getAttribute(String name, T parent, String parentAttributeName) { Object value = getActualAttribute(name); if (value != null ) @@ -534,15 +548,16 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im } } - protected <T extends ConfiguredObject> void addParent(Class<T> clazz, T parent) + private <T extends ConfiguredObject> void addParent(Class<T> clazz, T parent) { synchronized (_parents) { _parents.put(clazz, parent); } + } - protected <T extends ConfiguredObject> void removeParent(Class<T> clazz) + protected <T extends ConfiguredObject> void removeParent(Class<T> clazz) { synchronized (this) { @@ -564,19 +579,10 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im return getClass().getSimpleName() + " [id=" + _id + ", name=" + getName() + "]"; } - public ConfiguredObjectRecord asObjectRecord() { return new ConfiguredObjectRecord() { - - @Override - public String toString() - { - return getClass().getSimpleName() + "[name=" + getName() + ", categoryClass=" + getCategoryClass() + ", type=" - + getType() + ", id=" + getId() + "]"; - } - @Override public UUID getId() { @@ -626,10 +632,15 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im return parents; } + @Override + public String toString() + { + return getClass().getSimpleName() + "[name=" + getName() + ", categoryClass=" + getCategoryClass() + ", type=" + + getType() + ", id=" + getId() + "]"; + } }; } - @SuppressWarnings("unchecked") @Override public <C extends ConfiguredObject> C createChild(Class<C> childClass, Map<String, Object> attributes, ConfiguredObject... otherParents) @@ -655,8 +666,40 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im throw new UnsupportedOperationException(); } + protected <C extends ConfiguredObject> void instantiateChild(final C child) + { + + Class<? extends ConfiguredObject> childCategory = child.getCategoryClass(); + if(!Model.getInstance().getChildTypes(getCategoryClass()).contains(childCategory)) + { + throw new IllegalArgumentException("Cannot instantiate a child of category " + childCategory.getSimpleName() + + " to a parent of category " + getCategoryClass().getSimpleName()); + } - protected TaskExecutor getTaskExecutor() + try + { + final String methodName = "instantiate" + childCategory.getSimpleName(); + Method recoveryMethod = getClass().getMethod(methodName, childCategory); + recoveryMethod.setAccessible(true); + recoveryMethod.invoke(this, child); + } + catch (NoSuchMethodException e) + { + throw new IllegalArgumentException("Cannot instantiate a child of category " + childCategory.getSimpleName() + + " to a parent of category " + getCategoryClass().getSimpleName() + + ". No instatiation method defined. "); + } + catch (InvocationTargetException e) + { + throw new IllegalArgumentException("Error recovering child", e.getTargetException()); + } + catch (IllegalAccessException e) + { + throw new ServerScopedRuntimeException("Error recovering child, method for recovery cannot be called", e); + } + } + + public TaskExecutor getTaskExecutor() { return _taskExecutor; } @@ -836,6 +879,20 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im return map; } + + public <Y extends ConfiguredObject<Y>> Y findConfiguredObject(Class<Y> clazz, String name) + { + Collection<Y> reachable = getReachableObjects(this,clazz); + for(Y candidate : reachable) + { + if(candidate.getName().equals(name)) + { + return candidate; + } + } + return null; + } + //========================================================================================= private static abstract class AttributeOrStatistic<C extends ConfiguredObject, T> @@ -885,6 +942,10 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im } + public Method getGetter() + { + return _getter; + } } private static final class Statistic<C extends ConfiguredObject, T extends Number> extends AttributeOrStatistic<C,T> @@ -1166,6 +1227,7 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im } } + private static final class ConfiguredObjectConverter<X extends ConfiguredObject<X>> implements Converter<X> { private final Class<X> _klazz; @@ -1698,6 +1760,10 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im for(Class<? extends ConfiguredObject> parentClass : Model.getInstance().getParentTypes(category)) { ConfiguredObject parent = object.getParent(parentClass); + if(parent == null) + { + System.err.println(parentClass.getSimpleName()); + } ConfiguredObject ancestor = getAncestor(ancestorClass, parentClass, parent); if(ancestor != null) { @@ -1753,7 +1819,7 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im return allDescendants.contains(descendantClass); } - private static Class<? extends ConfiguredObject> getCategory(final Class<?> clazz) + static Class<? extends ConfiguredObject> getCategory(final Class<?> clazz) { ManagedObject annotation = clazz.getAnnotation(ManagedObject.class); if(annotation != null && annotation.category()) @@ -1776,4 +1842,51 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im } + protected static String getType(final Class<? extends ConfiguredObject> clazz) + { + ManagedObject annotation = clazz.getAnnotation(ManagedObject.class); + if(annotation != null) + { + if(!"".equals(annotation.type())) + { + return annotation.type(); + } + } + + if(clazz.getSuperclass() != null && ConfiguredObject.class.isAssignableFrom(clazz.getSuperclass())) + { + String type = getType((Class<? extends ConfiguredObject>) clazz.getSuperclass()); + if(!"".equals(type)) + { + return type; + } + } + + for(Class<?> iface : clazz.getInterfaces() ) + { + if(ConfiguredObject.class.isAssignableFrom(iface)) + { + String type = getType((Class<? extends ConfiguredObject>) iface); + if(!"".equals(type)) + { + return type; + } + } + } + Class<? extends ConfiguredObject> category = getCategory(clazz); + if(category == null) + { + return ""; + } + annotation = category.getAnnotation(ManagedObject.class); + if(annotation == null) + { + throw new NullPointerException("No definition found for category " + category.getSimpleName()); + } + if(!"".equals(annotation.defaultType())) + { + return annotation.defaultType(); + } + return category.getSimpleName(); + } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObjectTypeFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObjectTypeFactory.java new file mode 100644 index 0000000000..f8323e2b42 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObjectTypeFactory.java @@ -0,0 +1,111 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model; + +import org.apache.qpid.server.plugin.ConfiguredObjectTypeFactory; +import org.apache.qpid.server.store.ConfiguredObjectDependency; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.UnresolvedConfiguredObject; + +import java.util.HashMap; +import java.util.Map; + +abstract public class AbstractConfiguredObjectTypeFactory<X extends AbstractConfiguredObject<X>> implements ConfiguredObjectTypeFactory<X> +{ + private final Class<X> _clazz; + + protected AbstractConfiguredObjectTypeFactory(final Class<X> clazz) + { + _clazz = clazz; + } + + @Override + public final String getType() + { + return AbstractConfiguredObject.getType(_clazz); + } + + @Override + public final Class<? super X> getCategoryClass() + { + return (Class<? super X>) AbstractConfiguredObject.getCategory(_clazz); + } + + @Override + public X create(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + X instance = createInstance(attributes, parents); + instance.create(); + return instance; + } + + protected abstract X createInstance(Map<String, Object> attributes, ConfiguredObject<?>... parents); + + public final <C extends ConfiguredObject<C>> C getParent(Class<C> parentClass, ConfiguredObject<?>... parents) + { + if(!Model.getInstance().getParentTypes((Class<? extends ConfiguredObject>) getCategoryClass()).contains( + parentClass)) + { + throw new IllegalArgumentException(parentClass.getSimpleName() + " is not a parent of " + _clazz.getSimpleName()); + } + + for(ConfiguredObject<?> parent : parents) + { + if(parentClass.isInstance(parent)) + { + return (C) parent; + } + } + throw new IllegalArgumentException("No parent of class " + parentClass.getSimpleName() + " found."); + } + + @Override + public UnresolvedConfiguredObject<X> recover(final ConfiguredObjectRecord record, + final ConfiguredObject<?>... parents) + { + return new GenericUnresolvedConfiguredObject( record, parents ); + } + + + private class GenericUnresolvedConfiguredObject extends AbstractUnresolvedObject<X> + { + public GenericUnresolvedConfiguredObject( + final ConfiguredObjectRecord record, final ConfiguredObject<?>[] parents) + { + super(_clazz, record, parents); + } + + @Override + protected <C extends ConfiguredObject<C>> void resolved(final ConfiguredObjectDependency<C> dependency, + final C value) + { + + } + + @Override + public X resolve() + { + Map<String,Object> attributesWithId = new HashMap<String, Object>(getRecord().getAttributes()); + attributesWithId.put(ConfiguredObject.ID, getRecord().getId()); + return createInstance(attributesWithId, getParents()); + } + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractUnresolvedObject.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractUnresolvedObject.java new file mode 100644 index 0000000000..6e03ccdf8a --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractUnresolvedObject.java @@ -0,0 +1,241 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model; + +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.store.ConfiguredObjectDependency; +import org.apache.qpid.server.store.ConfiguredObjectIdDependency; +import org.apache.qpid.server.store.ConfiguredObjectNameDependency; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.UnresolvedConfiguredObject; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; + +public abstract class AbstractUnresolvedObject<C extends ConfiguredObject<C>> implements UnresolvedConfiguredObject<C> +{ + private final Class<C> _clazz; + private final Collection<ConfiguredObjectDependency<?>> _unresolvedObjects = new ArrayList<ConfiguredObjectDependency<?>>(); + private final ConfiguredObjectRecord _record; + private final ConfiguredObject<?>[] _parents; + + protected AbstractUnresolvedObject(Class<C> clazz, + ConfiguredObjectRecord record, + ConfiguredObject<?>... parents) + { + _clazz = clazz; + _record = record; + _parents = parents; + + Collection<AbstractConfiguredObject.Attribute<? super C, ?>> attributes = + AbstractConfiguredObject.getAttributes(clazz); + for(AbstractConfiguredObject.Attribute<? super C, ?> attribute : attributes) + { + final Class<?> attributeType = attribute.getType(); + if(ConfiguredObject.class.isAssignableFrom(attributeType)) + { + addUnresolvedObject((Class<? extends ConfiguredObject>) attributeType, attribute.getName(), attribute.getAnnotation().mandatory()); + } + else if(Collection.class.isAssignableFrom(attributeType)) + { + Type returnType = attribute.getGetter().getGenericReturnType(); + if (returnType instanceof ParameterizedType) + { + Type type = ((ParameterizedType) returnType).getActualTypeArguments()[0]; + if(ConfiguredObject.class.isAssignableFrom((Class)type)) + { + Class<? extends ConfiguredObject> attrClass = (Class<? extends ConfiguredObject>) type; + Object attrValue = _record.getAttributes().get(attribute.getName()); + if(attrValue != null) + { + if (attrValue instanceof Collection) + { + for (Object val : (Collection) attrValue) + { + addUnresolvedObject(attrClass, attribute.getName(), val); + } + } + else if(attrValue instanceof Object[]) + { + for (Object val : (Object[]) attrValue) + { + addUnresolvedObject(attrClass, attribute.getName(), val); + } + } + else + { + addUnresolvedObject(attrClass, attribute.getName(), attrValue); + } + } + } + } + + } + } + } + + public ConfiguredObjectRecord getRecord() + { + return _record; + } + + public ConfiguredObject<?>[] getParents() + { + return _parents; + } + + private void addUnresolvedObject(final Class<? extends ConfiguredObject> clazz, + final String attributeName, + boolean mandatory) + { + Object attrValue = _record.getAttributes().get(attributeName); + if(attrValue != null) + { + addUnresolvedObject(clazz, attributeName, attrValue); + } + else if(mandatory) + { + throw new IllegalConfigurationException("Missing attribute " + attributeName + " has no value"); + } + } + + private void addUnresolvedObject(final Class<? extends ConfiguredObject> clazz, + final String attributeName, + final Object attrValue) + { + if(attrValue instanceof UUID) + { + _unresolvedObjects.add(new IdDependency(clazz, attributeName,(UUID)attrValue)); + } + else if(attrValue instanceof String) + { + try + { + _unresolvedObjects.add(new IdDependency(clazz, attributeName, UUID.fromString((String) attrValue))); + } + catch(IllegalArgumentException e) + { + _unresolvedObjects.add(new NameDependency(clazz, attributeName, (String) attrValue)); + } + } + else if(!clazz.isInstance(attrValue)) + { + throw new IllegalArgumentException("Cannot convert from type " + attrValue.getClass() + " to a configured object dependency"); + } + } + + + protected abstract <X extends ConfiguredObject<X>> void resolved(ConfiguredObjectDependency<X> dependency, X value); + + @Override + public Collection<ConfiguredObjectDependency<?>> getUnresolvedDependencies() + { + return _unresolvedObjects; + } + + private abstract class Dependency<X extends ConfiguredObject<X>> implements ConfiguredObjectDependency<X> + { + private final Class<X> _clazz; + private final String _attributeName; + + public Dependency(final Class<X> clazz, + final String attributeName) + { + _clazz = clazz; + _attributeName = attributeName; + } + + @Override + public final Class<X> getCategoryClass() + { + return _clazz; + } + + @Override + public final void resolve(final X object) + { + _unresolvedObjects.remove(this); + resolved(this, object); + } + + public final String getAttributeName() + { + return _attributeName; + } + + } + + private class IdDependency<X extends ConfiguredObject<X>> extends Dependency<X> implements ConfiguredObjectIdDependency<X> + { + private final UUID _id; + + public IdDependency(final Class<X> clazz, + final String attributeName, + final UUID id) + { + super(clazz, attributeName); + _id = id; + } + + @Override + public UUID getId() + { + return _id; + } + + @Override + public String toString() + { + return "IdDependency{" + getCategoryClass().getSimpleName() + ", " + _id + " }"; + } + } + + private class NameDependency<X extends ConfiguredObject<X>> extends Dependency<X> implements ConfiguredObjectNameDependency<X> + { + + private final String _name; + + public NameDependency(final Class<X> clazz, + final String attributeName, + final String attrValue) + { + super(clazz, attributeName); + _name = attrValue; + } + + @Override + public String getName() + { + return _name; + } + + @Override + public String toString() + { + return "NameDependency{" + getCategoryClass().getSimpleName() + ", \"" + _name + "\" }"; + } + } +} + + diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Broker.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Broker.java index bb3e635326..7292bd1a9e 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Broker.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Broker.java @@ -20,20 +20,20 @@ */ package org.apache.qpid.server.model; -import java.net.SocketAddress; -import java.util.Collection; - +import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.logging.EventLogger; import org.apache.qpid.server.logging.EventLoggerProvider; import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.logging.MessageLogger; -import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.server.security.SubjectCreator; +import org.apache.qpid.server.stats.StatisticsGatherer; import org.apache.qpid.server.virtualhost.VirtualHostRegistry; -@ManagedObject -public interface Broker<X extends Broker<X>> extends ConfiguredObject<X>, EventLoggerProvider +import java.net.SocketAddress; +import java.util.Collection; + +@ManagedObject( defaultType = "adapter" ) +public interface Broker<X extends Broker<X>> extends ConfiguredObject<X>, EventLoggerProvider, StatisticsGatherer { String BUILD_VERSION = "buildVersion"; @@ -41,7 +41,6 @@ public interface Broker<X extends Broker<X>> extends ConfiguredObject<X>, EventL String PLATFORM = "platform"; String PROCESS_PID = "processPid"; String PRODUCT_VERSION = "productVersion"; - String SUPPORTED_BROKER_STORE_TYPES = "supportedBrokerStoreTypes"; String SUPPORTED_VIRTUALHOST_TYPES = "supportedVirtualHostTypes"; String SUPPORTED_VIRTUALHOST_STORE_TYPES = "supportedVirtualHostStoreTypes"; String SUPPORTED_AUTHENTICATION_PROVIDERS = "supportedAuthenticationProviders"; @@ -92,9 +91,6 @@ public interface Broker<X extends Broker<X>> extends ConfiguredObject<X>, EventL String getProductVersion(); @ManagedAttribute - Collection<String> getSupportedBrokerStoreTypes(); - - @ManagedAttribute Collection<String> getSupportedVirtualHostStoreTypes(); @ManagedAttribute @@ -152,15 +148,6 @@ public interface Broker<X extends Broker<X>> extends ConfiguredObject<X>, EventL boolean getStatisticsReportingResetEnabled(); @ManagedAttribute - String getStoreType(); - - @ManagedAttribute - int getStoreVersion(); - - @ManagedAttribute - String getStorePath(); - - @ManagedAttribute String getModelVersion(); @ManagedAttribute diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ConfiguredObject.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ConfiguredObject.java index 7e3e5c9bbe..e329b015c6 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ConfiguredObject.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ConfiguredObject.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.server.model; -import org.apache.qpid.server.model.adapter.AbstractConfiguredObject; import org.apache.qpid.server.store.ConfiguredObjectRecord; import java.security.AccessControlException; @@ -280,6 +279,8 @@ public interface ConfiguredObject<X extends ConfiguredObject<X>> Class<? extends ConfiguredObject> getCategoryClass(); + <C extends ConfiguredObject<C>> C findConfiguredObject(Class<C> clazz, String name); + // TODO - remove this when objects become responsible for their own storage ConfiguredObjectRecord asObjectRecord(); diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ConfiguredObjectFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ConfiguredObjectFactory.java new file mode 100644 index 0000000000..2389fc742f --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ConfiguredObjectFactory.java @@ -0,0 +1,141 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model; + +import org.apache.qpid.server.plugin.ConfiguredObjectTypeFactory; +import org.apache.qpid.server.plugin.QpidServiceLoader; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.UnresolvedConfiguredObject; +import org.apache.qpid.server.util.ServerScopedRuntimeException; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class ConfiguredObjectFactory +{ + private final Map<String, String> _defaultTypes = new HashMap<String, String>(); + private final Map<String, Map<String, ConfiguredObjectTypeFactory>> _allFactories = + new HashMap<String, Map<String, ConfiguredObjectTypeFactory>>(); + private final Map<String, Collection<String>> _supportedTypes = new HashMap<String, Collection<String>>(); + + public ConfiguredObjectFactory() + { + QpidServiceLoader<ConfiguredObjectTypeFactory> serviceLoader = new QpidServiceLoader<ConfiguredObjectTypeFactory>(); + Iterable<ConfiguredObjectTypeFactory> allFactories = serviceLoader.instancesOf(ConfiguredObjectTypeFactory.class); + for(ConfiguredObjectTypeFactory factory : allFactories) + { + final Class<? extends ConfiguredObject> categoryClass = factory.getCategoryClass(); + final String categoryName = categoryClass.getSimpleName(); + + Map<String, ConfiguredObjectTypeFactory> categoryFactories = _allFactories.get(categoryName); + if(categoryFactories == null) + { + categoryFactories = new HashMap<String, ConfiguredObjectTypeFactory>(); + _allFactories.put(categoryName, categoryFactories); + _supportedTypes.put(categoryName, new ArrayList<String>()); + ManagedObject annotation = categoryClass.getAnnotation(ManagedObject.class); + if(annotation != null && !"".equals(annotation.defaultType())) + { + _defaultTypes.put(categoryName, annotation.defaultType()); + } + + } + if(categoryFactories.put(factory.getType(),factory) != null) + { + throw new ServerScopedRuntimeException("Misconfiguration - there is more than one factory defined for class " + categoryName + + " with type " + factory.getType()); + } + if(factory.getType() != null) + { + _supportedTypes.get(categoryName).add(factory.getType()); + } + } + } + + public <X extends ConfiguredObject<X>> UnresolvedConfiguredObject<X> recover(ConfiguredObjectRecord record, + ConfiguredObject<?>... parents) + { + String category = record.getType(); + + + String type = (String) record.getAttributes().get(ConfiguredObject.TYPE); + + ConfiguredObjectTypeFactory factory = getConfiguredObjectTypeFactory(category, type); + + if(factory == null) + { + throw new ServerScopedRuntimeException("No factory defined for ConfiguredObject of category " + category + " and type " + type); + } + + return factory.recover(record, parents); + } + + public <X extends ConfiguredObject<X>> ConfiguredObjectTypeFactory<X> getConfiguredObjectTypeFactory(final Class<X> categoryClass, Map<String,Object> attributes) + { + final String category = categoryClass.getSimpleName(); + Map<String, ConfiguredObjectTypeFactory> categoryFactories = _allFactories.get(category); + if(categoryFactories == null) + { + throw new ServerScopedRuntimeException("No factory defined for ConfiguredObject of category " + category); + } + String type = (String) attributes.get(ConfiguredObject.TYPE); + + ConfiguredObjectTypeFactory factory; + + if(type != null) + { + factory = getConfiguredObjectTypeFactory(category, type); + } + else + { + factory = getConfiguredObjectTypeFactory(category, null); + if(factory == null) + { + ManagedObject annotation = categoryClass.getAnnotation(ManagedObject.class); + factory = getConfiguredObjectTypeFactory(category, annotation.defaultType()); + } + } + return factory; + } + + public ConfiguredObjectTypeFactory getConfiguredObjectTypeFactory(final String category, final String type) + { + Map<String, ConfiguredObjectTypeFactory> categoryFactories = _allFactories.get(category); + if(categoryFactories == null) + { + throw new ServerScopedRuntimeException("No factory defined for ConfiguredObject of category " + category); + } + ConfiguredObjectTypeFactory factory = categoryFactories.get(type); + if(factory == null) + { + factory = categoryFactories.get(_defaultTypes.get(category)); + } + return factory; + } + + public Collection<String> getSupportedTypes(Class<? extends ConfiguredObject> category) + { + return Collections.unmodifiableCollection(_supportedTypes.get(category.getSimpleName())); + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/KeyStore.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/KeyStore.java index db0745fbec..47f5a65477 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/KeyStore.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/KeyStore.java @@ -21,12 +21,9 @@ package org.apache.qpid.server.model; import java.security.GeneralSecurityException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; import javax.net.ssl.KeyManager; -@ManagedObject +@ManagedObject( defaultType = "FileKeyStore" ) public interface KeyStore<X extends KeyStore<X>> extends ConfiguredObject<X> { String DURABLE = "durable"; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ManagedObject.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ManagedObject.java index f3370ff354..bb821d057e 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ManagedObject.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/ManagedObject.java @@ -31,5 +31,6 @@ public @interface ManagedObject String[] operations() default {}; boolean managesChildren() default false; // for objects that manage children, a management node needs to be created boolean creatable() default true; - String defaultImplementation() default ""; // in this case the class/interface itself is to be used + String defaultType() default ""; // in this case the class/interface itself is to be used + String type() default ""; } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Model.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Model.java index c48c7bb7f6..5630b1c20d 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Model.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Model.java @@ -56,6 +56,8 @@ public class Model private Model() { + addRelationship(SystemContext.class, Broker.class); + addRelationship(Broker.class, VirtualHost.class); addRelationship(Broker.class, Port.class); addRelationship(Broker.class, AccessControlProvider.class); diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Port.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Port.java index 497e2bfceb..7c404fdef4 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Port.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/Port.java @@ -71,9 +71,6 @@ public interface Port<X extends Port<X>> extends ConfiguredObject<X> boolean getWantClientAuth(); @ManagedAttribute - AuthenticationProvider getAuthenticationProvider(); - - @ManagedAttribute KeyStore getKeyStore(); @ManagedAttribute diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemContext.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemContext.java new file mode 100644 index 0000000000..74e6eefb33 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemContext.java @@ -0,0 +1,324 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model; + +import org.apache.qpid.server.BrokerOptions; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.logging.EventLogger; +import org.apache.qpid.server.logging.LogRecorder; +import org.apache.qpid.server.logging.messages.BrokerMessages; +import org.apache.qpid.server.model.adapter.BrokerAdapter; +import org.apache.qpid.server.store.ConfiguredObjectDependency; +import org.apache.qpid.server.store.ConfiguredObjectIdDependency; +import org.apache.qpid.server.store.ConfiguredObjectNameDependency; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.UnresolvedConfiguredObject; +import org.apache.qpid.server.util.ServerScopedRuntimeException; + +import java.security.AccessControlException; +import java.util.*; + +@ManagedObject (creatable = false) +public class SystemContext extends AbstractConfiguredObject<SystemContext> +{ + private static final UUID SYSTEM_ID = new UUID(0l, 0l); + private final ConfiguredObjectFactory _objectFactory; + private final EventLogger _eventLogger; + private final LogRecorder _logRecorder; + private final BrokerOptions _brokerOptions; + + @ManagedAttributeField + private String _storePath; + + @ManagedAttributeField + private String _storeType; + private Broker _broker; + + public SystemContext(final TaskExecutor taskExecutor, + final ConfiguredObjectFactory configuredObjectFactory, + final EventLogger eventLogger, + final LogRecorder logRecorder, + final BrokerOptions brokerOptions) + { + super(SYSTEM_ID, Collections.<String,Object>emptyMap(), createAttributes(brokerOptions), taskExecutor); + _eventLogger = eventLogger; + getTaskExecutor().start(); + _objectFactory = configuredObjectFactory; + _logRecorder = logRecorder; + _brokerOptions = brokerOptions; + } + + public static Map<String, Object> createAttributes(final BrokerOptions brokerOptions) + { + Map<String,Object> attributes = new HashMap<String, Object>(); + attributes.put(NAME, "System"); + attributes.put("storePath", brokerOptions.getConfigurationStoreLocation()); + attributes.put("storeTye", brokerOptions.getConfigurationStoreType()); + return attributes; + } + + public void resolveObjects(ConfiguredObjectRecord... records) + { + + ConfiguredObjectFactory factory = getObjectFactory(); + + Map<UUID, ConfiguredObject<?>> resolvedObjects = new HashMap<UUID, ConfiguredObject<?>>(); + resolvedObjects.put(getId(), this); + + Collection<ConfiguredObjectRecord> recordsWithUnresolvedParents = new ArrayList<ConfiguredObjectRecord>(Arrays.asList(records)); + Collection<UnresolvedConfiguredObject<? extends ConfiguredObject>> recordsWithUnresolvedDependencies = + new ArrayList<UnresolvedConfiguredObject<? extends ConfiguredObject>>(); + + boolean updatesMade; + + do + { + updatesMade = false; + Iterator<ConfiguredObjectRecord> iter = recordsWithUnresolvedParents.iterator(); + while (iter.hasNext()) + { + ConfiguredObjectRecord record = iter.next(); + Collection<ConfiguredObject<?>> parents = new ArrayList<ConfiguredObject<?>>(); + boolean foundParents = true; + for (ConfiguredObjectRecord parent : record.getParents().values()) + { + if (!resolvedObjects.containsKey(parent.getId())) + { + foundParents = false; + break; + } + else + { + parents.add(resolvedObjects.get(parent.getId())); + } + } + if (foundParents) + { + iter.remove(); + UnresolvedConfiguredObject<? extends ConfiguredObject> recovered = + factory.recover(record, parents.toArray(new ConfiguredObject<?>[parents.size()])); + Collection<ConfiguredObjectDependency<?>> dependencies = + recovered.getUnresolvedDependencies(); + if (dependencies.isEmpty()) + { + updatesMade = true; + ConfiguredObject<?> resolved = recovered.resolve(); + resolvedObjects.put(resolved.getId(), resolved); + } + else + { + recordsWithUnresolvedDependencies.add(recovered); + } + } + + } + + Iterator<UnresolvedConfiguredObject<? extends ConfiguredObject>> unresolvedIter = + recordsWithUnresolvedDependencies.iterator(); + + while(unresolvedIter.hasNext()) + { + UnresolvedConfiguredObject<? extends ConfiguredObject> unresolvedObject = unresolvedIter.next(); + Collection<ConfiguredObjectDependency<?>> dependencies = + new ArrayList<ConfiguredObjectDependency<?>>(unresolvedObject.getUnresolvedDependencies()); + + for(ConfiguredObjectDependency dependency : dependencies) + { + if(dependency instanceof ConfiguredObjectIdDependency) + { + UUID id = ((ConfiguredObjectIdDependency)dependency).getId(); + if(resolvedObjects.containsKey(id)) + { + dependency.resolve(resolvedObjects.get(id)); + } + } + else if(dependency instanceof ConfiguredObjectNameDependency) + { + ConfiguredObject<?> dependentObject = null; + for(ConfiguredObject<?> parent : unresolvedObject.getParents()) + { + dependentObject = parent.findConfiguredObject(dependency.getCategoryClass(), ((ConfiguredObjectNameDependency)dependency).getName()); + if(dependentObject != null) + { + break; + } + } + if(dependentObject != null) + { + dependency.resolve(dependentObject); + } + } + else + { + throw new ServerScopedRuntimeException("Unknown dependency type " + dependency.getClass().getSimpleName()); + } + } + if(unresolvedObject.getUnresolvedDependencies().isEmpty()) + { + updatesMade = true; + unresolvedIter.remove(); + ConfiguredObject<?> resolved = unresolvedObject.resolve(); + resolvedObjects.put(resolved.getId(), resolved); + } + } + + } while(updatesMade && !(recordsWithUnresolvedDependencies.isEmpty() && recordsWithUnresolvedParents.isEmpty())); + + if(!recordsWithUnresolvedDependencies.isEmpty()) + { + throw new IllegalArgumentException("Cannot resolve some objects: " + recordsWithUnresolvedDependencies); + } + if(!recordsWithUnresolvedParents.isEmpty()) + { + throw new IllegalArgumentException("Cannot resolve object because their parents cannot be found" + recordsWithUnresolvedParents); + } + } + + @Override + protected boolean setState(final State currentState, final State desiredState) + { + throw new IllegalArgumentException("Cannot change the state of the SystemContext object"); + } + + @Override + public String setName(final String currentName, final String desiredName) + throws IllegalStateException, AccessControlException + { + return null; + } + + @Override + public State getState() + { + return State.ACTIVE; + } + + @Override + public boolean isDurable() + { + return true; + } + + @Override + public void setDurable(final boolean durable) + throws IllegalStateException, AccessControlException, IllegalArgumentException + { + throw new IllegalArgumentException("Cannot change the durability of the SystemContext object"); + } + + @Override + public LifetimePolicy getLifetimePolicy() + { + return LifetimePolicy.PERMANENT; + } + + @Override + public LifetimePolicy setLifetimePolicy(final LifetimePolicy expected, final LifetimePolicy desired) + throws IllegalStateException, AccessControlException, IllegalArgumentException + { + throw new IllegalArgumentException("Cannot change the lifetime of the SystemContext object"); + } + + @Override + public <C extends ConfiguredObject> Collection<C> getChildren(final Class<C> clazz) + { + if(clazz == Broker.class) + { + return (Collection<C>) Collections.singleton(_broker); + } + + return Collections.emptySet(); + } + + public ConfiguredObjectFactory getObjectFactory() + { + return _objectFactory; + } + + public EventLogger getEventLogger() + { + return _eventLogger; + } + + public LogRecorder getLogRecorder() + { + return _logRecorder; + } + + public BrokerOptions getBrokerOptions() + { + return _brokerOptions; + } + + @ManagedAttribute( automate = true ) + public String getStorePath() + { + return _storePath; + } + + @ManagedAttribute( automate = true ) + public String getStoreType() + { + return _storeType; + } + + public void close() + { + try + { + + + if (getTaskExecutor() != null) + { + getTaskExecutor().stop(); + } + + _eventLogger.message(BrokerMessages.STOPPED()); + + _logRecorder.closeLogRecorder(); + + } + finally + { + if (getTaskExecutor() != null) + { + getTaskExecutor().stopImmediately(); + } + } + + } + + @Override + public Collection<String> getAttributeNames() + { + return getAttributeNames(getClass()); + } + + public void instantiateBroker(final Broker broker) + { + _broker = broker; + } + + public Broker getBroker() + { + return _broker; + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/TrustStore.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/TrustStore.java index 07b593e9a2..92ea8e7863 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/TrustStore.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/TrustStore.java @@ -21,12 +21,9 @@ package org.apache.qpid.server.model; import java.security.GeneralSecurityException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; import javax.net.ssl.TrustManager; -@ManagedObject +@ManagedObject( defaultType = "FileTrustStore" ) public interface TrustStore<X extends TrustStore<X>> extends ConfiguredObject<X> { String DURABLE = "durable"; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/VirtualHost.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/VirtualHost.java index 103602edf5..77c06349bc 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/VirtualHost.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/VirtualHost.java @@ -20,17 +20,16 @@ */ package org.apache.qpid.server.model; -import java.security.AccessControlException; -import java.util.Collection; -import java.util.Map; - import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.message.MessageInstance; import org.apache.qpid.server.store.MessageStore; +import java.security.AccessControlException; +import java.util.Collection; +import java.util.Map; import java.util.UUID; -@ManagedObject( managesChildren = true ) +@ManagedObject( managesChildren = true, defaultType = "STANDARD") public interface VirtualHost<X extends VirtualHost<X>> extends ConfiguredObject<X> { diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AbstractPluginAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AbstractPluginAdapter.java index f42e5e2078..65e3691f81 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AbstractPluginAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AbstractPluginAdapter.java @@ -20,12 +20,7 @@ */ package org.apache.qpid.server.model.adapter; -import java.security.AccessControlException; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.UUID; - +import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.LifetimePolicy; @@ -33,17 +28,23 @@ import org.apache.qpid.server.model.Plugin; import org.apache.qpid.server.model.State; import org.apache.qpid.server.security.access.Operation; +import java.security.AccessControlException; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + public abstract class AbstractPluginAdapter<X extends Plugin<X>> extends AbstractConfiguredObject<X> implements Plugin<X> { private Broker _broker; protected AbstractPluginAdapter(UUID id, Map<String, Object> defaults, Map<String, Object> attributes, Broker broker) { - super(id, defaults, attributes, broker.getTaskExecutor()); + super(Collections.<Class<? extends ConfiguredObject>, ConfiguredObject<?>>singletonMap(Broker.class, broker), defaults, combineIdWithAttributes(id, attributes), broker.getTaskExecutor()); _broker = broker; - addParent(Broker.class, broker); } + @Override public String setName(String currentName, String desiredName) throws IllegalStateException, AccessControlException { @@ -116,13 +117,6 @@ public abstract class AbstractPluginAdapter<X extends Plugin<X>> extends Abstrac } @Override - public <C extends ConfiguredObject> C createChild(Class<C> childClass, Map<String, Object> attributes, - ConfiguredObject... otherParents) - { - throw new UnsupportedOperationException(); - } - - @Override protected void authoriseSetDesiredState(State currentState, State desiredState) throws AccessControlException { if(desiredState == State.DELETED) diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AccessControlProviderAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AccessControlProviderAdapter.java deleted file mode 100644 index ee6a5b5607..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AccessControlProviderAdapter.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.model.adapter; - -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.model.*; -import org.apache.qpid.server.plugin.AccessControlFactory; -import org.apache.qpid.server.security.AccessControl; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.util.MapValueConverter; - -public class AccessControlProviderAdapter extends AbstractConfiguredObject<AccessControlProviderAdapter> implements AccessControlProvider<AccessControlProviderAdapter> -{ - private static final Logger LOGGER = Logger.getLogger(AccessControlProviderAdapter.class); - - protected AccessControl _accessControl; - protected final Broker _broker; - - protected Collection<String> _supportedAttributes; - protected Map<String, AccessControlFactory> _factories; - private AtomicReference<State> _state; - - public AccessControlProviderAdapter(UUID id, Broker broker, AccessControl accessControl, Map<String, Object> attributes, Collection<String> attributeNames) - { - super(id, Collections.<String,Object>emptyMap(), Collections.singletonMap(NAME,attributes.get(NAME)), broker.getTaskExecutor()); - - if (accessControl == null) - { - throw new IllegalArgumentException("AccessControl must not be null"); - } - - _accessControl = accessControl; - _broker = broker; - _supportedAttributes = createSupportedAttributes(attributeNames); - addParent(Broker.class, broker); - - State state = MapValueConverter.getEnumAttribute(State.class, STATE, attributes, State.INITIALISING); - _state = new AtomicReference<State>(state); - - // set attributes now after all attribute names are known - if (attributes != null) - { - for (String name : _supportedAttributes) - { - if (attributes.containsKey(name)) - { - changeAttribute(name, null, attributes.get(name)); - } - } - } - } - - protected Collection<String> createSupportedAttributes(Collection<String> factoryAttributes) - { - List<String> attributesNames = new ArrayList<String>(getAttributeNames(AccessControlProvider.class)); - if (factoryAttributes != null) - { - attributesNames.addAll(factoryAttributes); - } - - return Collections.unmodifiableCollection(attributesNames); - } - - @Override - public String setName(String currentName, String desiredName) throws IllegalStateException, AccessControlException - { - return null; - } - - @Override - public State getState() - { - return _state.get(); - } - - @Override - public boolean isDurable() - { - return true; - } - - @Override - public void setDurable(boolean durable) - throws IllegalStateException, AccessControlException, IllegalArgumentException - { - } - - @Override - public LifetimePolicy getLifetimePolicy() - { - return LifetimePolicy.PERMANENT; - } - - @Override - public LifetimePolicy setLifetimePolicy(LifetimePolicy expected, LifetimePolicy desired) - throws IllegalStateException, AccessControlException, IllegalArgumentException - { - return null; - } - - @Override - public Collection<String> getAttributeNames() - { - return _supportedAttributes; - } - - @Override - public Object getAttribute(String name) - { - if(DURABLE.equals(name)) - { - return true; - } - else if(ID.equals(name)) - { - return getId(); - } - else if(LIFETIME_POLICY.equals(name)) - { - return LifetimePolicy.PERMANENT; - } - else if(STATE.equals(name)) - { - return getState(); - } - return super.getAttribute(name); - } - - @Override - public <C extends ConfiguredObject> Collection<C> getChildren(Class<C> clazz) - { - return Collections.emptySet(); - } - - @Override - public boolean setState(State currentState, State desiredState) - throws IllegalStateTransitionException, AccessControlException - { - State state = _state.get(); - - if(desiredState == State.DELETED) - { - return _state.compareAndSet(state, State.DELETED); - } - else if (desiredState == State.QUIESCED) - { - return _state.compareAndSet(state, State.QUIESCED); - } - else if(desiredState == State.ACTIVE) - { - if ((state == State.INITIALISING || state == State.QUIESCED) && _state.compareAndSet(state, State.ACTIVE)) - { - try - { - _accessControl.open(); - return true; - } - catch(RuntimeException e) - { - _state.compareAndSet(State.ACTIVE, State.ERRORED); - if (_broker.isManagementMode()) - { - LOGGER.warn("Failed to activate ACL provider: " + getName(), e); - } - else - { - throw e; - } - } - } - else - { - throw new IllegalStateException("Can't activate access control provider in " + state + " state"); - } - } - else if(desiredState == State.STOPPED) - { - if(_state.compareAndSet(state, State.STOPPED)) - { - _accessControl.close(); - return true; - } - - return false; - } - return false; - } - - - @Override - protected void changeAttributes(Map<String, Object> attributes) - { - throw new UnsupportedOperationException("Changing attributes on AccessControlProvider is not supported"); - } - - @Override - protected void authoriseSetDesiredState(State currentState, State desiredState) throws AccessControlException - { - if(desiredState == State.DELETED) - { - if (!_broker.getSecurityManager().authoriseConfiguringBroker(getName(), AccessControlProvider.class, Operation.DELETE)) - { - throw new AccessControlException("Deletion of AccessControlProvider is denied"); - } - } - } - - @Override - protected void authoriseSetAttribute(String name, Object expected, Object desired) throws AccessControlException - { - if (!_broker.getSecurityManager().authoriseConfiguringBroker(getName(), AccessControlProvider.class, Operation.UPDATE)) - { - throw new AccessControlException("Setting of AccessControlProvider attributes is denied"); - } - } - - @Override - protected void authoriseSetAttributes(Map<String, Object> attributes) throws AccessControlException - { - if (!_broker.getSecurityManager().authoriseConfiguringBroker(getName(), AccessControlProvider.class, Operation.UPDATE)) - { - throw new AccessControlException("Setting of AccessControlProvider attributes is denied"); - } - } - - public AccessControl getAccessControl() - { - return _accessControl; - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AccessControlProviderFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AccessControlProviderFactory.java deleted file mode 100644 index e98cc2800c..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AccessControlProviderFactory.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.model.adapter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.model.AccessControlProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.AccessControlFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.security.AccessControl; - -public class AccessControlProviderFactory -{ - private final Iterable<AccessControlFactory> _factories; - private Collection<String> _supportedAccessControlProviders; - - public AccessControlProviderFactory(QpidServiceLoader<AccessControlFactory> accessControlFactoryServiceLoader) - { - _factories = accessControlFactoryServiceLoader.instancesOf(AccessControlFactory.class); - List<String> supportedAccessControlProviders = new ArrayList<String>(); - for (AccessControlFactory factory : _factories) - { - supportedAccessControlProviders.add(factory.getType()); - } - _supportedAccessControlProviders = Collections.unmodifiableCollection(supportedAccessControlProviders); - } - - /** - * Creates {@link AccessControlProvider} for given ID, {@link Broker} and attributes. - * <p> - * The configured {@link AccessControlFactory}'s are used to try to create the {@link AccessControlProvider}. - * The first non-null instance is returned. The factories are used in non-deterministic order. - */ - public AccessControlProvider create(UUID id, Broker broker, Map<String, Object> attributes) - { - AccessControlProvider ac = createAccessControlProvider(id, broker, attributes); - ac.getAccessControl().onCreate(); - - return ac; - } - - public AccessControlProvider recover(UUID id, Broker broker, Map<String, Object> attributes) - { - return createAccessControlProvider(id, broker, attributes); - } - - private AccessControlProvider createAccessControlProvider(UUID id, - Broker broker, Map<String, Object> attributes) - { - for (AccessControlFactory factory : _factories) - { - AccessControl accessControl = factory.createInstance(attributes, broker); - if (accessControl != null) - { - return new AccessControlProviderAdapter(id, broker,accessControl, attributes, factory.getAttributeNames()); - } - } - - throw new IllegalArgumentException("No access control provider factory found for configuration attributes " + attributes); - } - - public Collection<String> getSupportedAuthenticationProviders() - { - return _supportedAccessControlProviders; - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactory.java deleted file mode 100644 index 7536f8b39f..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AuthenticationProviderFactory.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.model.adapter; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.security.auth.manager.AbstractAuthenticationManager; - -public class AuthenticationProviderFactory -{ - private final Iterable<AuthenticationManagerFactory> _factories; - private Collection<String> _supportedAuthenticationProviders; - - public AuthenticationProviderFactory(QpidServiceLoader<AuthenticationManagerFactory> authManagerFactoryServiceLoader) - { - _factories = authManagerFactoryServiceLoader.atLeastOneInstanceOf(AuthenticationManagerFactory.class); - List<String> supportedAuthenticationProviders = new ArrayList<String>(); - for (AuthenticationManagerFactory factory : _factories) - { - supportedAuthenticationProviders.add(factory.getType()); - } - _supportedAuthenticationProviders = Collections.unmodifiableCollection(supportedAuthenticationProviders); - } - - /** - * Creates {@link AuthenticationProvider} for given ID, {@link Broker} and attributes. - * <p> - * The configured {@link AuthenticationManagerFactory}'s are used to try to create the {@link AuthenticationProvider}. - * The first non-null instance is returned. The factories are used in non-deterministic order. - */ - public AuthenticationProvider create(UUID id, Broker broker, Map<String, Object> attributes) - { - return createAuthenticationProvider(id, broker, attributes, false); - } - - /** - * Recovers {@link AuthenticationProvider} for given ID, attributes and {@link Broker}. - * <p> - * The configured {@link AuthenticationManagerFactory}'s are used to try to create the {@link AuthenticationProvider}. - * The first non-null instance is returned. The factories are used in non-deterministic order. - */ - public AuthenticationProvider recover(UUID id, Map<String, Object> attributes, Broker broker) - { - return createAuthenticationProvider(id, broker, attributes, true); - } - - private AuthenticationProvider createAuthenticationProvider(UUID id, Broker broker, Map<String, Object> attributes, boolean recovering) - { - attributes = new HashMap<String, Object>(attributes); - attributes.put(AuthenticationProvider.ID,id); - - for (AuthenticationManagerFactory factory : _factories) - { - AbstractAuthenticationManager manager = factory.createInstance(broker, attributes, recovering); - if (manager != null) - { - return manager; - } - } - - throw new IllegalArgumentException("No authentication provider factory found for configuration attributes " + attributes); - } - - public Collection<String> getSupportedAuthenticationProviders() - { - return _supportedAuthenticationProviders; - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapter.java index 7fcdcfe61c..98af4e08dc 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapter.java @@ -20,47 +20,49 @@ */ package org.apache.qpid.server.model.adapter; -import java.lang.reflect.Type; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.security.AccessControlException; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - import org.apache.log4j.Logger; import org.apache.qpid.common.QpidProperties; import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.BrokerConfigurationStoreCreator; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.logging.EventLogger; import org.apache.qpid.server.logging.LogRecorder; import org.apache.qpid.server.logging.messages.BrokerMessages; +import org.apache.qpid.server.logging.messages.VirtualHostMessages; import org.apache.qpid.server.model.*; +import org.apache.qpid.server.model.port.AmqpPort; +import org.apache.qpid.server.model.port.PortWithAuthProvider; +import org.apache.qpid.server.plugin.ConfiguredObjectTypeFactory; import org.apache.qpid.server.plugin.MessageStoreFactory; -import org.apache.qpid.server.plugin.PreferencesProviderFactory; import org.apache.qpid.server.plugin.VirtualHostFactory; +import org.apache.qpid.server.security.FileKeyStore; +import org.apache.qpid.server.security.FileTrustStore; import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.server.security.SubjectCreator; import org.apache.qpid.server.security.access.Operation; import org.apache.qpid.server.security.auth.manager.SimpleAuthenticationManager; +import org.apache.qpid.server.stats.StatisticsCounter; import org.apache.qpid.server.stats.StatisticsGatherer; import org.apache.qpid.server.util.MapValueConverter; import org.apache.qpid.server.virtualhost.VirtualHostRegistry; import org.apache.qpid.util.SystemUtils; import javax.security.auth.Subject; +import java.lang.reflect.Type; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.security.AccessControlException; +import java.security.PrivilegedAction; +import java.util.*; +import java.util.regex.Pattern; -public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject<X> implements Broker<X>, ConfigurationChangeListener +@ManagedObject(category = false, type = "adapter") +public class BrokerAdapter extends AbstractConfiguredObject<BrokerAdapter> implements Broker<BrokerAdapter>, ConfigurationChangeListener, StatisticsGatherer, StatisticsGatherer.Source { private static final Logger LOGGER = Logger.getLogger(BrokerAdapter.class); + private static final Pattern MODEL_VERSION_PATTERN = Pattern.compile("^\\d+\\.\\d+$"); + @SuppressWarnings("serial") public static final Map<String, Type> ATTRIBUTE_TYPES = Collections.unmodifiableMap(new HashMap<String, Type>(){{ put(QUEUE_ALERT_THRESHOLD_MESSAGE_AGE, Long.class); @@ -136,6 +138,7 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject put(Broker.VIRTUALHOST_STORE_TRANSACTION_OPEN_TIMEOUT_CLOSE, DEFAULT_STORE_TRANSACTION_OPEN_TIMEOUT_CLOSE); put(Broker.VIRTUALHOST_STORE_TRANSACTION_OPEN_TIMEOUT_WARN, DEFAULT_STORE_TRANSACTION_OPEN_TIMEOUT_WARN); }}); + private final ConfiguredObjectFactory _objectFactory; private String[] POSITIVE_NUMERIC_ATTRIBUTES = { QUEUE_ALERT_THRESHOLD_MESSAGE_AGE, QUEUE_ALERT_THRESHOLD_QUEUE_DEPTH_MESSAGES, QUEUE_ALERT_THRESHOLD_QUEUE_DEPTH_BYTES, QUEUE_ALERT_THRESHOLD_MESSAGE_SIZE, QUEUE_ALERT_REPEAT_GAP, QUEUE_FLOW_CONTROL_SIZE_BYTES, @@ -146,7 +149,6 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject private EventLogger _eventLogger; - private final StatisticsGatherer _statisticsGatherer; private final VirtualHostRegistry _virtualHostRegistry; private final LogRecorder _logRecorder; @@ -160,46 +162,33 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject private final Map<String, TrustStore<?>> _trustStores = new HashMap<String, TrustStore<?>>(); private final Map<UUID, AccessControlProvider<?>> _accessControlProviders = new HashMap<UUID, AccessControlProvider<?>>(); - private final GroupProviderFactory _groupProviderFactory; - private final AuthenticationProviderFactory _authenticationProviderFactory; - private final AccessControlProviderFactory _accessControlProviderFactory; - private final PortFactory _portFactory; private final SecurityManager _securityManager; private final Collection<String> _supportedVirtualHostStoreTypes; - private Collection<String> _supportedBrokerStoreTypes; - private final ConfigurationEntryStore _brokerStore; private AuthenticationProvider<?> _managementAuthenticationProvider; private BrokerOptions _brokerOptions; + private Timer _reportingTimer; + private StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived; + + public BrokerAdapter(UUID id, Map<String, Object> attributes, - StatisticsGatherer statisticsGatherer, - VirtualHostRegistry virtualHostRegistry, - LogRecorder logRecorder, - AuthenticationProviderFactory authenticationProviderFactory, - GroupProviderFactory groupProviderFactory, - AccessControlProviderFactory accessControlProviderFactory, - PortFactory portFactory, - TaskExecutor taskExecutor, - ConfigurationEntryStore brokerStore, - BrokerOptions brokerOptions) - { - super(id, DEFAULTS, MapValueConverter.convert(attributes, ATTRIBUTE_TYPES), taskExecutor); - _statisticsGatherer = statisticsGatherer; - _virtualHostRegistry = virtualHostRegistry; - _logRecorder = logRecorder; - _eventLogger = virtualHostRegistry.getEventLogger(); - _authenticationProviderFactory = authenticationProviderFactory; - _groupProviderFactory = groupProviderFactory; - _accessControlProviderFactory = accessControlProviderFactory; - _portFactory = portFactory; - _brokerOptions = brokerOptions; + SystemContext parent) + { + super(Collections.<Class<? extends ConfiguredObject>, ConfiguredObject<?>>singletonMap(SystemContext.class, parent), DEFAULTS, combineIdWithAttributes(id,MapValueConverter.convert(attributes, ATTRIBUTE_TYPES)), parent.getTaskExecutor()); + validateModelVersion(); + + _objectFactory = parent.getObjectFactory(); + _virtualHostRegistry = new VirtualHostRegistry(parent.getEventLogger()); + _virtualHostRegistry.setDefaultVirtualHostName((String)getAttribute(Broker.DEFAULT_VIRTUAL_HOST)); + + _logRecorder = parent.getLogRecorder(); + _eventLogger = parent.getEventLogger(); + _brokerOptions = parent.getBrokerOptions(); _securityManager = new SecurityManager(this, _brokerOptions.isManagementMode()); _supportedVirtualHostStoreTypes = MessageStoreFactory.FACTORY_LOADER.getSupportedTypes(); - _supportedBrokerStoreTypes = new BrokerConfigurationStoreCreator().getStoreTypes(); - _brokerStore = brokerStore; if (_brokerOptions.isManagementMode()) { Map<String,Object> authManagerAttrs = new HashMap<String, Object>(); @@ -209,8 +198,52 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject authManager.addUser(BrokerOptions.MANAGEMENT_MODE_USER_NAME, _brokerOptions.getManagementModePassword()); _managementAuthenticationProvider = authManager; } + initialiseStatistics(); + } + + private void validateModelVersion() + { + String modelVersion = (String) getActualAttributes().get(Broker.MODEL_VERSION); + if (modelVersion == null) + { + throw new IllegalConfigurationException("Broker " + Broker.MODEL_VERSION + " must be specified"); + } + + if (!MODEL_VERSION_PATTERN.matcher(modelVersion).matches()) + { + throw new IllegalConfigurationException("Broker " + Broker.MODEL_VERSION + " is specified in incorrect format: " + + modelVersion); + } + + int versionSeparatorPosition = modelVersion.indexOf("."); + String majorVersionPart = modelVersion.substring(0, versionSeparatorPosition); + int majorModelVersion = Integer.parseInt(majorVersionPart); + int minorModelVersion = Integer.parseInt(modelVersion.substring(versionSeparatorPosition + 1)); + + if (majorModelVersion != Model.MODEL_MAJOR_VERSION || minorModelVersion > Model.MODEL_MINOR_VERSION) + { + throw new IllegalConfigurationException("The model version '" + modelVersion + + "' in configuration is incompatible with the broker model version '" + Model.MODEL_VERSION + "'"); + } + + } + + private void initialiseStatisticsReporting() + { + long report = ((Number)getAttribute(Broker.STATISTICS_REPORTING_PERIOD)).intValue() * 1000; // convert to ms + final boolean reset = (Boolean)getAttribute(Broker.STATISTICS_REPORTING_RESET_ENABLED); + + /* add a timer task to report statistics if generation is enabled for broker or virtualhosts */ + if (report > 0L) + { + _reportingTimer = new Timer("Statistics-Reporting", true); + StatisticsReportingTask task = new StatisticsReportingTask(reset, _eventLogger); + _reportingTimer.scheduleAtFixedRate(task, report / 2, report); + } } + + @Override public String getBuildVersion() { @@ -242,12 +275,6 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject } @Override - public Collection<String> getSupportedBrokerStoreTypes() - { - return _supportedBrokerStoreTypes; - } - - @Override public Collection<String> getSupportedVirtualHostStoreTypes() { return _supportedVirtualHostStoreTypes; @@ -256,13 +283,13 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject @Override public Collection<String> getSupportedAuthenticationProviders() { - return _authenticationProviderFactory.getSupportedAuthenticationProviders(); + return _objectFactory.getSupportedTypes(AuthenticationProvider.class); } @Override public Collection<String> getSupportedPreferencesProviderTypes() { - return PreferencesProviderFactory.FACTORY_LOADER.getSupportedTypes(); + return _objectFactory.getSupportedTypes(PreferencesProvider.class); } @Override @@ -362,24 +389,6 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject } @Override - public String getStoreType() - { - return _brokerStore.getType(); - } - - @Override - public int getStoreVersion() - { - return _brokerStore.getVersion(); - } - - @Override - public String getStorePath() - { - return _brokerStore.getStoreLocation(); - } - - @Override public String getModelVersion() { return Model.MODEL_VERSION; @@ -478,9 +487,9 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject private VirtualHost createVirtualHost(final Map<String, Object> attributes) throws AccessControlException, IllegalArgumentException { - final VirtualHostAdapter virtualHostAdapter = new VirtualHostAdapter(UUID.randomUUID(), attributes, this, - _statisticsGatherer, getTaskExecutor()); - addVirtualHost(virtualHostAdapter); + ConfiguredObjectTypeFactory virtualHostFactory = + _objectFactory.getConfiguredObjectTypeFactory(VirtualHost.class, attributes); + final VirtualHostAdapter virtualHostAdapter = (VirtualHostAdapter) virtualHostFactory.create(attributes,this); // permission has already been granted to create the virtual host // disable further access check on other operations, e.g. create exchange @@ -556,25 +565,25 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject @Override public long getBytesIn() { - return _statisticsGatherer.getDataReceiptStatistics().getTotal(); + return getDataReceiptStatistics().getTotal(); } @Override public long getBytesOut() { - return _statisticsGatherer.getDataDeliveryStatistics().getTotal(); + return getDataDeliveryStatistics().getTotal(); } @Override public long getMessagesIn() { - return _statisticsGatherer.getMessageReceiptStatistics().getTotal(); + return getMessageReceiptStatistics().getTotal(); } @Override public long getMessagesOut() { - return _statisticsGatherer.getMessageDeliveryStatistics().getTotal(); + return getMessageDeliveryStatistics().getTotal(); } @SuppressWarnings("unchecked") @Override @@ -657,17 +666,16 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject /** * Called when adding a new port via the management interface */ - private Port createPort(Map<String, Object> attributes) + private Port<?> createPort(Map<String, Object> attributes) { - Port<?> port = _portFactory.createPort(UUID.randomUUID(), this, attributes); - addPort(port); + Port<?> port = createChild(Port.class, attributes); //1. AMQP ports are disabled during ManagementMode. //2. The management plugins can currently only start ports at broker startup and // not when they are newly created via the management interfaces. //3. When active ports are deleted, or their port numbers updated, the broker must be // restarted for it to take effect so we can't reuse port numbers until it is. - boolean quiesce = isManagementMode() || !(port instanceof AmqpPortAdapter) || isPreviouslyUsedPortNumber(port); + boolean quiesce = isManagementMode() || !(port instanceof AmqpPort) || isPreviouslyUsedPortNumber(port); port.setDesiredState(State.INITIALISING, quiesce ? State.QUIESCED : State.ACTIVE); @@ -710,8 +718,7 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject AccessControlProvider<?> accessControlProvider; synchronized (_accessControlProviders) { - accessControlProvider = _accessControlProviderFactory.create(UUID.randomUUID(), this, attributes); - addAccessControlProvider(accessControlProvider); + accessControlProvider = (AccessControlProvider<?>) createChild(AccessControlProvider.class, attributes); } boolean quiesce = isManagementMode() ; @@ -765,12 +772,25 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject private AuthenticationProvider createAuthenticationProvider(Map<String, Object> attributes) { - AuthenticationProvider<?> authenticationProvider = _authenticationProviderFactory.create(UUID.randomUUID(), this, attributes); + AuthenticationProvider<?> authenticationProvider = createChild(AuthenticationProvider.class, attributes); authenticationProvider.setDesiredState(State.INITIALISING, State.ACTIVE); - addAuthenticationProvider(authenticationProvider); return authenticationProvider; } + private <X extends ConfiguredObject> X createChild(Class<X> clazz, Map<String, Object> attributes) + { + ConfiguredObjectTypeFactory factory = + _objectFactory.getConfiguredObjectTypeFactory(clazz, attributes); + if(!attributes.containsKey(ConfiguredObject.ID)) + { + attributes = new HashMap<String, Object>(attributes); + attributes.put(ConfiguredObject.ID, UUID.randomUUID()); + } + final X instance = (X) factory.create(attributes, this); + + return instance; + } + /** * @throws IllegalConfigurationException if an AuthenticationProvider with the same name already exists */ @@ -797,9 +817,8 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject private GroupProvider<?> createGroupProvider(Map<String, Object> attributes) { - GroupProvider<?> groupProvider = _groupProviderFactory.create(UUID.randomUUID(), this, attributes); + GroupProvider<?> groupProvider = createChild(GroupProvider.class, attributes); groupProvider.setDesiredState(State.INITIALISING, State.ACTIVE); - addGroupProvider(groupProvider); return groupProvider; } @@ -835,17 +854,13 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject private KeyStore createKeyStore(Map<String, Object> attributes) { - KeyStore keyStore = new KeyStoreAdapter(UUIDGenerator.generateRandomUUID(), this, attributes); - addKeyStore(keyStore); - + KeyStore keyStore = new FileKeyStore(UUIDGenerator.generateRandomUUID(), this, attributes); return keyStore; } private TrustStore createTrustStore(Map<String, Object> attributes) { - TrustStore trustStore = new TrustStoreAdapter(UUIDGenerator.generateRandomUUID(), this, attributes); - addTrustStore(trustStore); - + TrustStore trustStore = new FileTrustStore(UUIDGenerator.generateRandomUUID(), this, attributes); return trustStore; } @@ -951,10 +966,6 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject { return QpidProperties.getReleaseVersion(); } - else if(SUPPORTED_BROKER_STORE_TYPES.equals(name)) - { - return _supportedBrokerStoreTypes; - } else if(SUPPORTED_VIRTUALHOST_STORE_TYPES.equals(name)) { return _supportedVirtualHostStoreTypes; @@ -965,28 +976,16 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject } else if(SUPPORTED_AUTHENTICATION_PROVIDERS.equals(name)) { - return _authenticationProviderFactory.getSupportedAuthenticationProviders(); + return getSupportedAuthenticationProviders(); } else if (SUPPORTED_PREFERENCES_PROVIDER_TYPES.equals(name)) { - return PreferencesProviderFactory.FACTORY_LOADER.getSupportedTypes(); + return getSupportedPreferencesProviderTypes(); } else if (MODEL_VERSION.equals(name)) { return Model.MODEL_VERSION; } - else if (STORE_VERSION.equals(name)) - { - return _brokerStore.getVersion(); - } - else if (STORE_TYPE.equals(name)) - { - return _brokerStore.getType(); - } - else if (STORE_PATH.equals(name)) - { - return _brokerStore.getStoreLocation(); - } return super.getAttribute(name); } @@ -1048,6 +1047,7 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject { if (desiredState == State.ACTIVE) { + initialiseStatisticsReporting(); changeState(_groupProviders, currentState, State.ACTIVE, false); changeState(_authenticationProviders, currentState, State.ACTIVE, false); changeState(_accessControlProviders, currentState, State.ACTIVE, false); @@ -1067,11 +1067,18 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject } else if (desiredState == State.STOPPED) { + //Stop Statistics Reporting + if (_reportingTimer != null) + { + _reportingTimer.cancel(); + } + changeState(_plugins, currentState,State.STOPPED, true); changeState(_portAdapters, currentState, State.STOPPED, true); changeState(_vhostAdapters,currentState, State.STOPPED, true); changeState(_authenticationProviders, currentState, State.STOPPED, true); changeState(_groupProviders, currentState, State.STOPPED, true); + _virtualHostRegistry.close(); return true; } return false; @@ -1201,46 +1208,46 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject } } - public void recoverChild(ConfiguredObject object) + public void instantiateAuthenticationProvider(AuthenticationProvider object) { - if(object instanceof AuthenticationProvider) - { - addAuthenticationProvider((AuthenticationProvider)object); - } - else if(object instanceof AccessControlProvider) - { - addAccessControlProvider((AccessControlProvider)object); - } - else if(object instanceof Port) - { - addPort((Port)object); - } - else if(object instanceof VirtualHost) - { - addVirtualHost((VirtualHost)object); - } - else if(object instanceof GroupProvider) - { - addGroupProvider((GroupProvider)object); - } - else if(object instanceof KeyStore) - { - addKeyStore((KeyStore)object); - } - else if(object instanceof TrustStore) - { - addTrustStore((TrustStore)object); - } - else if(object instanceof Plugin) - { - addPlugin(object); - } - else - { - throw new IllegalArgumentException("Attempted to recover unexpected type of configured object: " + object.getClass().getName()); - } + addAuthenticationProvider(object); + } + + public void instantiateAccessControlProvider(AccessControlProvider object) + { + addAccessControlProvider(object); + } + + public void instantiatePort(Port object) + { + addPort(object); + } + + public void instantiateVirtualHost(VirtualHost object) + { + addVirtualHost(object); + } + + public void instantiateGroupProvider(GroupProvider object) + { + addGroupProvider(object); + } + + public void instantiateKeyStore(KeyStore object) + { + addKeyStore(object); + } + + public void instantiateTrustStore(TrustStore object) + { + addTrustStore(object); } + public void instantiatePlugin(Plugin object) + { + addPlugin(object); + } + @Override public SecurityManager getSecurityManager() { @@ -1280,9 +1287,9 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject Collection<Port<?>> ports = getPorts(); for (Port<?> p : ports) { - if (inetSocketAddress.getPort() == p.getPort()) + if (p instanceof PortWithAuthProvider && inetSocketAddress.getPort() == p.getPort()) { - provider = p.getAuthenticationProvider(); + provider = ((PortWithAuthProvider<?>) p).getAuthenticationProvider(); break; } } @@ -1335,12 +1342,6 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject throw new IllegalConfigurationException("Cannot change the model version"); } - if (convertedAttributes.containsKey(STORE_VERSION) - && !new Integer(_brokerStore.getVersion()).equals(convertedAttributes.get(STORE_VERSION))) - { - throw new IllegalConfigurationException("Cannot change the store version"); - } - String defaultVirtualHost = (String) convertedAttributes.get(DEFAULT_VIRTUAL_HOST); if (defaultVirtualHost != null) { @@ -1447,4 +1448,138 @@ public class BrokerAdapter<X extends Broker<X>> extends AbstractConfiguredObject { _eventLogger = eventLogger; } + + @Override + public StatisticsGatherer getStatisticsGatherer() + { + return this; + } + + public void registerMessageDelivered(long messageSize) + { + _messagesDelivered.registerEvent(1L); + _dataDelivered.registerEvent(messageSize); + } + + public void registerMessageReceived(long messageSize, long timestamp) + { + _messagesReceived.registerEvent(1L, timestamp); + _dataReceived.registerEvent(messageSize, timestamp); + } + + public StatisticsCounter getMessageReceiptStatistics() + { + return _messagesReceived; + } + + public StatisticsCounter getDataReceiptStatistics() + { + return _dataReceived; + } + + public StatisticsCounter getMessageDeliveryStatistics() + { + return _messagesDelivered; + } + + public StatisticsCounter getDataDeliveryStatistics() + { + return _dataDelivered; + } + + public void resetStatistics() + { + _messagesDelivered.reset(); + _dataDelivered.reset(); + _messagesReceived.reset(); + _dataReceived.reset(); + + for (org.apache.qpid.server.virtualhost.VirtualHost vhost : _virtualHostRegistry.getVirtualHosts()) + { + vhost.resetStatistics(); + } + } + + public void initialiseStatistics() + { + _messagesDelivered = new StatisticsCounter("messages-delivered"); + _dataDelivered = new StatisticsCounter("bytes-delivered"); + _messagesReceived = new StatisticsCounter("messages-received"); + _dataReceived = new StatisticsCounter("bytes-received"); + } + + private class StatisticsReportingTask extends TimerTask + { + private final int DELIVERED = 0; + private final int RECEIVED = 1; + + private final boolean _reset; + private final EventLogger _logger; + private final Subject _subject; + + public StatisticsReportingTask(boolean reset, EventLogger logger) + { + _reset = reset; + _logger = logger; + _subject = SecurityManager.getSystemTaskSubject("Statistics"); + } + + public void run() + { + Subject.doAs(_subject, new PrivilegedAction<Object>() + { + @Override + public Object run() + { + reportStatistics(); + return null; + } + }); + } + + protected void reportStatistics() + { + try + { + _eventLogger.message(BrokerMessages.STATS_DATA(DELIVERED, _dataDelivered.getPeak() / 1024.0, _dataDelivered.getTotal())); + _eventLogger.message(BrokerMessages.STATS_MSGS(DELIVERED, _messagesDelivered.getPeak(), _messagesDelivered.getTotal())); + _eventLogger.message(BrokerMessages.STATS_DATA(RECEIVED, _dataReceived.getPeak() / 1024.0, _dataReceived.getTotal())); + _eventLogger.message(BrokerMessages.STATS_MSGS(RECEIVED, + _messagesReceived.getPeak(), + _messagesReceived.getTotal())); + Collection<org.apache.qpid.server.virtualhost.VirtualHost> hosts = _virtualHostRegistry.getVirtualHosts(); + + if (hosts.size() > 1) + { + for (org.apache.qpid.server.virtualhost.VirtualHost vhost : hosts) + { + String name = vhost.getName(); + StatisticsCounter dataDelivered = vhost.getDataDeliveryStatistics(); + StatisticsCounter messagesDelivered = vhost.getMessageDeliveryStatistics(); + StatisticsCounter dataReceived = vhost.getDataReceiptStatistics(); + StatisticsCounter messagesReceived = vhost.getMessageReceiptStatistics(); + EventLogger logger = vhost.getEventLogger(); + logger.message(VirtualHostMessages.STATS_DATA(name, + DELIVERED, + dataDelivered.getPeak() / 1024.0, + dataDelivered.getTotal())); + logger.message(VirtualHostMessages.STATS_MSGS(name, DELIVERED, messagesDelivered.getPeak(), messagesDelivered.getTotal())); + logger.message(VirtualHostMessages.STATS_DATA(name, RECEIVED, dataReceived.getPeak() / 1024.0, dataReceived.getTotal())); + logger.message(VirtualHostMessages.STATS_MSGS(name, RECEIVED, messagesReceived.getPeak(), messagesReceived.getTotal())); + } + } + + if (_reset) + { + resetStatistics(); + } + } + catch(Exception e) + { + LOGGER.warn("Unexpected exception occurred while reporting the statistics", e); + } + } + } + + } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapterFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapterFactory.java new file mode 100644 index 0000000000..8bbe446dc3 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapterFactory.java @@ -0,0 +1,48 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.adapter; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.model.SystemContext; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class BrokerAdapterFactory extends AbstractConfiguredObjectTypeFactory<BrokerAdapter> +{ + public BrokerAdapterFactory() + { + super(BrokerAdapter.class); + } + + @Override + public BrokerAdapter createInstance(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + SystemContext context = getParent(SystemContext.class, parents); + Map<String,Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(ConfiguredObject.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + return new BrokerAdapter(id, attributesWithoutId, context); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/ConnectionAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/ConnectionAdapter.java index 0da93fa784..d626252cad 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/ConnectionAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/ConnectionAdapter.java @@ -30,7 +30,6 @@ import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.protocol.AMQConnectionModel; import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.protocol.SessionModelListener; -import org.apache.qpid.server.stats.StatisticsGatherer; final class ConnectionAdapter extends AbstractConfiguredObject<ConnectionAdapter> implements Connection<ConnectionAdapter>, SessionModelListener diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/GroupProviderAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileBasedGroupProvider.java index 4c2d2ac4e0..06c3f9a74c 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/GroupProviderAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileBasedGroupProvider.java @@ -19,65 +19,85 @@ */ package org.apache.qpid.server.model.adapter; +import java.io.File; +import java.io.IOException; import java.security.AccessControlException; import java.security.Principal; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import org.apache.log4j.Logger; +import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.model.*; import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.security.access.Operation; +import org.apache.qpid.server.security.group.FileGroupManager; import org.apache.qpid.server.security.group.GroupManager; import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.server.util.MapValueConverter; -public class GroupProviderAdapter extends AbstractConfiguredObject<GroupProviderAdapter> implements GroupProvider<GroupProviderAdapter> +@ManagedObject( category = false, type = "GroupFile" ) +public class FileBasedGroupProvider + extends AbstractConfiguredObject<FileBasedGroupProvider> implements GroupProvider<FileBasedGroupProvider> { - private static Logger LOGGER = Logger.getLogger(GroupProviderAdapter.class); + private static Logger LOGGER = Logger.getLogger(FileBasedGroupProvider.class); private final GroupManager _groupManager; - private final Broker _broker; - private Collection<String> _supportedAttributes; + private final Broker<?> _broker; private AtomicReference<State> _state; - public GroupProviderAdapter(UUID id, Broker broker, GroupManager groupManager, Map<String, Object> attributes, Collection<String> attributeNames) + @ManagedAttributeField + private String _path; + + public FileBasedGroupProvider(UUID id, + Broker broker, + Map<String, Object> attributes) { - super(id, Collections.singletonMap(NAME, attributes.get(NAME)), Collections.<String,Object>emptyMap(), broker.getTaskExecutor()); + super(Collections.<Class<? extends ConfiguredObject>,ConfiguredObject<?>>singletonMap(Broker.class, broker), + Collections.<String,Object>emptyMap(), combineIdWithAttributes(id, attributes), broker.getTaskExecutor()); - if (groupManager == null) - { - throw new IllegalArgumentException("GroupManager must not be null"); - } - _groupManager = groupManager; + _groupManager = new FileGroupManager(getPath()); _broker = broker; - _supportedAttributes = createSupportedAttributes(attributeNames); + State state = MapValueConverter.getEnumAttribute(State.class, STATE, attributes, State.INITIALISING); _state = new AtomicReference<State>(state); - addParent(Broker.class, broker); - - // set attributes now after all attribute names are known - if (attributes != null) - { - for (String name : _supportedAttributes) - { - if (attributes.containsKey(name)) - { - changeAttribute(name, null, attributes.get(name)); - } - } - } + validateUniqueFile(); } - protected Collection<String> createSupportedAttributes(Collection<String> factoryAttributes) + private void validateUniqueFile() { - List<String> attributesNames = new ArrayList<String>(getAttributeNames(GroupProvider.class)); - if (factoryAttributes != null) + Collection<GroupProvider<?>> groupProviders = _broker.getGroupProviders(); + for(GroupProvider<?> provider : groupProviders) { - attributesNames.addAll(factoryAttributes); + if(provider instanceof FileBasedGroupProvider && provider != this) + { + try + { + if(new File(getPath()).getCanonicalPath().equals(new File(((FileBasedGroupProvider)provider).getPath()).getCanonicalPath())) + { + throw new IllegalConfigurationException("Cannot have two group providers using the same file: " + getPath()); + } + } + catch (IOException e) + { + throw new IllegalArgumentException("Invalid path", e); + } + } } + } - return Collections.unmodifiableCollection(attributesNames); + + @Override + protected void create() + { + _groupManager.onCreate(); + super.create(); + } + + @ManagedAttribute( automate = true, mandatory = true) + public String getPath() + { + return _path; } @Override @@ -122,7 +142,7 @@ public class GroupProviderAdapter extends AbstractConfiguredObject<GroupProvider @Override public Collection<String> getAttributeNames() { - return _supportedAttributes; + return getAttributeNames(getClass()); } @Override @@ -132,10 +152,6 @@ public class GroupProviderAdapter extends AbstractConfiguredObject<GroupProvider { return true; } - else if (ID.equals(name)) - { - return getId(); - } else if (LIFETIME_POLICY.equals(name)) { return LifetimePolicy.PERMANENT; @@ -388,7 +404,7 @@ public class GroupProviderAdapter extends AbstractConfiguredObject<GroupProvider Collection<GroupMember> members = new ArrayList<GroupMember>(); for (Principal principal : usersInGroup) { - UUID id = UUIDGenerator.generateGroupMemberUUID(GroupProviderAdapter.this.getName(), getName(), principal.getName()); + UUID id = UUIDGenerator.generateGroupMemberUUID(FileBasedGroupProvider.this.getName(), getName(), principal.getName()); Map<String,Object> attrMap = new HashMap<String, Object>(); attrMap.put(GroupMember.ID,id); attrMap.put(GroupMember.NAME, principal.getName()); @@ -416,7 +432,7 @@ public class GroupProviderAdapter extends AbstractConfiguredObject<GroupProvider getSecurityManager().authoriseGroupOperation(Operation.UPDATE, getName()); _groupManager.addUserToGroup(memberName, getName()); - UUID id = UUIDGenerator.generateGroupMemberUUID(GroupProviderAdapter.this.getName(), getName(), memberName); + UUID id = UUIDGenerator.generateGroupMemberUUID(FileBasedGroupProvider.this.getName(), getName(), memberName); Map<String,Object> attrMap = new HashMap<String, Object>(); attrMap.put(GroupMember.ID,id); attrMap.put(GroupMember.NAME, memberName); @@ -541,14 +557,6 @@ public class GroupProviderAdapter extends AbstractConfiguredObject<GroupProvider } @Override - public <C extends ConfiguredObject> C createChild( - Class<C> childClass, Map<String, Object> attributes, - ConfiguredObject... otherParents) - { - return null; - } - - @Override protected boolean setState(State currentState, State desiredState) throws IllegalStateTransitionException, AccessControlException diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileBasedGroupProviderFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileBasedGroupProviderFactory.java new file mode 100644 index 0000000000..8d7ec4bff2 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileBasedGroupProviderFactory.java @@ -0,0 +1,48 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.adapter; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class FileBasedGroupProviderFactory extends AbstractConfiguredObjectTypeFactory<FileBasedGroupProvider> +{ + public FileBasedGroupProviderFactory() + { + super(FileBasedGroupProvider.class); + } + + @Override + public FileBasedGroupProvider createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) + { + Map<String,Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(ConfiguredObject.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + return new FileBasedGroupProvider(id, getParent(Broker.class, parents), attributesWithoutId); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProvider.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProvider.java index 5e3a3061d0..7fc11e1644 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProvider.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProvider.java @@ -21,6 +21,16 @@ package org.apache.qpid.server.model.adapter; +import org.apache.log4j.Logger; +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.model.*; +import org.apache.qpid.server.util.MapValueConverter; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.JsonProcessingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.SerializationConfig; +import org.codehaus.jackson.type.TypeReference; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -31,27 +41,10 @@ import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.security.AccessControlException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.UUID; +import java.util.*; import java.util.concurrent.atomic.AtomicReference; -import org.apache.log4j.Logger; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.model.*; -import org.apache.qpid.server.util.MapValueConverter; -import org.codehaus.jackson.JsonParser; -import org.codehaus.jackson.JsonProcessingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.codehaus.jackson.type.TypeReference; - +@ManagedObject( category = false, type = "FileSystemPreferences" ) public class FileSystemPreferencesProvider extends AbstractConfiguredObject<FileSystemPreferencesProvider> implements PreferencesProvider<FileSystemPreferencesProvider> { private static final Logger LOGGER = Logger.getLogger(FileSystemPreferencesProvider.class); @@ -77,16 +70,18 @@ public class FileSystemPreferencesProvider extends AbstractConfiguredObject<File private FileSystemPreferencesStore _store; - protected FileSystemPreferencesProvider(UUID id, Map<String, Object> attributes, - AuthenticationProvider<? extends AuthenticationProvider> authenticationProvider, - TaskExecutor taskExecutor) + public FileSystemPreferencesProvider(UUID id, Map<String, Object> attributes, + AuthenticationProvider<? extends AuthenticationProvider> authenticationProvider) { - super(id, DEFAULTS, MapValueConverter.convert(attributes, ATTRIBUTE_TYPES), taskExecutor); + super(Collections.<Class<? extends ConfiguredObject>, ConfiguredObject<?>>singletonMap(AuthenticationProvider.class, authenticationProvider), + DEFAULTS, + combineIdWithAttributes(id,MapValueConverter.convert(attributes, ATTRIBUTE_TYPES)), + authenticationProvider.getParent(Broker.class).getTaskExecutor()); State state = MapValueConverter.getEnumAttribute(State.class, STATE, attributes, State.INITIALISING); _state = new AtomicReference<State>(state); - addParent(AuthenticationProvider.class, authenticationProvider); _authenticationProvider = authenticationProvider; _store = new FileSystemPreferencesStore(new File(MapValueConverter.getStringAttribute(PATH, attributes))); + createStoreIfNotExist(); } @Override diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactory.java index 666fa47557..abf0dbb863 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactory.java @@ -21,33 +21,29 @@ package org.apache.qpid.server.model.adapter; +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.AuthenticationProvider; +import org.apache.qpid.server.model.ConfiguredObject; + +import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.plugin.PreferencesProviderFactory; - -public class FileSystemPreferencesProviderFactory implements PreferencesProviderFactory +public class FileSystemPreferencesProviderFactory extends AbstractConfiguredObjectTypeFactory<FileSystemPreferencesProvider> { - @Override - public String getType() + public FileSystemPreferencesProviderFactory() { - return FileSystemPreferencesProvider.PROVIDER_TYPE; + super(FileSystemPreferencesProvider.class); } @Override - public PreferencesProvider createInstance(UUID id, Map<String, Object> attributes, - AuthenticationProvider<? extends AuthenticationProvider> authenticationProvider) + public FileSystemPreferencesProvider createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) { - Broker<?> broker = authenticationProvider.getParent(Broker.class); - FileSystemPreferencesProvider provider = new FileSystemPreferencesProvider(id, attributes, authenticationProvider, broker.getTaskExecutor()); - - // create store if such does not exist - provider.createStoreIfNotExist(); - return provider; + Map<String,Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(ConfiguredObject.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + return new FileSystemPreferencesProvider(id, attributesWithoutId, getParent(AuthenticationProvider.class,parents)); } - } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/GroupProviderFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/GroupProviderFactory.java deleted file mode 100644 index 1d3ccd81b3..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/GroupProviderFactory.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.model.adapter; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.plugin.GroupManagerFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.security.group.GroupManager; - -public class GroupProviderFactory -{ - private final Map<String, GroupManagerFactory> _factories; - private Collection<String> _supportedGroupProviders; - - public GroupProviderFactory(QpidServiceLoader<GroupManagerFactory> groupManagerFactoryServiceLoader) - { - Iterable<GroupManagerFactory> factories = groupManagerFactoryServiceLoader.instancesOf(GroupManagerFactory.class); - - Map<String, GroupManagerFactory> registeredGroupProviderFactories = new HashMap<String, GroupManagerFactory>(); - for (GroupManagerFactory factory : factories) - { - GroupManagerFactory existingFactory = registeredGroupProviderFactories.put(factory.getType(), factory); - if (existingFactory != null) - { - throw new IllegalConfigurationException("Group provider factory of the same type '" + factory.getType() - + "' is already registered using class '" + existingFactory.getClass().getName() - + "', can not register class '" + factory.getClass().getName() + "'"); - } - } - _factories = registeredGroupProviderFactories; - _supportedGroupProviders = Collections.unmodifiableCollection(registeredGroupProviderFactories.keySet()); - } - - /** - * Creates {@link GroupProvider} for given ID, {@link Broker} and attributes. - * <p> - * The configured {@link GroupManagerFactory}'s are used to try to create the {@link GroupProvider}. The first non-null - * instance is returned. The factories are used in non-deterministic order. - */ - public GroupProvider create(UUID id, Broker broker, Map<String, Object> attributes) - { - GroupProviderAdapter authenticationProvider = createGroupProvider(id, broker, attributes); - authenticationProvider.getGroupManager().onCreate(); - return authenticationProvider; - } - - /** - * Recovers {@link GroupProvider} with given ID, {@link Broker} and attributes. - * <p> - * The configured {@link GroupManagerFactory}'s are used to try to create the {@link GroupProvider}. The first non-null - * instance is returned. The factories are used in non-deterministic order. - */ - public GroupProvider recover(UUID id, Broker broker, Map<String, Object> attributes) - { - return createGroupProvider(id, broker, attributes); - } - - public Collection<String> getSupportedGroupProviders() - { - return _supportedGroupProviders; - } - - private GroupProviderAdapter createGroupProvider(UUID id, Broker broker, Map<String, Object> attributes) - { - for (GroupManagerFactory factory : _factories.values()) - { - GroupManager manager = factory.createInstance(attributes); - if (manager != null) - { - verifyGroupManager(manager, broker); - return new GroupProviderAdapter(id, broker, manager, attributes,factory.getAttributeNames()); - } - } - throw new IllegalConfigurationException("No group provider factory found for configuration attributes " + attributes); - } - - private void verifyGroupManager(GroupManager manager, Broker broker) - { - Collection<GroupProvider> groupProviders = broker.getGroupProviders(); - for (GroupProvider groupProvider : groupProviders) - { - if (groupProvider instanceof GroupProviderAdapter) - { - GroupManager providerManager = ((GroupProviderAdapter) groupProvider).getGroupManager(); - if (manager.equals(providerManager)) - { - throw new IllegalConfigurationException("A group provider with the same settings already exists"); - } - } - } - } -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/PortFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/PortFactory.java deleted file mode 100644 index 8d7ba3688e..0000000000 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/PortFactory.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.model.adapter; - -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.Protocol; -import org.apache.qpid.server.model.Protocol.ProtocolType; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.util.MapValueConverter; - -public class PortFactory -{ - public static final int DEFAULT_AMQP_SEND_BUFFER_SIZE = 262144; - public static final int DEFAULT_AMQP_RECEIVE_BUFFER_SIZE = 262144; - public static final boolean DEFAULT_AMQP_NEED_CLIENT_AUTH = false; - public static final boolean DEFAULT_AMQP_WANT_CLIENT_AUTH = false; - public static final boolean DEFAULT_AMQP_TCP_NO_DELAY = true; - public static final String DEFAULT_AMQP_BINDING = "*"; - public static final Transport DEFAULT_TRANSPORT = Transport.TCP; - - private final Collection<Protocol> _defaultProtocols; - - public PortFactory() - { - Set<Protocol> defaultProtocols = EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1, - Protocol.AMQP_0_10, Protocol.AMQP_1_0); - String excludedProtocols = System.getProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_EXCLUDES); - if (excludedProtocols != null) - { - String[] excludes = excludedProtocols.split(","); - for (String exclude : excludes) - { - Protocol protocol = Protocol.valueOf(exclude); - defaultProtocols.remove(protocol); - } - } - String includedProtocols = System.getProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_INCLUDES); - if (includedProtocols != null) - { - String[] includes = includedProtocols.split(","); - for (String include : includes) - { - Protocol protocol = Protocol.valueOf(include); - defaultProtocols.add(protocol); - } - } - _defaultProtocols = Collections.unmodifiableCollection(defaultProtocols); - } - - public Port createPort(UUID id, Broker broker, Map<String, Object> attributes) - { - final Port port; - Map<String, Object> defaults = new HashMap<String, Object>(); - defaults.put(Port.TRANSPORTS, Collections.singleton(DEFAULT_TRANSPORT)); - Object portValue = attributes.get(Port.PORT); - if (portValue == null) - { - throw new IllegalConfigurationException("Port attribute is not specified for port: " + attributes); - } - Set<Protocol> protocols = MapValueConverter.getEnumSetAttribute(Port.PROTOCOLS, attributes, Protocol.class); - if (isAmqpProtocol(protocols, attributes)) - { - Object binding = attributes.get(Port.BINDING_ADDRESS); - if (binding == null) - { - binding = DEFAULT_AMQP_BINDING; - defaults.put(Port.BINDING_ADDRESS, DEFAULT_AMQP_BINDING); - } - defaults.put(Port.NAME, binding + ":" + portValue); - defaults.put(Port.PROTOCOLS, _defaultProtocols); - defaults.put(Port.TCP_NO_DELAY, DEFAULT_AMQP_TCP_NO_DELAY); - defaults.put(Port.WANT_CLIENT_AUTH, DEFAULT_AMQP_WANT_CLIENT_AUTH); - defaults.put(Port.NEED_CLIENT_AUTH, DEFAULT_AMQP_NEED_CLIENT_AUTH); - defaults.put(Port.RECEIVE_BUFFER_SIZE, DEFAULT_AMQP_RECEIVE_BUFFER_SIZE); - defaults.put(Port.SEND_BUFFER_SIZE, DEFAULT_AMQP_SEND_BUFFER_SIZE); - port = new AmqpPortAdapter(id, broker, attributes, defaults, broker.getTaskExecutor()); - - boolean useClientAuth = (Boolean) port.getAttribute(Port.NEED_CLIENT_AUTH) || (Boolean) port.getAttribute(Port.WANT_CLIENT_AUTH); - if(useClientAuth && port.getTrustStores().isEmpty()) - { - throw new IllegalConfigurationException("Can't create port which requests SSL client certificates but has no trust stores configured."); - } - - if(useClientAuth && !(port.getTransports().contains(Transport.SSL) || port.getTransports().contains(Transport.WSS))) - { - throw new IllegalConfigurationException("Can't create port which requests SSL client certificates but doesn't use SSL transport."); - } - } - else - { - if (protocols.size() > 1) - { - throw new IllegalConfigurationException("Only one protocol can be used on non AMQP port"); - } - Protocol protocol = protocols.iterator().next(); - - if(!broker.isManagementMode() && protocol.getProtocolType() != ProtocolType.HTTP) - { - //ManagementMode needs this relaxed to allow its overriding management ports to be inserted. - - //Enforce only a single port of each management protocol, as the plugins will only use one. - Collection<Port> existingPorts = broker.getPorts(); - for (Port existingPort : existingPorts) - { - Collection<Protocol> portProtocols = existingPort.getProtocols(); - if (portProtocols != null && portProtocols.contains(protocol)) - { - throw new IllegalConfigurationException("Port for protocol " + protocol + " already exists. Only one management port per protocol can be created."); - } - } - } - - defaults.put(Port.NAME, portValue + "-" + protocol.name()); - port = new NonAmqpPortAdapter(id, broker, attributes, defaults, broker.getTaskExecutor()); - - boolean rmiPort = port.getProtocols().contains(Protocol.RMI); - if (rmiPort && port.getTransports().contains(Transport.SSL)) - { - throw new IllegalConfigurationException("Can't create RMI registry port which requires SSL"); - } - } - - if(port.getTransports().contains(Transport.SSL)) - { - if(port.getKeyStore() == null) - { - throw new IllegalConfigurationException("Can't create port which requires SSL but has no key store configured."); - } - } - - return port; - } - - private boolean isAmqpProtocol(Set<Protocol> protocols, Map<String, Object> portAttributes) - { - if (protocols == null || protocols.isEmpty()) - { - // defaulting to AMQP if protocol is not specified - return true; - } - - Set<ProtocolType> protocolTypes = new HashSet<ProtocolType>(); - for (Protocol protocolObject : protocols) - { - protocolTypes.add(protocolObject.getProtocolType()); - } - - if (protocolTypes.size() > 1) - { - throw new IllegalConfigurationException("Found different protocol types '" + protocolTypes - + "' for port configuration: " + portAttributes); - } - - return protocolTypes.contains(ProtocolType.AMQP); - } - - public Collection<Protocol> getDefaultProtocols() - { - return _defaultProtocols; - } - -} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/SessionAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/SessionAdapter.java index 19d174a157..91d91d5f67 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/SessionAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/SessionAdapter.java @@ -21,7 +21,6 @@ package org.apache.qpid.server.model.adapter; import java.security.AccessControlException; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -29,12 +28,10 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.apache.qpid.server.consumer.ConsumerImpl; import org.apache.qpid.server.model.*; import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.protocol.ConsumerListener; -import org.apache.qpid.server.queue.QueueConsumer; final class SessionAdapter extends AbstractConfiguredObject<SessionAdapter> implements Session<SessionAdapter> { @@ -165,12 +162,6 @@ final class SessionAdapter extends AbstractConfiguredObject<SessionAdapter> impl } @Override - public <C extends ConfiguredObject> C createChild(Class<C> childClass, Map<String, Object> attributes, ConfiguredObject... otherParents) - { - throw new UnsupportedOperationException(); - } - - @Override public long getConsumerCount() { return _session.getConsumerCount(); diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/NonAmqpPortAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/StandardVirtualHostAdapter.java index 24b880c1b7..4577bd94a3 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/NonAmqpPortAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/StandardVirtualHostAdapter.java @@ -20,20 +20,19 @@ */ package org.apache.qpid.server.model.adapter; -import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; import java.util.Map; import java.util.UUID; -public class NonAmqpPortAdapter extends PortAdapter<NonAmqpPortAdapter> +@ManagedObject( category = false, type = "STANDARD") +public class StandardVirtualHostAdapter extends VirtualHostAdapter<StandardVirtualHostAdapter> { - public NonAmqpPortAdapter(final UUID id, - final Broker<?> broker, - final Map<String, Object> attributes, - final Map<String, Object> defaults, - final TaskExecutor taskExecutor) + public StandardVirtualHostAdapter(final UUID id, + final Map<String, Object> attributes, + final Broker<?> broker) { - super(id, broker, attributes, defaults, taskExecutor); + super(id, attributes, broker); } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/StandardVirtualHostAdapterFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/StandardVirtualHostAdapterFactory.java new file mode 100644 index 0000000000..5dc0a2decb --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/StandardVirtualHostAdapterFactory.java @@ -0,0 +1,51 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.adapter; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class StandardVirtualHostAdapterFactory extends AbstractConfiguredObjectTypeFactory<StandardVirtualHostAdapter> +{ + + public StandardVirtualHostAdapterFactory() + { + super(StandardVirtualHostAdapter.class); + } + + @Override + public StandardVirtualHostAdapter createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) + { + Map<String,Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(ConfiguredObject.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + final Broker broker = getParent(Broker.class, parents); + return new StandardVirtualHostAdapter(id, attributesWithoutId, broker); + } + + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/VirtualHostAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/VirtualHostAdapter.java index fafe081226..25009de748 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/VirtualHostAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/VirtualHostAdapter.java @@ -20,45 +20,44 @@ */ package org.apache.qpid.server.model.adapter; -import java.lang.reflect.Type; -import java.security.AccessControlException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - import org.apache.log4j.Logger; -import org.apache.qpid.server.exchange.AMQUnknownExchangeType; import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.exchange.AMQUnknownExchangeType; import org.apache.qpid.server.exchange.ExchangeImpl; import org.apache.qpid.server.message.MessageInstance; import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.model.*; -import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.plugin.ExchangeType; +import org.apache.qpid.server.plugin.VirtualHostFactory; import org.apache.qpid.server.protocol.AMQConnectionModel; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.ConflationQueue; import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.stats.StatisticsGatherer; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.txn.LocalTransaction; import org.apache.qpid.server.txn.ServerTransaction; import org.apache.qpid.server.util.MapValueConverter; import org.apache.qpid.server.util.ParameterizedTypeImpl; -import org.apache.qpid.server.plugin.VirtualHostFactory; -import org.apache.qpid.server.util.ServerScopedRuntimeException; import org.apache.qpid.server.virtualhost.ExchangeExistsException; +import org.apache.qpid.server.virtualhost.QueueExistsException; import org.apache.qpid.server.virtualhost.ReservedExchangeNameException; import org.apache.qpid.server.virtualhost.UnknownExchangeException; import org.apache.qpid.server.virtualhost.VirtualHostListener; import org.apache.qpid.server.virtualhost.VirtualHostRegistry; -import org.apache.qpid.server.virtualhost.QueueExistsException; -public final class VirtualHostAdapter extends AbstractConfiguredObject<VirtualHostAdapter> implements VirtualHost<VirtualHostAdapter>, VirtualHostListener +import java.lang.reflect.Type; +import java.security.AccessControlException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@ManagedObject( category = false, type = "STANDARD") +public class VirtualHostAdapter<X extends VirtualHostAdapter<X>> extends AbstractConfiguredObject<X> implements VirtualHost<X>, VirtualHostListener { private static final Logger LOGGER = Logger.getLogger(VirtualHostAdapter.class); @@ -101,15 +100,19 @@ public final class VirtualHostAdapter extends AbstractConfiguredObject<VirtualHo private final Broker<?> _broker; private final List<VirtualHostAlias> _aliases = new ArrayList<VirtualHostAlias>(); - private StatisticsGatherer _brokerStatisticsGatherer; - public VirtualHostAdapter(UUID id, Map<String, Object> attributes, Broker<?> broker, StatisticsGatherer brokerStatisticsGatherer, TaskExecutor taskExecutor) + public VirtualHostAdapter(UUID id, + Map<String, Object> attributes, + Broker<?> broker) { - super(id, DEFAULTS, MapValueConverter.convert(attributes, ATTRIBUTE_TYPES, false), taskExecutor, false); + super(Collections.<Class<? extends ConfiguredObject>, ConfiguredObject<?>>singletonMap(Broker.class,broker), + DEFAULTS, + combineIdWithAttributes(id, MapValueConverter.convert(attributes, ATTRIBUTE_TYPES, false)), + broker.getTaskExecutor(), + false); + _broker = broker; - _brokerStatisticsGatherer = brokerStatisticsGatherer; validateAttributes(); - addParent(Broker.class, broker); } private void validateAttributes() @@ -1003,25 +1006,18 @@ public final class VirtualHostAdapter extends AbstractConfiguredObject<VirtualHo { VirtualHostRegistry virtualHostRegistry = _broker.getVirtualHostRegistry(); String virtualHostName = getName(); - try + String type = (String) getAttribute(TYPE); + final VirtualHostFactory factory = VirtualHostFactory.FACTORIES.get(type); + if(factory == null) { - String type = (String) getAttribute(TYPE); - final VirtualHostFactory factory = VirtualHostFactory.FACTORIES.get(type); - if(factory == null) - { - throw new IllegalArgumentException("Unknown virtual host type: " + type); - } - else - { - _virtualHost = factory.createVirtualHost(_broker.getVirtualHostRegistry(), - _brokerStatisticsGatherer, - _broker.getSecurityManager(), - this); - } + throw new IllegalArgumentException("Unknown virtual host type: " + type); } - catch (Exception e) + else { - throw new ServerScopedRuntimeException("Failed to create virtual host " + virtualHostName, e); + _virtualHost = factory.createVirtualHost(_broker.getVirtualHostRegistry(), + _broker, + _broker.getSecurityManager(), + this); } virtualHostRegistry.registerVirtualHost(_virtualHost); diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/VirtualHostAliasAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/VirtualHostAliasAdapter.java index ae7325c928..0d7254b672 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/VirtualHostAliasAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/VirtualHostAliasAdapter.java @@ -23,14 +23,8 @@ package org.apache.qpid.server.model.adapter; import java.util.HashMap; import java.util.Map; -import org.apache.qpid.server.model.AuthenticationMethod; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.LifetimePolicy; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.VirtualHostAlias; + +import org.apache.qpid.server.model.*; import java.security.AccessControlException; import java.util.Collection; @@ -119,12 +113,6 @@ public class VirtualHostAliasAdapter extends AbstractConfiguredObject<VirtualHos } @Override - public <C extends ConfiguredObject> C createChild(Class<C> childClass, Map<String, Object> attributes, ConfiguredObject... otherParents) - { - throw new UnsupportedOperationException(); - } - - @Override protected boolean setState(State currentState, State desiredState) { // TODO: state is not supported at the moment diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/PortAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/AbstractPort.java index aa7550b510..e758e1a1dd 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/PortAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/AbstractPort.java @@ -19,7 +19,7 @@ * */ -package org.apache.qpid.server.model.adapter; +package org.apache.qpid.server.model.port; import java.lang.reflect.Type; import java.security.AccessControlException; @@ -40,7 +40,7 @@ import org.apache.qpid.server.util.ParameterizedTypeImpl; import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.configuration.updater.TaskExecutor; -abstract public class PortAdapter<X extends PortAdapter<X>> extends AbstractConfiguredObject<X> implements Port<X> +abstract public class AbstractPort<X extends AbstractPort<X>> extends AbstractConfiguredObject<X> implements Port<X> { @SuppressWarnings("serial") public static final Map<String, Type> ATTRIBUTE_TYPES = Collections.unmodifiableMap(new HashMap<String, Type>(){{ @@ -60,35 +60,67 @@ abstract public class PortAdapter<X extends PortAdapter<X>> extends AbstractConf put(AUTHENTICATION_PROVIDER, String.class); }}); + public static final Transport DEFAULT_TRANSPORT = Transport.TCP; + private final Broker<?> _broker; - private AuthenticationProvider _authenticationProvider; private AtomicReference<State> _state; - public PortAdapter(UUID id, Broker<?> broker, Map<String, Object> attributes, Map<String, Object> defaults, TaskExecutor taskExecutor) + public AbstractPort(UUID id, + Broker<?> broker, + Map<String, Object> attributes, + Map<String, Object> defaults, + TaskExecutor taskExecutor) { - super(id, defaults, MapValueConverter.convert(attributes, ATTRIBUTE_TYPES), taskExecutor); + super(Collections.<Class<? extends ConfiguredObject>,ConfiguredObject<?>>singletonMap(Broker.class, broker), + updateDefaults(defaults, attributes), + combineIdWithAttributes(id,MapValueConverter.convert(attributes, ATTRIBUTE_TYPES)), + taskExecutor); _broker = broker; + + Object portValue = attributes.get(Port.PORT); + if (portValue == null) + { + throw new IllegalConfigurationException("Port attribute is not specified for port: " + attributes); + } + State state = MapValueConverter.getEnumAttribute(State.class, STATE, attributes, State.INITIALISING); + _state = new AtomicReference<State>(state); - Collection<Protocol> protocols = getProtocols(); - boolean rmiRegistry = protocols != null && protocols.contains(Protocol.RMI); - if (!rmiRegistry) + + boolean useClientAuth = Boolean.TRUE.equals(getAttribute(Port.NEED_CLIENT_AUTH)) + || Boolean.TRUE.equals(getAttribute(Port.WANT_CLIENT_AUTH)); + + if(useClientAuth && getTrustStores().isEmpty()) { - String authProvider = (String)getAttribute(Port.AUTHENTICATION_PROVIDER); - if (authProvider == null) - { - throw new IllegalConfigurationException("An authentication provider must be specified for port : " + getName()); - } - _authenticationProvider = broker.findAuthenticationProviderByName(authProvider); + throw new IllegalConfigurationException("Can't create port which requests SSL client certificates but has no trust stores configured."); + } - if(_authenticationProvider == null) - { - throw new IllegalConfigurationException("The authentication provider '" + authProvider + "' could not be found for port : " + getName()); - } + boolean useTLSTransport = getTransports().contains(Transport.SSL) || getTransports().contains(Transport.WSS); + if(useClientAuth && !useTLSTransport) + { + throw new IllegalConfigurationException( + "Can't create port which requests SSL client certificates but doesn't use SSL transport."); } + if(useTLSTransport && getKeyStore() == null) + { + throw new IllegalConfigurationException("Can't create a port which uses a secure transport but has no KeyStore"); + } + } - _state = new AtomicReference<State>(state); - addParent(Broker.class, broker); + + private static Map<String, Object> updateDefaults(final Map<String, Object> defaults, + final Map<String, Object> attributes) + { + Map<String, Object> updatedDefaults = new HashMap<String, Object>(defaults); + if(!defaults.containsKey(TRANSPORTS)) + { + updatedDefaults.put(Port.TRANSPORTS, Collections.singleton(DEFAULT_TRANSPORT)); + } + if(!defaults.containsKey(NAME)) + { + updatedDefaults.put(NAME, attributes.get(PORT) + "-" + attributes.get(TYPE)); + } + return updatedDefaults; } @Override @@ -220,12 +252,6 @@ abstract public class PortAdapter<X extends PortAdapter<X>> extends AbstractConf } @Override - public <C extends ConfiguredObject> C createChild(Class<C> childClass, Map<String, Object> attributes, ConfiguredObject... otherParents) - { - throw new UnsupportedOperationException(); - } - - @Override public Object getAttribute(String name) { if(ID.equals(name)) @@ -250,7 +276,7 @@ abstract public class PortAdapter<X extends PortAdapter<X>> extends AbstractConf @Override public Collection<String> getAttributeNames() { - return getAttributeNames(Port.class); + return getAttributeNames(getClass()); } @Override @@ -325,12 +351,6 @@ abstract public class PortAdapter<X extends PortAdapter<X>> extends AbstractConf } @Override - public AuthenticationProvider getAuthenticationProvider() - { - return _authenticationProvider; - } - - @Override protected void changeAttributes(Map<String, Object> attributes) { Map<String, Object> converted = MapValueConverter.convert(attributes, ATTRIBUTE_TYPES); @@ -546,4 +566,30 @@ abstract public class PortAdapter<X extends PortAdapter<X>> extends AbstractConf { return (Boolean)getAttribute(WANT_CLIENT_AUTH); } + + protected void validateOnlyOneInstance(final Broker<?> broker) + { + if(!broker.isManagementMode()) + { + //ManagementMode needs this relaxed to allow its overriding management ports to be inserted. + + //Enforce only a single port of each management protocol, as the plugins will only use one. + Collection<Port<?>> existingPorts = broker.getPorts(); + existingPorts.remove(this); + + for (Port<?> existingPort : existingPorts) + { + Collection<Protocol> portProtocols = existingPort.getProtocols(); + if (portProtocols != null) + { + final ArrayList<Protocol> intersection = new ArrayList(portProtocols); + intersection.retainAll(getProtocols()); + if(!intersection.isEmpty()) + { + throw new IllegalConfigurationException("Port for protocols " + intersection + " already exists. Only one management port per protocol can be created."); + } + } + } + } + } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AmqpPortAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/AmqpPort.java index 93bbbf935f..02cdc6e740 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AmqpPortAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/AmqpPort.java @@ -17,15 +17,10 @@ * under the License. * */ -package org.apache.qpid.server.model.adapter; +package org.apache.qpid.server.model.port; import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.util.*; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; @@ -37,6 +32,7 @@ import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.logging.messages.BrokerMessages; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.KeyStore; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.Transport; import org.apache.qpid.server.model.TrustStore; @@ -49,17 +45,73 @@ import org.apache.qpid.server.transport.TransportProvider; import org.apache.qpid.server.util.ServerScopedRuntimeException; import org.apache.qpid.transport.network.security.ssl.QpidMultipleTrustManager; -public class AmqpPortAdapter extends PortAdapter<AmqpPortAdapter> +@ManagedObject( category = false, type = "AMQP") +public class AmqpPort extends PortWithAuthProvider<AmqpPort> { + public static final int DEFAULT_AMQP_SEND_BUFFER_SIZE = 262144; + public static final int DEFAULT_AMQP_RECEIVE_BUFFER_SIZE = 262144; + public static final boolean DEFAULT_AMQP_NEED_CLIENT_AUTH = false; + public static final boolean DEFAULT_AMQP_WANT_CLIENT_AUTH = false; + public static final boolean DEFAULT_AMQP_TCP_NO_DELAY = true; + public static final String DEFAULT_AMQP_BINDING = "*"; + private final Broker<?> _broker; private AcceptingTransport _transport; - public AmqpPortAdapter(UUID id, Broker<?> broker, Map<String, Object> attributes, Map<String, Object> defaultAttributes, TaskExecutor taskExecutor) + public AmqpPort(UUID id, + Broker<?> broker, + Map<String, Object> attributes, + TaskExecutor taskExecutor) { - super(id, broker, attributes, defaultAttributes, taskExecutor); + super(id, broker, attributes, defaults(attributes), taskExecutor); _broker = broker; } + private static Map<String, Object> defaults(Map<String,Object> attributes) + { + Map<String,Object> defaults = new HashMap<String, Object>(); + + defaults.put(BINDING_ADDRESS, DEFAULT_AMQP_BINDING); + defaults.put(NAME, attributes.containsKey(BINDING_ADDRESS) ? attributes.get(BINDING_ADDRESS) : DEFAULT_AMQP_BINDING + ":" + attributes.get(PORT)); + defaults.put(PROTOCOLS, getDefaultProtocols()); + defaults.put(TCP_NO_DELAY, DEFAULT_AMQP_TCP_NO_DELAY); + defaults.put(WANT_CLIENT_AUTH, DEFAULT_AMQP_WANT_CLIENT_AUTH); + defaults.put(NEED_CLIENT_AUTH, DEFAULT_AMQP_NEED_CLIENT_AUTH); + defaults.put(RECEIVE_BUFFER_SIZE, DEFAULT_AMQP_RECEIVE_BUFFER_SIZE); + defaults.put(SEND_BUFFER_SIZE, DEFAULT_AMQP_SEND_BUFFER_SIZE); + + return defaults; + } + + + private static Set<Protocol> getDefaultProtocols() + { + Set<Protocol> defaultProtocols = EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1, + Protocol.AMQP_0_10, Protocol.AMQP_1_0); + String excludedProtocols = System.getProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_EXCLUDES); + if (excludedProtocols != null) + { + String[] excludes = excludedProtocols.split(","); + for (String exclude : excludes) + { + Protocol protocol = Protocol.valueOf(exclude); + defaultProtocols.remove(protocol); + } + } + String includedProtocols = System.getProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_INCLUDES); + if (includedProtocols != null) + { + String[] includes = includedProtocols.split(","); + for (String include : includes) + { + Protocol protocol = Protocol.valueOf(include); + defaultProtocols.add(protocol); + } + } + return defaultProtocols; + } + + @Override protected void onActivate() { diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/AmqpPortFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/AmqpPortFactory.java new file mode 100644 index 0000000000..f2f721f572 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/AmqpPortFactory.java @@ -0,0 +1,50 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.model.Port; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class AmqpPortFactory extends AbstractConfiguredObjectTypeFactory<AmqpPort> +{ + public AmqpPortFactory() + { + super(AmqpPort.class); + } + + @Override + public AmqpPort createInstance(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + Broker broker = getParent(Broker.class, parents); + Map<String,Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(Port.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + + return new AmqpPort(id, broker, attributesWithoutId, broker.getTaskExecutor()); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/HttpPort.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/HttpPort.java new file mode 100644 index 0000000000..61aa0b3e82 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/HttpPort.java @@ -0,0 +1,41 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; + +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +@ManagedObject( category = false, type = "HTTP") +public class HttpPort extends PortWithAuthProvider<HttpPort> +{ + public HttpPort(final UUID id, + final Broker<?> broker, + final Map<String, Object> attributes, + final TaskExecutor taskExecutor) + { + super(id, broker, attributes, Collections.<String,Object>emptyMap(), taskExecutor); + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/HttpPortFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/HttpPortFactory.java new file mode 100644 index 0000000000..c8bd257114 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/HttpPortFactory.java @@ -0,0 +1,49 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.model.Port; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class HttpPortFactory extends AbstractConfiguredObjectTypeFactory<HttpPort> +{ + public HttpPortFactory() + { + super(HttpPort.class); + } + + @Override + public HttpPort createInstance(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + Broker broker = getParent(Broker.class, parents); + Map<String,Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(Port.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + return new HttpPort(id, broker, attributesWithoutId, broker.getTaskExecutor()); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/JmxPort.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/JmxPort.java new file mode 100644 index 0000000000..c334f7e766 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/JmxPort.java @@ -0,0 +1,44 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; + +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +@ManagedObject( category = false, type = "JMX") +public class JmxPort extends PortWithAuthProvider<JmxPort> +{ + public JmxPort(final UUID id, + final Broker<?> broker, + final Map<String, Object> attributes, + final TaskExecutor taskExecutor) + { + super(id, broker, attributes, Collections.<String,Object>emptyMap(), taskExecutor); + + validateOnlyOneInstance(broker); + + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/JmxPortFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/JmxPortFactory.java new file mode 100644 index 0000000000..c51a9815b7 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/JmxPortFactory.java @@ -0,0 +1,49 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.model.Port; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class JmxPortFactory extends AbstractConfiguredObjectTypeFactory<JmxPort> +{ + public JmxPortFactory() + { + super(JmxPort.class); + } + + @Override + public JmxPort createInstance(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + Broker broker = getParent(Broker.class, parents); + Map<String,Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(Port.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + return new JmxPort(id, broker, attributesWithoutId, broker.getTaskExecutor()); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/PortFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/PortFactory.java new file mode 100644 index 0000000000..0d97d10dee --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/PortFactory.java @@ -0,0 +1,159 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.model.ConfiguredObjectFactory; +import org.apache.qpid.server.model.Port; +import org.apache.qpid.server.model.Protocol; +import org.apache.qpid.server.model.Protocol.ProtocolType; +import org.apache.qpid.server.model.Transport; +import org.apache.qpid.server.model.port.AmqpPort; +import org.apache.qpid.server.model.port.HttpPort; +import org.apache.qpid.server.model.port.JmxPort; +import org.apache.qpid.server.model.port.RmiPort; +import org.apache.qpid.server.plugin.ConfiguredObjectTypeFactory; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.UnresolvedConfiguredObject; +import org.apache.qpid.server.util.MapValueConverter; + +public class PortFactory<X extends Port<X>> implements ConfiguredObjectTypeFactory<X> +{ + public static final int DEFAULT_AMQP_SEND_BUFFER_SIZE = 262144; + public static final int DEFAULT_AMQP_RECEIVE_BUFFER_SIZE = 262144; + public static final boolean DEFAULT_AMQP_NEED_CLIENT_AUTH = false; + public static final boolean DEFAULT_AMQP_WANT_CLIENT_AUTH = false; + public static final boolean DEFAULT_AMQP_TCP_NO_DELAY = true; + public static final String DEFAULT_AMQP_BINDING = "*"; + public static final Transport DEFAULT_TRANSPORT = Transport.TCP; + private ConfiguredObjectFactory _configuredObjectFactory; + + + public PortFactory() + { + } + + public Port createPort(UUID id, Broker broker, Map<String, Object> attributes) + { + attributes = new HashMap<String, Object>(attributes); + attributes.put(Port.ID, id); + return create(attributes,broker); + } + + private ProtocolType getProtocolType(Map<String, Object> portAttributes) + { + + Set<Protocol> protocols = MapValueConverter.getEnumSetAttribute(Port.PROTOCOLS, portAttributes, Protocol.class); + + ProtocolType protocolType = null; + + if(protocols == null || protocols.isEmpty()) + { + // defaulting to AMQP if protocol is not specified + protocolType = ProtocolType.AMQP; + } + else + { + for (Protocol protocol : protocols) + { + if (protocolType == null) + { + protocolType = protocol.getProtocolType(); + } + else if (protocolType != protocol.getProtocolType()) + { + + throw new IllegalConfigurationException("Found different protocol types '" + protocolType + + "' and '" + protocol.getProtocolType() + + "' for port configuration: " + portAttributes); + + } + } + } + + return protocolType; + } + + + @Override + public Class<? super Port> getCategoryClass() + { + return Port.class; + } + + @Override + public X create(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + return getPortFactory(attributes).create(attributes,parents); + } + + @Override + public UnresolvedConfiguredObject<X> recover(final ConfiguredObjectRecord record, + final ConfiguredObject<?>... parents) + { + return getPortFactory(record.getAttributes()).recover(record, parents); + } + + public ConfiguredObjectTypeFactory<X> getPortFactory(Map<String,Object> attributes) + { + String type; + + if(attributes.containsKey(Port.TYPE)) + { + type = (String) attributes.get(Port.TYPE); + } + else + { + type = getProtocolType(attributes).name(); + } + + synchronized (this) + { + if(_configuredObjectFactory == null) + { + _configuredObjectFactory = new ConfiguredObjectFactory(); + } + } + return _configuredObjectFactory.getConfiguredObjectTypeFactory(Port.class.getSimpleName(), type); + } + + private Broker getBroker(final ConfiguredObject<?>[] parents) + { + if(parents.length != 1 || !(parents[0] instanceof Broker)) + { + throw new IllegalConfigurationException("Port should have exactly one parent, of type Broker"); + } + return (Broker<?>) parents[0]; + } + + @Override + public String getType() + { + return null; + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/PortWithAuthProvider.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/PortWithAuthProvider.java new file mode 100644 index 0000000000..b21b418ce4 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/PortWithAuthProvider.java @@ -0,0 +1,63 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.model.AuthenticationProvider; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedAttribute; +import org.apache.qpid.server.model.Port; + +import java.util.Map; +import java.util.UUID; + +abstract public class PortWithAuthProvider<X extends PortWithAuthProvider<X>> extends AbstractPort<X> +{ + private AuthenticationProvider _authenticationProvider; + + public PortWithAuthProvider(final UUID id, + final Broker<?> broker, + final Map<String, Object> attributes, + final Map<String, Object> defaults, + final TaskExecutor taskExecutor) + { + super(id, broker, attributes, defaults, taskExecutor); + String authProvider = (String)getAttribute(Port.AUTHENTICATION_PROVIDER); + if (authProvider == null) + { + throw new IllegalConfigurationException("An authentication provider must be specified for port : " + getName()); + } + _authenticationProvider = broker.findAuthenticationProviderByName(authProvider); + + if(_authenticationProvider == null) + { + throw new IllegalConfigurationException("The authentication provider '" + authProvider + "' could not be found for port : " + getName()); + } + } + + + @ManagedAttribute + public AuthenticationProvider getAuthenticationProvider() + { + return _authenticationProvider; + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/RmiPort.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/RmiPort.java new file mode 100644 index 0000000000..1671971dff --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/RmiPort.java @@ -0,0 +1,50 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; +import org.apache.qpid.server.model.Transport; + +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +@ManagedObject( category = false, type = "RMI") +public class RmiPort extends AbstractPort<RmiPort> +{ + public RmiPort(final UUID id, + final Broker<?> broker, + final Map<String, Object> attributes, + final TaskExecutor taskExecutor) + { + super(id, broker, attributes, Collections.<String,Object>emptyMap(), taskExecutor); + + validateOnlyOneInstance(broker); + + if (getTransports().contains(Transport.SSL)) + { + throw new IllegalConfigurationException("Can't create RMI registry port which requires SSL"); + } + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/RmiPortFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/RmiPortFactory.java new file mode 100644 index 0000000000..69d2ebfc19 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/port/RmiPortFactory.java @@ -0,0 +1,49 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.model.port; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.model.Port; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class RmiPortFactory extends AbstractConfiguredObjectTypeFactory<RmiPort> +{ + public RmiPortFactory() + { + super(RmiPort.class); + } + + @Override + public RmiPort createInstance(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + Broker broker = getParent(Broker.class, parents); + Map<String,Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(Port.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + return new RmiPort(id, broker, attributesWithoutId, broker.getTaskExecutor()); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/AccessControlFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/AccessControlProviderFactory.java index 3d7c479ba2..fd1970f837 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/AccessControlFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/AccessControlProviderFactory.java @@ -26,26 +26,10 @@ import org.apache.qpid.server.logging.EventLoggerProvider; import org.apache.qpid.server.model.AccessControlProvider; import org.apache.qpid.server.security.AccessControl; -public interface AccessControlFactory extends Pluggable +public interface AccessControlProviderFactory<X extends AccessControlProvider<X>> extends ConfiguredObjectTypeFactory<X> { public static final String ATTRIBUTE_TYPE = AccessControlProvider.TYPE; - AccessControl createInstance(Map<String, Object> attributes, final EventLoggerProvider eventLogger); - - /** - * Returns the access control provider type - * @return authentication provider type - */ - String getType(); - - /** - * Get the names of attributes of the access control which can be passed into - * {@link #createInstance(java.util.Map, org.apache.qpid.server.logging.EventLogger)} to create the group manager - * - * @return the collection of attribute names - */ - Collection<String> getAttributeNames(); - /** * @return returns human readable descriptions for the attributes */ diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/AuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/AuthenticationManagerFactory.java index 6e92121036..35651b442c 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/AuthenticationManagerFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/AuthenticationManagerFactory.java @@ -21,10 +21,11 @@ package org.apache.qpid.server.plugin; import java.util.Collection; import java.util.Map; +import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.security.auth.manager.AbstractAuthenticationManager; -public interface AuthenticationManagerFactory extends Pluggable +public interface AuthenticationManagerFactory<X extends AuthenticationProvider<X>> extends ConfiguredObjectTypeFactory<X> { /** @@ -34,22 +35,7 @@ public interface AuthenticationManagerFactory extends Pluggable String getType(); /** - * Creates authentication manager from the provided attributes - * - * @param broker - * broker model object - * @param attributes - * attributes to create authentication manager - * - * @param recovering - * @return authentication manager instance - */ - AbstractAuthenticationManager createInstance(Broker broker, - Map<String, Object> attributes, - final boolean recovering); - - /** - * Get the names of attributes the authentication manager which can be passed into {@link #createInstance(org.apache.qpid.server.model.Broker, java.util.Map, boolean)} to create the + * Get the names of attributes the authentication manager * authentication manager * * @return the collection of attribute names diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfigurationStoreFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfigurationStoreFactory.java index 382c742161..eb3884d59e 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfigurationStoreFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfigurationStoreFactory.java @@ -24,6 +24,7 @@ import java.util.Map; import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.model.SystemContext; public interface ConfigurationStoreFactory extends Pluggable @@ -38,11 +39,11 @@ public interface ConfigurationStoreFactory extends Pluggable * <p> * If location does not exist, or the overwrite option is specified, then a new store is created from the initial store if it is provided * - * @param storeLocation store location + * @param systemContext application configuration * @param initialStore initial store * @param overwrite overwrite existing store with initial store * @param configProperties a map of configuration properties the store can use to resolve configuration variables * @throws IllegalConfigurationException if store cannot be opened in the given location */ - public ConfigurationEntryStore createStore(String storeLocation, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties); + public ConfigurationEntryStore createStore(SystemContext systemContext, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties); } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfiguredObjectTypeFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfiguredObjectTypeFactory.java new file mode 100644 index 0000000000..9e4c760acf --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfiguredObjectTypeFactory.java @@ -0,0 +1,36 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.plugin; + +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.UnresolvedConfiguredObject; + +import java.util.Map; + +public interface ConfiguredObjectTypeFactory<X extends ConfiguredObject<X>> extends Pluggable +{ + Class<? super X> getCategoryClass(); + + X create(Map<String, Object> attributes, ConfiguredObject<?>... parents); + + UnresolvedConfiguredObject<X> recover(ConfiguredObjectRecord record, ConfiguredObject<?>... parents); +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/PluginFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/PluginFactory.java index 7f804781a5..2ef13345b4 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/PluginFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/plugin/PluginFactory.java @@ -18,15 +18,13 @@ */ package org.apache.qpid.server.plugin; -import java.util.Map; -import java.util.UUID; - import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.Plugin; +import java.util.Map; +import java.util.UUID; + public interface PluginFactory extends Pluggable { - static final String PLUGIN_TYPE = "pluginType"; - Plugin createInstance(UUID id, Map<String, Object> attributes, Broker broker); } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java index e5f587ea94..d9195cca38 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java @@ -42,7 +42,7 @@ import org.apache.qpid.server.logging.EventLogger; import org.apache.qpid.server.message.MessageSource; import org.apache.qpid.server.model.*; import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.adapter.AbstractConfiguredObject; +import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.protocol.AMQConnectionModel; import org.apache.qpid.pool.ReferenceCountingExecutorService; import org.apache.qpid.server.configuration.BrokerProperties; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/queue/QueueConsumerImpl.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/queue/QueueConsumerImpl.java index fd9159334f..0805566d4f 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/queue/QueueConsumerImpl.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/queue/QueueConsumerImpl.java @@ -35,7 +35,7 @@ import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.LifetimePolicy; import org.apache.qpid.server.model.ManagedAttributeField; import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.adapter.AbstractConfiguredObject; +import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.protocol.MessageConverterRegistry; import org.apache.qpid.server.consumer.ConsumerTarget; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java index 764c92d53d..be24a09dfb 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java @@ -20,37 +20,23 @@ */ package org.apache.qpid.server.registry; -import java.security.PrivilegedAction; -import java.util.Collection; -import java.util.Timer; -import java.util.TimerTask; - import org.apache.log4j.Logger; -import org.apache.qpid.common.Closeable; import org.apache.qpid.common.QpidProperties; import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.startup.DefaultRecovererProvider; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.logging.*; +import org.apache.qpid.server.configuration.startup.BrokerStoreUpgrader; +import org.apache.qpid.server.logging.CompositeStartupMessageLogger; +import org.apache.qpid.server.logging.EventLogger; +import org.apache.qpid.server.logging.Log4jMessageLogger; +import org.apache.qpid.server.logging.MessageLogger; +import org.apache.qpid.server.logging.SystemOutMessageLogger; import org.apache.qpid.server.logging.messages.BrokerMessages; -import org.apache.qpid.server.logging.messages.VirtualHostMessages; import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.State; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.stats.StatisticsCounter; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; +import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.util.SystemUtils; -import javax.security.auth.Subject; - /** * An abstract application registry that provides access to configuration information and handles the @@ -62,171 +48,47 @@ public class ApplicationRegistry implements IApplicationRegistry { private static final Logger _logger = Logger.getLogger(ApplicationRegistry.class); - private final EventLogger _eventLogger; - - private final VirtualHostRegistry _virtualHostRegistry; - - private volatile MessageLogger _messageLogger; + private final SystemContext _systemContext; private Broker _broker; - private Timer _reportingTimer; - private StatisticsCounter _messagesDelivered, _dataDelivered, _messagesReceived, _dataReceived; - - private LogRecorder _logRecorder; - - private ConfigurationEntryStore _store; - private TaskExecutor _taskExecutor; + private DurableConfigurationStore _store; - public ApplicationRegistry(ConfigurationEntryStore store, EventLogger eventLogger) + public ApplicationRegistry(DurableConfigurationStore store, SystemContext systemContext) { _store = store; - _eventLogger = eventLogger; - _virtualHostRegistry = new VirtualHostRegistry(_eventLogger); - initialiseStatistics(); + _systemContext = systemContext; } public void initialise(BrokerOptions brokerOptions) throws Exception { // Create the RootLogger to be used during broker operation boolean statusUpdatesEnabled = Boolean.parseBoolean(System.getProperty(BrokerProperties.PROPERTY_STATUS_UPDATES, "true")); - _messageLogger = new Log4jMessageLogger(statusUpdatesEnabled); - _eventLogger.setMessageLogger(_messageLogger); - _logRecorder = new LogRecorder(); + MessageLogger messageLogger = new Log4jMessageLogger(statusUpdatesEnabled); + final EventLogger eventLogger = _systemContext.getEventLogger(); + eventLogger.setMessageLogger(messageLogger); //Create the composite (log4j+SystemOut MessageLogger to be used during startup - MessageLogger[] messageLoggers = {new SystemOutMessageLogger(), _messageLogger}; + MessageLogger[] messageLoggers = {new SystemOutMessageLogger(), messageLogger}; CompositeStartupMessageLogger startupMessageLogger = new CompositeStartupMessageLogger(messageLoggers); EventLogger startupLogger = new EventLogger(startupMessageLogger); - logStartupMessages(startupLogger); - _taskExecutor = new TaskExecutor(); - _taskExecutor.start(); + BrokerStoreUpgrader upgrader = new BrokerStoreUpgrader(_systemContext); + _broker = upgrader.upgrade(_store); - StoreConfigurationChangeListener storeChangeListener = new StoreConfigurationChangeListener(_store); - RecovererProvider provider = new DefaultRecovererProvider((StatisticsGatherer)this, _virtualHostRegistry, _logRecorder, - _taskExecutor, brokerOptions, storeChangeListener); - ConfiguredObjectRecoverer<? extends ConfiguredObject> brokerRecoverer = provider.getRecoverer(Broker.class.getSimpleName()); - _broker = (Broker) brokerRecoverer.create(provider, _store.getRootEntry()); _broker.setEventLogger(startupLogger); - _virtualHostRegistry.setDefaultVirtualHostName((String)_broker.getAttribute(Broker.DEFAULT_VIRTUAL_HOST)); - - initialiseStatisticsReporting(); // starting the broker _broker.setDesiredState(State.INITIALISING, State.ACTIVE); startupLogger.message(BrokerMessages.READY()); - _broker.setEventLogger(_eventLogger); + _broker.setEventLogger(eventLogger); } - private void initialiseStatisticsReporting() - { - long report = ((Number)_broker.getAttribute(Broker.STATISTICS_REPORTING_PERIOD)).intValue() * 1000; // convert to ms - final boolean reset = (Boolean)_broker.getAttribute(Broker.STATISTICS_REPORTING_RESET_ENABLED); - - /* add a timer task to report statistics if generation is enabled for broker or virtualhosts */ - if (report > 0L) - { - _reportingTimer = new Timer("Statistics-Reporting", true); - StatisticsReportingTask task = new StatisticsReportingTask(reset, _messageLogger); - _reportingTimer.scheduleAtFixedRate(task, report / 2, report); - } - } - - private class StatisticsReportingTask extends TimerTask - { - private final int DELIVERED = 0; - private final int RECEIVED = 1; - - private final boolean _reset; - private final MessageLogger _logger; - private final Subject _subject; - - public StatisticsReportingTask(boolean reset, MessageLogger logger) - { - _reset = reset; - _logger = logger; - _subject = SecurityManager.getSystemTaskSubject("Statistics"); - } - - public void run() - { - Subject.doAs(_subject, new PrivilegedAction<Object>() - { - @Override - public Object run() - { - reportStatistics(); - return null; - } - }); - } - - protected void reportStatistics() - { - try - { - _eventLogger.message(BrokerMessages.STATS_DATA(DELIVERED, _dataDelivered.getPeak() / 1024.0, _dataDelivered.getTotal())); - _eventLogger.message(BrokerMessages.STATS_MSGS(DELIVERED, _messagesDelivered.getPeak(), _messagesDelivered.getTotal())); - _eventLogger.message(BrokerMessages.STATS_DATA(RECEIVED, _dataReceived.getPeak() / 1024.0, _dataReceived.getTotal())); - _eventLogger.message(BrokerMessages.STATS_MSGS(RECEIVED, - _messagesReceived.getPeak(), - _messagesReceived.getTotal())); - Collection<VirtualHost> hosts = _virtualHostRegistry.getVirtualHosts(); - - if (hosts.size() > 1) - { - for (VirtualHost vhost : hosts) - { - String name = vhost.getName(); - StatisticsCounter dataDelivered = vhost.getDataDeliveryStatistics(); - StatisticsCounter messagesDelivered = vhost.getMessageDeliveryStatistics(); - StatisticsCounter dataReceived = vhost.getDataReceiptStatistics(); - StatisticsCounter messagesReceived = vhost.getMessageReceiptStatistics(); - EventLogger logger = vhost.getEventLogger(); - logger.message(VirtualHostMessages.STATS_DATA(name, DELIVERED, dataDelivered.getPeak() / 1024.0, dataDelivered.getTotal())); - logger.message(VirtualHostMessages.STATS_MSGS(name, DELIVERED, messagesDelivered.getPeak(), messagesDelivered.getTotal())); - logger.message(VirtualHostMessages.STATS_DATA(name, RECEIVED, dataReceived.getPeak() / 1024.0, dataReceived.getTotal())); - logger.message(VirtualHostMessages.STATS_MSGS(name, RECEIVED, messagesReceived.getPeak(), messagesReceived.getTotal())); - } - } - - if (_reset) - { - resetStatistics(); - } - } - catch(Exception e) - { - ApplicationRegistry._logger.warn("Unexpected exception occurred while reporting the statistics", e); - } - } - } - - /** - * Close non-null Closeable items and log any errors - * @param close - */ - private void close(Closeable close) - { - try - { - if (close != null) - { - close.close(); - } - } - catch (Throwable e) - { - _logger.error("Error thrown whilst closing " + close.getClass().getSimpleName(), e); - } - } - public void close() { if (_logger.isInfoEnabled()) @@ -236,93 +98,19 @@ public class ApplicationRegistry implements IApplicationRegistry try { - //Stop Statistics Reporting - if (_reportingTimer != null) - { - _reportingTimer.cancel(); - } - if (_broker != null) { _broker.setDesiredState(_broker.getState(), State.STOPPED); } - - //Shutdown virtualhosts - close(_virtualHostRegistry); - - if (_taskExecutor != null) - { - _taskExecutor.stop(); - } - - _eventLogger.message(BrokerMessages.STOPPED()); - - _logRecorder.closeLogRecorder(); - } finally { - if (_taskExecutor != null) - { - _taskExecutor.stopImmediately(); - } + _systemContext.close(); } _store = null; _broker = null; } - public void registerMessageDelivered(long messageSize) - { - _messagesDelivered.registerEvent(1L); - _dataDelivered.registerEvent(messageSize); - } - - public void registerMessageReceived(long messageSize, long timestamp) - { - _messagesReceived.registerEvent(1L, timestamp); - _dataReceived.registerEvent(messageSize, timestamp); - } - - public StatisticsCounter getMessageReceiptStatistics() - { - return _messagesReceived; - } - - public StatisticsCounter getDataReceiptStatistics() - { - return _dataReceived; - } - - public StatisticsCounter getMessageDeliveryStatistics() - { - return _messagesDelivered; - } - - public StatisticsCounter getDataDeliveryStatistics() - { - return _dataDelivered; - } - - public void resetStatistics() - { - _messagesDelivered.reset(); - _dataDelivered.reset(); - _messagesReceived.reset(); - _dataReceived.reset(); - - for (VirtualHost vhost : _virtualHostRegistry.getVirtualHosts()) - { - vhost.resetStatistics(); - } - } - - public void initialiseStatistics() - { - _messagesDelivered = new StatisticsCounter("messages-delivered"); - _dataDelivered = new StatisticsCounter("bytes-delivered"); - _messagesReceived = new StatisticsCounter("messages-received"); - _dataReceived = new StatisticsCounter("bytes-received"); - } private void logStartupMessages(EventLogger eventLogger) { diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java index 7341922bd0..fb588875a6 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java @@ -24,7 +24,7 @@ import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.stats.StatisticsGatherer; -public interface IApplicationRegistry extends StatisticsGatherer +public interface IApplicationRegistry { void initialise(BrokerOptions brokerOptions) throws Exception; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AbstractKeyStoreAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/AbstractKeyStoreAdapter.java index efc86a2594..39682ff055 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/AbstractKeyStoreAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/AbstractKeyStoreAdapter.java @@ -18,28 +18,23 @@ * under the License. * */ -package org.apache.qpid.server.model.adapter; +package org.apache.qpid.server.security; import java.security.AccessControlException; -import java.security.AccessController; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.UUID; -import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.KeyStore; import org.apache.qpid.server.model.LifetimePolicy; import org.apache.qpid.server.model.ManagedAttributeField; import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.security.SecurityManager; +import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.util.MapValueConverter; -import javax.security.auth.Subject; - public abstract class AbstractKeyStoreAdapter<X extends ConfiguredObject<X>> extends AbstractConfiguredObject<X> { public static final String DUMMY_PASSWORD_MASK = "********"; @@ -52,9 +47,10 @@ public abstract class AbstractKeyStoreAdapter<X extends ConfiguredObject<X>> ext protected AbstractKeyStoreAdapter(UUID id, Broker broker, Map<String, Object> defaults, Map<String, Object> attributes) { - super(id, defaults, attributes, broker.getTaskExecutor()); - - addParent(Broker.class, broker); + super(Collections.<Class<? extends ConfiguredObject>,ConfiguredObject<?>>singletonMap(Broker.class, broker), + defaults, + combineIdWithAttributes(id, attributes), + broker.getTaskExecutor()); MapValueConverter.assertMandatoryAttribute(KeyStore.PATH, attributes); } @@ -104,12 +100,6 @@ public abstract class AbstractKeyStoreAdapter<X extends ConfiguredObject<X>> ext } @Override - public <C extends ConfiguredObject> C createChild(Class<C> childClass, Map<String, Object> attributes, ConfiguredObject... otherParents) - { - throw new UnsupportedOperationException(); - } - - @Override public Object getAttribute(String name) { if(KeyStore.STATE.equals(name)) diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/KeyStoreAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileKeyStore.java index 12de8142da..54e94c61cf 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/KeyStoreAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileKeyStore.java @@ -18,7 +18,7 @@ * under the License. * */ -package org.apache.qpid.server.model.adapter; +package org.apache.qpid.server.security; import java.io.IOException; import java.lang.reflect.Type; @@ -26,7 +26,6 @@ import java.security.AccessControlException; import java.security.GeneralSecurityException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; -import java.security.PrivilegedAction; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Collection; @@ -37,23 +36,23 @@ import java.util.UUID; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; -import javax.security.auth.Subject; import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.IntegrityViolationException; import org.apache.qpid.server.model.KeyStore; import org.apache.qpid.server.model.ManagedAttributeField; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.State; -import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.server.security.access.Operation; import org.apache.qpid.server.util.MapValueConverter; import org.apache.qpid.server.util.ServerScopedRuntimeException; import org.apache.qpid.transport.network.security.ssl.QpidClientX509KeyManager; import org.apache.qpid.transport.network.security.ssl.SSLUtil; -public class KeyStoreAdapter extends AbstractKeyStoreAdapter<KeyStoreAdapter> implements KeyStore<KeyStoreAdapter> +@ManagedObject( category = false ) +public class FileKeyStore extends AbstractKeyStoreAdapter<FileKeyStore> implements KeyStore<FileKeyStore> { @SuppressWarnings("serial") public static final Map<String, Type> ATTRIBUTE_TYPES = Collections.unmodifiableMap(new HashMap<String, Type>(){{ @@ -66,6 +65,8 @@ public class KeyStoreAdapter extends AbstractKeyStoreAdapter<KeyStoreAdapter> im }}); @ManagedAttributeField + private String _type; + @ManagedAttributeField private String _keyStoreType; @ManagedAttributeField private String _certificateAlias; @@ -82,7 +83,7 @@ public class KeyStoreAdapter extends AbstractKeyStoreAdapter<KeyStoreAdapter> im private Broker<?> _broker; - public KeyStoreAdapter(UUID id, Broker<?> broker, Map<String, Object> attributes) + public FileKeyStore(UUID id, Broker<?> broker, Map<String, Object> attributes) { super(id, broker, DEFAULTS, attributes); _broker = broker; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileKeyStoreFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileKeyStoreFactory.java new file mode 100644 index 0000000000..3421bffeba --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileKeyStoreFactory.java @@ -0,0 +1,48 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.security; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class FileKeyStoreFactory extends AbstractConfiguredObjectTypeFactory<FileKeyStore> +{ + public FileKeyStoreFactory() + { + super(FileKeyStore.class); + } + + + @Override + public FileKeyStore createInstance(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + HashMap<String, Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(ConfiguredObject.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + return new FileKeyStore(id, getParent(Broker.class, parents), attributesWithoutId); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/TrustStoreAdapter.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileTrustStore.java index 88f40a83aa..f4f0d81bea 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/TrustStoreAdapter.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileTrustStore.java @@ -18,7 +18,7 @@ * under the License. * */ -package org.apache.qpid.server.model.adapter; +package org.apache.qpid.server.security; import java.io.IOException; import java.lang.reflect.Type; @@ -26,7 +26,6 @@ import java.security.AccessControlException; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; -import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -38,17 +37,9 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; -import javax.security.auth.Subject; import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.IntegrityViolationException; -import org.apache.qpid.server.model.ManagedAttributeField; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.security.SecurityManager; +import org.apache.qpid.server.model.*; import org.apache.qpid.server.security.access.Operation; import org.apache.qpid.server.security.auth.manager.SimpleLDAPAuthenticationManagerFactory; import org.apache.qpid.server.util.MapValueConverter; @@ -56,7 +47,8 @@ import org.apache.qpid.transport.network.security.ssl.QpidMultipleTrustManager; import org.apache.qpid.transport.network.security.ssl.QpidPeersOnlyTrustManager; import org.apache.qpid.transport.network.security.ssl.SSLUtil; -public class TrustStoreAdapter extends AbstractKeyStoreAdapter<TrustStoreAdapter> implements TrustStore<TrustStoreAdapter> +@ManagedObject( category = false ) +public class FileTrustStore extends AbstractKeyStoreAdapter<FileTrustStore> implements TrustStore<FileTrustStore> { @SuppressWarnings("serial") public static final Map<String, Type> ATTRIBUTE_TYPES = Collections.unmodifiableMap(new HashMap<String, Type>(){{ @@ -87,7 +79,7 @@ public class TrustStoreAdapter extends AbstractKeyStoreAdapter<TrustStoreAdapter private Broker<?> _broker; - public TrustStoreAdapter(UUID id, Broker<?> broker, Map<String, Object> attributes) + public FileTrustStore(UUID id, Broker<?> broker, Map<String, Object> attributes) { super(id, broker, DEFAULTS, attributes); _broker = broker; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileTrustStoreFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileTrustStoreFactory.java new file mode 100644 index 0000000000..42a0c49308 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/FileTrustStoreFactory.java @@ -0,0 +1,56 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.security; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class FileTrustStoreFactory extends AbstractConfiguredObjectTypeFactory<FileTrustStore> +{ + public FileTrustStoreFactory() + { + super(FileTrustStore.class); + } + + protected final Broker getBroker(ConfiguredObject<?>... parents) + { + if(parents.length != 1 && !(parents[0] instanceof Broker)) + { + throw new IllegalArgumentException("Should have exactly one parent of type broker"); + } + return (Broker) parents[0]; + } + + @Override + public FileTrustStore createInstance(final Map<String, Object> attributes, final ConfiguredObject<?>... parents) + { + HashMap<String, Object> attributesWithoutId = new HashMap<String, Object>(attributes); + Object idObj = attributesWithoutId.remove(ConfiguredObject.ID); + UUID id = idObj == null ? UUID.randomUUID() : idObj instanceof UUID ? (UUID) idObj : UUID.fromString(idObj.toString()); + return new FileTrustStore(id, getParent(Broker.class, parents), attributesWithoutId); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AbstractAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AbstractAuthenticationManager.java index 2274ddb189..7a5adcf92e 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AbstractAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AbstractAuthenticationManager.java @@ -22,9 +22,9 @@ package org.apache.qpid.server.security.auth.manager; import org.apache.log4j.Logger; import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.*; -import org.apache.qpid.server.model.adapter.AbstractConfiguredObject; +import org.apache.qpid.server.model.AbstractConfiguredObject; +import org.apache.qpid.server.plugin.ConfiguredObjectTypeFactory; import org.apache.qpid.server.plugin.PreferencesProviderFactory; import org.apache.qpid.server.security.SubjectCreator; import org.apache.qpid.server.security.access.Operation; @@ -34,6 +34,7 @@ import java.security.AccessControlException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; @@ -92,6 +93,11 @@ public abstract class AbstractAuthenticationManager<T extends AbstractAuthentica throw new IllegalConfigurationException("Cannot associate " + user + " with authentication provider " + this); } + public void instantiatePreferencesProvider(final PreferencesProvider preferencesProvider) + { + _preferencesProvider = preferencesProvider; + } + @Override public String setName(final String currentName, final String desiredName) throws IllegalStateException, AccessControlException @@ -137,11 +143,13 @@ public abstract class AbstractAuthenticationManager<T extends AbstractAuthentica { if(childClass == PreferencesProvider.class) { - String name = MapValueConverter.getStringAttribute(PreferencesProvider.NAME, attributes); - String type = MapValueConverter.getStringAttribute(PreferencesProvider.TYPE, attributes); - PreferencesProviderFactory factory = PreferencesProviderFactory.FACTORY_LOADER.get(type); - UUID id = UUIDGenerator.generatePreferencesProviderUUID(name, getName()); - PreferencesProvider pp = factory.createInstance(id, attributes, this); + // TODO RG - get the configured object factory from parents + ConfiguredObjectFactory factory = new ConfiguredObjectFactory(); + attributes = new HashMap<String, Object>(attributes); + attributes.put(ConfiguredObject.ID, UUID.randomUUID()); + final ConfiguredObjectTypeFactory preferencesFactory = + factory.getConfiguredObjectTypeFactory(PreferencesProvider.class, attributes); + PreferencesProvider pp = (PreferencesProvider) preferencesFactory.create(attributes, this); pp.setDesiredState(State.INITIALISING, State.ACTIVE); _preferencesProvider = pp; return (C)pp; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AbstractAuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AbstractAuthenticationManagerFactory.java new file mode 100644 index 0000000000..de0d119a60 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AbstractAuthenticationManagerFactory.java @@ -0,0 +1,34 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.security.auth.manager; + +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.plugin.AuthenticationManagerFactory; + +public abstract class AbstractAuthenticationManagerFactory<X extends AbstractAuthenticationManager<X>> + extends AbstractConfiguredObjectTypeFactory<X> implements AuthenticationManagerFactory<X> +{ + protected AbstractAuthenticationManagerFactory(final Class<X> clazz) + { + super(clazz); + } + +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManager.java index 0300f9f503..d27951bb61 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManager.java @@ -27,12 +27,13 @@ import javax.security.auth.Subject; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; -import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.UsernamePrincipal; import org.apache.qpid.server.security.auth.sasl.anonymous.AnonymousSaslServer; +@ManagedObject( category = false, type= "Anonymous" ) public class AnonymousAuthenticationManager extends AbstractAuthenticationManager<AnonymousAuthenticationManager> { private static final String ANONYMOUS = "ANONYMOUS"; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerFactory.java index af8d3149aa..ee3dcbbcc0 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/AnonymousAuthenticationManagerFactory.java @@ -19,45 +19,43 @@ */ package org.apache.qpid.server.security.auth.manager; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -public class AnonymousAuthenticationManagerFactory implements AuthenticationManagerFactory +import java.util.Collection; +import java.util.Collections; +import java.util.Map; + +public class AnonymousAuthenticationManagerFactory extends AbstractConfiguredObjectTypeFactory<AnonymousAuthenticationManager> implements AuthenticationManagerFactory<AnonymousAuthenticationManager> { public static final String PROVIDER_TYPE = "Anonymous"; - @Override - public AnonymousAuthenticationManager createInstance(Broker broker, - Map<String, Object> attributes, - final boolean recovering) + public AnonymousAuthenticationManagerFactory() { - if (attributes != null && PROVIDER_TYPE.equals(attributes.get(AuthenticationProvider.TYPE))) - { - return new AnonymousAuthenticationManager(broker, Collections.<String,Object>emptyMap(),attributes); - } - return null; + super(AnonymousAuthenticationManager.class); } @Override public Collection<String> getAttributeNames() { - return Collections.<String>singletonList(AuthenticationProvider.TYPE); + return Collections.singletonList(AuthenticationProvider.TYPE); } + @Override - public String getType() + public Map<String, String> getAttributeDescriptions() { - return PROVIDER_TYPE; + return Collections.emptyMap(); } - @Override - public Map<String, String> getAttributeDescriptions() + public AnonymousAuthenticationManager createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) { - return null; + return new AnonymousAuthenticationManager(getParent(Broker.class,parents), Collections.<String,Object>emptyMap(),attributes); } + + } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordDatabaseAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordDatabaseAuthenticationManager.java index 9866460162..fadd74f837 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordDatabaseAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordDatabaseAuthenticationManager.java @@ -22,6 +22,7 @@ package org.apache.qpid.server.security.auth.manager; import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase; import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; import org.apache.qpid.server.security.auth.database.PrincipalDatabase; @@ -31,6 +32,7 @@ import java.util.Collection; import java.util.Collections; import java.util.Map; +@ManagedObject( category = false, type = "Base64MD5PasswordFile" ) public class Base64MD5PasswordDatabaseAuthenticationManager extends PrincipalDatabaseAuthenticationManager<Base64MD5PasswordDatabaseAuthenticationManager> { diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactory.java index 79a2e584b3..4803ade567 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactory.java @@ -20,17 +20,21 @@ */ package org.apache.qpid.server.security.auth.manager; +import org.apache.qpid.server.model.AuthenticationProvider; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.ResolvedObject; +import org.apache.qpid.server.store.UnresolvedConfiguredObject; +import org.apache.qpid.server.util.ResourceBundleLoader; + import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.Map; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.util.ResourceBundleLoader; - -public class Base64MD5PasswordFileAuthenticationManagerFactory implements AuthenticationManagerFactory +public class Base64MD5PasswordFileAuthenticationManagerFactory extends AbstractAuthenticationManagerFactory<Base64MD5PasswordDatabaseAuthenticationManager> { public static final String PROVIDER_TYPE = "Base64MD5PasswordFile"; public static final String RESOURCE_BUNDLE = "org.apache.qpid.server.security.auth.manager.PasswordFileAuthenticationProviderAttributeDescriptions"; @@ -41,10 +45,9 @@ public class Base64MD5PasswordFileAuthenticationManagerFactory implements Authen AuthenticationProvider.TYPE, ATTRIBUTE_PATH)); - @Override - public String getType() + public Base64MD5PasswordFileAuthenticationManagerFactory() { - return PROVIDER_TYPE; + super(Base64MD5PasswordDatabaseAuthenticationManager.class); } @Override @@ -53,24 +56,31 @@ public class Base64MD5PasswordFileAuthenticationManagerFactory implements Authen return ResourceBundleLoader.getResources(RESOURCE_BUNDLE); } - @Override - public AbstractAuthenticationManager createInstance(final Broker broker, - final Map<String, Object> attributes, - final boolean recovering) + public Collection<String> getAttributeNames() { - if (attributes == null || !getType().equals(attributes.get(AuthenticationProvider.TYPE))) - { - return null; - } - - return new Base64MD5PasswordDatabaseAuthenticationManager(broker, Collections.<String,Object>emptyMap(),attributes,recovering); + return ATTRIBUTES; } @Override - public Collection<String> getAttributeNames() + public Base64MD5PasswordDatabaseAuthenticationManager createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) { - return ATTRIBUTES; + return new Base64MD5PasswordDatabaseAuthenticationManager(getParent(Broker.class, parents), Collections.<String,Object>emptyMap(),attributes,false); } + @Override + public UnresolvedConfiguredObject<Base64MD5PasswordDatabaseAuthenticationManager> recover(final ConfiguredObjectRecord record, + final ConfiguredObject<?>... parents) + { + + Map<String, Object> attributes = new HashMap<String, Object>(record.getAttributes()); + attributes.put(ConfiguredObject.ID, record.getId()); + final Base64MD5PasswordDatabaseAuthenticationManager authenticationManager = + new Base64MD5PasswordDatabaseAuthenticationManager(getParent(Broker.class, parents), + Collections.<String, Object>emptyMap(), + attributes, + true); + return ResolvedObject.newInstance(authenticationManager); + } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManager.java index 5ff9a3ddac..48ac5885a7 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManager.java @@ -28,10 +28,12 @@ import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ManagedAttribute; import org.apache.qpid.server.model.ManagedAttributeField; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.UsernamePrincipal; import org.apache.qpid.server.security.auth.sasl.external.ExternalSaslServer; +@ManagedObject( category = false, type = "External" ) public class ExternalAuthenticationManager extends AbstractAuthenticationManager<ExternalAuthenticationManager> { private static final String EXTERNAL = "EXTERNAL"; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerFactory.java index b62012b203..30097e5987 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ExternalAuthenticationManagerFactory.java @@ -19,17 +19,17 @@ */ package org.apache.qpid.server.security.auth.manager; +import org.apache.qpid.server.model.AuthenticationProvider; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.util.ResourceBundleLoader; + import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.util.ResourceBundleLoader; - -public class ExternalAuthenticationManagerFactory implements AuthenticationManagerFactory +public class ExternalAuthenticationManagerFactory extends AbstractAuthenticationManagerFactory<ExternalAuthenticationManager> { public static final String RESOURCE_BUNDLE = "org.apache.qpid.server.security.auth.manager.ExternalAuthenticationProviderAttributeDescriptions"; public static final String PROVIDER_TYPE = "External"; @@ -39,16 +39,9 @@ public class ExternalAuthenticationManagerFactory implements AuthenticationManag AuthenticationProvider.TYPE, ATTRIBUTE_USE_FULL_DN)); - @Override - public ExternalAuthenticationManager createInstance(Broker broker, - Map<String, Object> attributes, - final boolean recovering) + public ExternalAuthenticationManagerFactory() { - if (attributes != null && PROVIDER_TYPE.equals(attributes.get(AuthenticationProvider.TYPE))) - { - return new ExternalAuthenticationManager(broker, Collections.<String,Object>emptyMap(),attributes); - } - return null; + super(ExternalAuthenticationManager.class); } @Override @@ -58,15 +51,16 @@ public class ExternalAuthenticationManagerFactory implements AuthenticationManag } @Override - public String getType() + public Map<String, String> getAttributeDescriptions() { - return PROVIDER_TYPE; + return ResourceBundleLoader.getResources(RESOURCE_BUNDLE); } @Override - public Map<String, String> getAttributeDescriptions() + public ExternalAuthenticationManager createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) { - return ResourceBundleLoader.getResources(RESOURCE_BUNDLE); + return new ExternalAuthenticationManager(getParent(Broker.class, parents), Collections.<String,Object>emptyMap(),attributes); } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/KerberosAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/KerberosAuthenticationManager.java index 720b778cd2..750b15e17a 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/KerberosAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/KerberosAuthenticationManager.java @@ -32,9 +32,11 @@ import javax.security.sasl.SaslServer; import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.UsernamePrincipal; +@ManagedObject( category = false, type = "Kerberos" ) public class KerberosAuthenticationManager extends AbstractAuthenticationManager<KerberosAuthenticationManager> { private static final String GSSAPI_MECHANISM = "GSSAPI"; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/KerberosAuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/KerberosAuthenticationManagerFactory.java index 3481afb8e2..4a8ffda997 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/KerberosAuthenticationManagerFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/KerberosAuthenticationManagerFactory.java @@ -19,28 +19,21 @@ */ package org.apache.qpid.server.security.auth.manager; +import org.apache.qpid.server.model.AuthenticationProvider; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; + import java.util.Collection; import java.util.Collections; import java.util.Map; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; - -public class KerberosAuthenticationManagerFactory implements AuthenticationManagerFactory +public class KerberosAuthenticationManagerFactory extends AbstractAuthenticationManagerFactory<KerberosAuthenticationManager> { public static final String PROVIDER_TYPE = "Kerberos"; - @Override - public KerberosAuthenticationManager createInstance(Broker broker, - Map<String, Object> attributes, - final boolean recovering) + public KerberosAuthenticationManagerFactory() { - if (attributes != null && PROVIDER_TYPE.equals(attributes.get(AuthenticationProvider.TYPE))) - { - return new KerberosAuthenticationManager(broker, Collections.<String,Object>emptyMap(), attributes); - } - return null; + super(KerberosAuthenticationManager.class); } @Override @@ -50,14 +43,16 @@ public class KerberosAuthenticationManagerFactory implements AuthenticationManag } @Override - public String getType() + public Map<String, String> getAttributeDescriptions() { - return PROVIDER_TYPE; + return Collections.emptyMap(); } @Override - public Map<String, String> getAttributeDescriptions() + public KerberosAuthenticationManager createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) { - return null; + return new KerberosAuthenticationManager(getParent(Broker.class, parents), Collections.<String,Object>emptyMap(), attributes); } + } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PlainPasswordDatabaseAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PlainPasswordDatabaseAuthenticationManager.java index 647678a6ea..b53b66464a 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PlainPasswordDatabaseAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PlainPasswordDatabaseAuthenticationManager.java @@ -21,11 +21,13 @@ package org.apache.qpid.server.security.auth.manager; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; import org.apache.qpid.server.security.auth.database.PrincipalDatabase; import java.util.Map; +@ManagedObject( category = false, type = "PlainPasswordFile" ) public class PlainPasswordDatabaseAuthenticationManager extends PrincipalDatabaseAuthenticationManager<PlainPasswordDatabaseAuthenticationManager> { protected PlainPasswordDatabaseAuthenticationManager(final Broker broker, diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactory.java index 3ed66d07c6..305bf6dcac 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactory.java @@ -20,17 +20,21 @@ */ package org.apache.qpid.server.security.auth.manager; +import org.apache.qpid.server.model.AuthenticationProvider; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.ResolvedObject; +import org.apache.qpid.server.store.UnresolvedConfiguredObject; +import org.apache.qpid.server.util.ResourceBundleLoader; + import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; import java.util.Map; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.util.ResourceBundleLoader; - -public class PlainPasswordFileAuthenticationManagerFactory implements AuthenticationManagerFactory +public class PlainPasswordFileAuthenticationManagerFactory extends AbstractAuthenticationManagerFactory<PlainPasswordDatabaseAuthenticationManager> { public static final String RESOURCE_BUNDLE = "org.apache.qpid.server.security.auth.manager.PasswordFileAuthenticationProviderAttributeDescriptions"; public static final String ATTRIBUTE_PATH = "path"; @@ -42,23 +46,9 @@ public class PlainPasswordFileAuthenticationManagerFactory implements Authentica public static final String PROVIDER_TYPE = "PlainPasswordFile"; - @Override - public String getType() - { - return PROVIDER_TYPE; - } - - @Override - public AbstractAuthenticationManager createInstance(final Broker broker, - final Map<String, Object> attributes, - final boolean recovering) + public PlainPasswordFileAuthenticationManagerFactory() { - if (attributes == null || !getType().equals(attributes.get(AuthenticationProvider.TYPE))) - { - return null; - } - - return new PlainPasswordDatabaseAuthenticationManager(broker, Collections.<String,Object>emptyMap(),attributes,recovering); + super(PlainPasswordDatabaseAuthenticationManager.class); } @Override @@ -73,4 +63,27 @@ public class PlainPasswordFileAuthenticationManagerFactory implements Authentica { return ATTRIBUTES; } + + @Override + public PlainPasswordDatabaseAuthenticationManager createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) + { + return new PlainPasswordDatabaseAuthenticationManager(getParent(Broker.class, parents), Collections.<String,Object>emptyMap(),attributes,false); + } + + @Override + public UnresolvedConfiguredObject<PlainPasswordDatabaseAuthenticationManager> recover(final ConfiguredObjectRecord record, + final ConfiguredObject<?>... parents) + { + + Map<String, Object> attributes = new HashMap<String, Object>(record.getAttributes()); + attributes.put(ConfiguredObject.ID, record.getId()); + PlainPasswordDatabaseAuthenticationManager authManager = new PlainPasswordDatabaseAuthenticationManager( + getParent(Broker.class, parents), + Collections.<String, Object>emptyMap(), + attributes, + true); + + return ResolvedObject.newInstance(authManager); + } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java index 7b9f850536..5b6e8f51c0 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java @@ -39,8 +39,7 @@ import javax.security.sasl.SaslServer; import org.apache.log4j.Logger; import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.model.*; -import org.apache.qpid.server.model.adapter.AbstractConfiguredObject; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; +import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.security.access.Operation; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.UsernamePrincipal; @@ -420,14 +419,6 @@ public abstract class PrincipalDatabaseAuthenticationManager<T extends Principal } @Override - public <C extends ConfiguredObject> C createChild(Class<C> childClass, - Map<String, Object> attributes, - ConfiguredObject... otherParents) - { - return null; - } - - @Override public Collection<String> getAttributeNames() { return getAttributeNames(User.class); diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManager.java index 097d0bfb9d..02fe989e56 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManager.java @@ -20,18 +20,18 @@ */ package org.apache.qpid.server.security.auth.manager; -import org.apache.qpid.server.configuration.ConfigurationEntry; import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; import org.apache.qpid.server.configuration.RecovererProvider; import org.apache.qpid.server.configuration.updater.ChangeAttributesTask; import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.*; -import org.apache.qpid.server.model.adapter.AbstractConfiguredObject; +import org.apache.qpid.server.model.AbstractConfiguredObject; import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.server.security.access.Operation; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.UsernamePrincipal; import org.apache.qpid.server.security.auth.sasl.scram.ScramSHA1SaslServer; +import org.apache.qpid.server.store.ConfiguredObjectRecord; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; @@ -40,7 +40,6 @@ import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.xml.bind.DatatypeConverter; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.AccessControlException; import java.security.InvalidKeyException; @@ -56,6 +55,7 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +@ManagedObject( category = false, type = "SCRAM-SHA1" ) public class ScramSHA1AuthenticationManager extends AbstractAuthenticationManager<ScramSHA1AuthenticationManager> implements PasswordCredentialManagingAuthenticationProvider<ScramSHA1AuthenticationManager>, @@ -71,8 +71,7 @@ public class ScramSHA1AuthenticationManager protected ScramSHA1AuthenticationManager(final Broker broker, final Map<String, Object> defaults, - final Map<String, Object> attributes, - final boolean recovering) + final Map<String, Object> attributes) { super(broker, defaults, attributes); } @@ -265,7 +264,7 @@ public class ScramSHA1AuthenticationManager userAttrs.put(User.NAME, username); userAttrs.put(User.PASSWORD, createStoredPassword(password)); userAttrs.put(User.TYPE, SCRAM_USER_TYPE); - ScramAuthUser user = new ScramAuthUser(userAttrs); + ScramAuthUser user = new ScramAuthUser(userAttrs, this); _users.put(username, user); return true; @@ -425,30 +424,25 @@ public class ScramSHA1AuthenticationManager @Override public ConfiguredObjectRecoverer<? extends ConfiguredObject> getRecoverer(final String type) { - if("User".equals(type)) - { - return new UserRecoverer(); - } - else - { - return null; - } + return null; } - private class ScramAuthUser extends AbstractConfiguredObject<ScramAuthUser> implements User<ScramAuthUser> + @ManagedObject( category = false, type = "scram") + static class ScramAuthUser extends AbstractConfiguredObject<ScramAuthUser> implements User<ScramAuthUser> { - - protected ScramAuthUser(final Map<String, Object> attributes) + private ScramSHA1AuthenticationManager _authenticationManager; + protected ScramAuthUser(final Map<String, Object> attributes, ScramSHA1AuthenticationManager parent) { - super(parentsMap(ScramSHA1AuthenticationManager.this), + super(parentsMap(parent), Collections.<String,Object>emptyMap(), - attributes, ScramSHA1AuthenticationManager.this.getTaskExecutor()); - + attributes, parent.getTaskExecutor()); + _authenticationManager = parent; if(!ASCII.newEncoder().canEncode(getName())) { throw new IllegalArgumentException("Scram SHA1 user names are restricted to characters in the ASCII charset"); } + } @Override @@ -456,9 +450,9 @@ public class ScramSHA1AuthenticationManager { if(desiredState == State.DELETED) { - getSecurityManager().authoriseUserOperation(Operation.DELETE, getName()); - _users.remove(getName()); - ScramSHA1AuthenticationManager.this.childRemoved(this); + _authenticationManager.getSecurityManager().authoriseUserOperation(Operation.DELETE, getName()); + _authenticationManager._users.remove(getName()); + _authenticationManager.childRemoved(this); return true; } else @@ -479,7 +473,7 @@ public class ScramSHA1AuthenticationManager { try { - modifiedAttributes.put(User.PASSWORD, createStoredPassword(newPassword)); + modifiedAttributes.put(User.PASSWORD, _authenticationManager.createStoredPassword(newPassword)); } catch (SaslException e) { @@ -514,11 +508,12 @@ public class ScramSHA1AuthenticationManager @Override public void setPassword(final String password) { - getSecurityManager().authoriseUserOperation(Operation.UPDATE, getName()); + _authenticationManager.getSecurityManager().authoriseUserOperation(Operation.UPDATE, getName()); try { - changeAttribute(User.PASSWORD, getAttribute(User.PASSWORD), createStoredPassword(password)); + changeAttribute(User.PASSWORD, getAttribute(User.PASSWORD), _authenticationManager.createStoredPassword( + password)); } catch (SaslException e) { @@ -579,7 +574,7 @@ public class ScramSHA1AuthenticationManager @Override public Map<String, Object> getPreferences() { - PreferencesProvider preferencesProvider = getPreferencesProvider(); + PreferencesProvider preferencesProvider = _authenticationManager.getPreferencesProvider(); if (preferencesProvider == null) { return null; @@ -601,7 +596,7 @@ public class ScramSHA1AuthenticationManager @Override public Map<String, Object> setPreferences(Map<String, Object> preferences) { - PreferencesProvider preferencesProvider = getPreferencesProvider(); + PreferencesProvider preferencesProvider = _authenticationManager.getPreferencesProvider(); if (preferencesProvider == null) { return null; @@ -612,7 +607,7 @@ public class ScramSHA1AuthenticationManager @Override public boolean deletePreferences() { - PreferencesProvider preferencesProvider = getPreferencesProvider(); + PreferencesProvider preferencesProvider = _authenticationManager.getPreferencesProvider(); if (preferencesProvider == null) { return false; @@ -680,17 +675,13 @@ public class ScramSHA1AuthenticationManager } } - private class UserRecoverer implements ConfiguredObjectRecoverer<ScramAuthUser> + public void instantiateUser(User<?> user) { - @Override - public ScramAuthUser create(final RecovererProvider recovererProvider, - final ConfigurationEntry entry, - final ConfiguredObject... parents) + if(!(user instanceof ScramAuthUser)) { - - Map<String,Object> attributes = new HashMap<String, Object>(entry.getAttributes()); - attributes.put(User.ID,entry.getId()); - return new ScramAuthUser(attributes); + throw new IllegalArgumentException("Only users of type " + ScramAuthUser.class.getSimpleName() + " can be add to a " + getClass().getSimpleName()); } + _users.put(user.getName(), (ScramAuthUser) user); + } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManagerFactory.java index dd6f77e474..ab3846cc01 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManagerFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManagerFactory.java @@ -21,15 +21,14 @@ package org.apache.qpid.server.security.auth.manager; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.util.ResourceBundleLoader; +import org.apache.qpid.server.model.ConfiguredObject; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; -public class ScramSHA1AuthenticationManagerFactory implements AuthenticationManagerFactory +public class ScramSHA1AuthenticationManagerFactory extends AbstractAuthenticationManagerFactory<ScramSHA1AuthenticationManager> { public static final String PROVIDER_TYPE = "SCRAM-SHA1"; @@ -40,18 +39,9 @@ public class ScramSHA1AuthenticationManagerFactory implements AuthenticationMana AuthenticationProvider.TYPE )); - @Override - public ScramSHA1AuthenticationManager createInstance(Broker broker, - Map<String, Object> attributes, - final boolean recovering) + public ScramSHA1AuthenticationManagerFactory() { - if (attributes == null || !PROVIDER_TYPE.equals(attributes.get(AuthenticationProvider.TYPE))) - { - return null; - } - - - return new ScramSHA1AuthenticationManager(broker, Collections.<String,Object>emptyMap(),attributes, false); + super(ScramSHA1AuthenticationManager.class); } @Override @@ -61,14 +51,16 @@ public class ScramSHA1AuthenticationManagerFactory implements AuthenticationMana } @Override - public String getType() + public Map<String, String> getAttributeDescriptions() { - return PROVIDER_TYPE; + return Collections.emptyMap(); } @Override - public Map<String, String> getAttributeDescriptions() + public ScramSHA1AuthenticationManager createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) { - return Collections.emptyMap(); + return new ScramSHA1AuthenticationManager(getParent(Broker.class, parents), Collections.<String,Object>emptyMap(),attributes); } + } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/TrustStoreRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1UserRecoverer.java index 7e9428a4d6..b5e369269c 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/configuration/startup/TrustStoreRecoverer.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/ScramSHA1UserRecoverer.java @@ -18,23 +18,25 @@ * under the License. * */ -package org.apache.qpid.server.configuration.startup; +package org.apache.qpid.server.security.auth.manager; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.AbstractConfiguredObjectTypeFactory; +import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.adapter.TrustStoreAdapter; -public class TrustStoreRecoverer implements ConfiguredObjectRecoverer<TrustStore> +import java.util.Map; + +public class ScramSHA1UserRecoverer extends AbstractConfiguredObjectTypeFactory<ScramSHA1AuthenticationManager.ScramAuthUser> { - @Override - public TrustStore create(RecovererProvider recovererProvider, ConfigurationEntry entry, ConfiguredObject... parents) + public ScramSHA1UserRecoverer() { - Broker broker = RecovererHelper.verifyOnlyBrokerIsParent(parents); - return new TrustStoreAdapter(entry.getId(), broker, entry.getAttributes()); + super(ScramSHA1AuthenticationManager.ScramAuthUser.class); } + @Override + public ScramSHA1AuthenticationManager.ScramAuthUser createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) + { + return new ScramSHA1AuthenticationManager.ScramAuthUser(attributes, (ScramSHA1AuthenticationManager)getParent(AuthenticationProvider.class, parents)); + } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleAuthenticationManager.java index 68cd3f5cb4..b10adffbf7 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleAuthenticationManager.java @@ -38,11 +38,13 @@ import javax.security.sasl.SaslServer; import org.apache.log4j.Logger; import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.UsernamePrincipal; import org.apache.qpid.server.security.auth.sasl.plain.PlainPasswordCallback; import org.apache.qpid.server.security.auth.sasl.plain.PlainSaslServer; +@ManagedObject( category = false, type = "Simple" ) public class SimpleAuthenticationManager extends AbstractAuthenticationManager<SimpleAuthenticationManager> { private static final Logger _logger = Logger.getLogger(SimpleAuthenticationManager.class); diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java index 6e80e13dfd..8162c664b9 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManager.java @@ -50,6 +50,7 @@ import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ManagedAttribute; import org.apache.qpid.server.model.ManagedAttributeField; +import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.model.TrustStore; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; @@ -62,6 +63,7 @@ import org.apache.qpid.server.util.ServerScopedRuntimeException; import org.apache.qpid.server.util.StringUtil; import org.apache.qpid.ssl.SSLContextFactory; +@ManagedObject( category = false, type = "SimpleLDAP" ) public class SimpleLDAPAuthenticationManager extends AbstractAuthenticationManager<SimpleLDAPAuthenticationManager> { private static final Logger _logger = Logger.getLogger(SimpleLDAPAuthenticationManager.class); diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactory.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactory.java index 4c32cdc2c8..34b630e2bf 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactory.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactory.java @@ -19,22 +19,19 @@ */ package org.apache.qpid.server.security.auth.manager; +import org.apache.qpid.server.model.AuthenticationProvider; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.util.ResourceBundleLoader; + import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.util.ResourceBundleLoader; - -public class SimpleLDAPAuthenticationManagerFactory implements AuthenticationManagerFactory +public class SimpleLDAPAuthenticationManagerFactory extends AbstractAuthenticationManagerFactory<SimpleLDAPAuthenticationManager> { public static final String RESOURCE_BUNDLE = "org.apache.qpid.server.security.auth.manager.SimpleLDAPAuthenticationProviderAttributeDescriptions"; - private static final String DEFAULT_LDAP_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory"; public static final String PROVIDER_TYPE = "SimpleLDAP"; @@ -56,18 +53,9 @@ public class SimpleLDAPAuthenticationManagerFactory implements AuthenticationMan ATTRIBUTE_LDAP_CONTEXT_FACTORY )); - @Override - public SimpleLDAPAuthenticationManager createInstance(Broker broker, - Map<String, Object> attributes, - final boolean recovering) + public SimpleLDAPAuthenticationManagerFactory() { - if (attributes == null || !PROVIDER_TYPE.equals(attributes.get(AuthenticationProvider.TYPE))) - { - return null; - } - - - return new SimpleLDAPAuthenticationManager(broker, Collections.<String,Object>emptyMap(),attributes); + super(SimpleLDAPAuthenticationManager.class); } @Override @@ -77,14 +65,16 @@ public class SimpleLDAPAuthenticationManagerFactory implements AuthenticationMan } @Override - public String getType() + public Map<String, String> getAttributeDescriptions() { - return PROVIDER_TYPE; + return ResourceBundleLoader.getResources(RESOURCE_BUNDLE); } @Override - public Map<String, String> getAttributeDescriptions() + public SimpleLDAPAuthenticationManager createInstance(final Map<String, Object> attributes, + final ConfiguredObject<?>... parents) { - return ResourceBundleLoader.getResources(RESOURCE_BUNDLE); + return new SimpleLDAPAuthenticationManager(getParent(Broker.class, parents), Collections.<String,Object>emptyMap(),attributes); } + } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/stats/StatisticsGatherer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/stats/StatisticsGatherer.java index 306191d528..6956e8e56c 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/stats/StatisticsGatherer.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/stats/StatisticsGatherer.java @@ -103,4 +103,9 @@ public interface StatisticsGatherer * Reset the counters for this, and any child {@link StatisticsGatherer}s. */ void resetStatistics(); + + interface Source + { + StatisticsGatherer getStatisticsGatherer(); + } } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractDurableConfiguredObjectRecoverer.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractDurableConfiguredObjectRecoverer.java index da84580a94..154b548cab 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractDurableConfiguredObjectRecoverer.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractDurableConfiguredObjectRecoverer.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.server.store; -import java.util.Map; import java.util.UUID; public abstract class AbstractDurableConfiguredObjectRecoverer<T> implements DurableConfiguredObjectRecoverer @@ -41,21 +40,26 @@ public abstract class AbstractDurableConfiguredObjectRecoverer<T> implements Dur else { durableConfigurationRecoverer.addResolutionListener(dependency.getType(), dependency.getId(), - new DependencyListener() - { + new DependencyListener() + { - @Override - public void dependencyResolved(final String depType, - final UUID depId, - final Object o) - { - dependency.resolve(o); - if(obj.getUnresolvedDependencies().length == 0) - { - durableConfigurationRecoverer.resolve(getType(), record.getId(), obj.resolve()); - } - } - }); + @Override + public void dependencyResolved(final String depType, + final UUID depId, + final Object o) + { + dependency.resolve(o); + if (obj.getUnresolvedDependencies().length + == 0) + { + durableConfigurationRecoverer.resolve( + getType(), + record.getId(), + obj.resolve()); + } + } + } + ); } } if(obj.getUnresolvedDependencies().length == 0) diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectDependency.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectDependency.java new file mode 100644 index 0000000000..a8146330ed --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectDependency.java @@ -0,0 +1,29 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.store; + +import org.apache.qpid.server.model.ConfiguredObject; + +public interface ConfiguredObjectDependency<C extends ConfiguredObject<C>> +{ + Class<C> getCategoryClass(); + void resolve(C object); +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectIdDependency.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectIdDependency.java new file mode 100644 index 0000000000..efe65c8a5f --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectIdDependency.java @@ -0,0 +1,30 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.store; + +import org.apache.qpid.server.model.ConfiguredObject; + +import java.util.UUID; + +public interface ConfiguredObjectIdDependency<C extends ConfiguredObject<C>> extends ConfiguredObjectDependency<C> +{ + UUID getId(); +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectNameDependency.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectNameDependency.java new file mode 100644 index 0000000000..3758a1bc16 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectNameDependency.java @@ -0,0 +1,28 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.store; + +import org.apache.qpid.server.model.ConfiguredObject; + +public interface ConfiguredObjectNameDependency<C extends ConfiguredObject<C>> extends ConfiguredObjectDependency<C> +{ + String getName(); +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java index f37edbccdb..7d93f18906 100755 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java @@ -41,7 +41,8 @@ public interface DurableConfigurationStore /** * Called after instantiation in order to configure the message store. A particular implementation can define * whatever parameters it wants. - * @param parent host name + * + * @param parent * @param storeSettings store settings */ void openConfigurationStore(ConfiguredObject<?> parent, Map<String, Object> storeSettings) throws StoreException; diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/JsonFileConfigStore.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/JsonFileConfigStore.java index aefee7fab0..a5ace16cfa 100644 --- a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/JsonFileConfigStore.java +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/JsonFileConfigStore.java @@ -93,7 +93,6 @@ public class JsonFileConfigStore implements DurableConfigurationStore public void openConfigurationStore(ConfiguredObject<?> parent, Map<String, Object> storeSettings) { _name = parent.getName(); - setup(storeSettings); load(); } diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ResolvedObject.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ResolvedObject.java new file mode 100644 index 0000000000..ee36663a7f --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/ResolvedObject.java @@ -0,0 +1,71 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.store; + +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.model.Model; + +import java.util.Collection; +import java.util.Collections; + +public class ResolvedObject<C extends ConfiguredObject<C>> implements UnresolvedConfiguredObject<C> +{ + + private final C _resolved; + + + private ResolvedObject(final C resolved) + { + _resolved = resolved; + } + + @Override + public ConfiguredObject<?>[] getParents() + { + final Collection<Class<? extends ConfiguredObject>> parentTypes = + Model.getInstance().getParentTypes(_resolved.getCategoryClass()); + ConfiguredObject<?>[] parents = new ConfiguredObject[parentTypes.size()]; + int i = 0; + for(Class<? extends ConfiguredObject> parentType : parentTypes) + { + parents[i] = _resolved.getParent(parentType); + i++; + } + return parents; + } + + @Override + public Collection<ConfiguredObjectDependency<?>> getUnresolvedDependencies() + { + return Collections.emptySet(); + } + + @Override + public C resolve() + { + return _resolved; + } + + public static <T extends ConfiguredObject<T>> ResolvedObject<T> newInstance(T object) + { + return new ResolvedObject<T>(object); + } +} diff --git a/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/UnresolvedConfiguredObject.java b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/UnresolvedConfiguredObject.java new file mode 100644 index 0000000000..f284c20ec3 --- /dev/null +++ b/qpid/java/broker-core/src/main/java/org/apache/qpid/server/store/UnresolvedConfiguredObject.java @@ -0,0 +1,36 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.store; + +import org.apache.qpid.server.model.ConfiguredObject; + +import java.util.Collection; +import java.util.Collections; + +public interface UnresolvedConfiguredObject<X extends ConfiguredObject<X>> +{ + ConfiguredObject<?>[] getParents(); + + Collection<ConfiguredObjectDependency<?>> getUnresolvedDependencies(); + + X resolve(); + +} diff --git a/qpid/java/broker-core/src/main/resources/META-INF/services/org.apache.qpid.server.plugin.ConfiguredObjectTypeFactory b/qpid/java/broker-core/src/main/resources/META-INF/services/org.apache.qpid.server.plugin.ConfiguredObjectTypeFactory new file mode 100644 index 0000000000..c66ff45897 --- /dev/null +++ b/qpid/java/broker-core/src/main/resources/META-INF/services/org.apache.qpid.server.plugin.ConfiguredObjectTypeFactory @@ -0,0 +1,40 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +org.apache.qpid.server.security.FileKeyStoreFactory +org.apache.qpid.server.security.FileTrustStoreFactory +org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManagerFactory +org.apache.qpid.server.security.auth.manager.Base64MD5PasswordFileAuthenticationManagerFactory +org.apache.qpid.server.security.auth.manager.ExternalAuthenticationManagerFactory +org.apache.qpid.server.security.auth.manager.KerberosAuthenticationManagerFactory +org.apache.qpid.server.security.auth.manager.PlainPasswordFileAuthenticationManagerFactory +org.apache.qpid.server.security.auth.manager.SimpleLDAPAuthenticationManagerFactory +org.apache.qpid.server.security.auth.manager.ScramSHA1AuthenticationManagerFactory +org.apache.qpid.server.security.auth.manager.ScramSHA1UserRecoverer +org.apache.qpid.server.model.port.AmqpPortFactory +org.apache.qpid.server.model.port.HttpPortFactory +org.apache.qpid.server.model.port.JmxPortFactory +org.apache.qpid.server.model.port.RmiPortFactory +org.apache.qpid.server.model.port.PortFactory +org.apache.qpid.server.model.adapter.BrokerAdapterFactory +org.apache.qpid.server.model.adapter.StandardVirtualHostAdapterFactory +org.apache.qpid.server.model.adapter.FileBasedGroupProviderFactory +org.apache.qpid.server.model.adapter.FileSystemPreferencesProviderFactory + + + diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java index a7772ffd10..280ee185ae 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java @@ -20,28 +20,37 @@ */ package org.apache.qpid.server.configuration; -import java.io.File; -import java.io.StringWriter; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.configuration.store.JsonConfigurationEntryStore; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.logging.EventLogger; +import org.apache.qpid.server.logging.LogRecorder; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObjectFactory; import org.apache.qpid.server.model.Model; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.test.utils.TestFileUtils; import org.apache.qpid.util.FileUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; +import java.io.File; +import java.io.StringWriter; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class BrokerConfigurationStoreCreatorTest extends QpidTestCase { private File _userStoreLocation; private BrokerConfigurationStoreCreator _storeCreator; + private SystemContext _systemContext; public void setUp() throws Exception { @@ -56,6 +65,13 @@ public class BrokerConfigurationStoreCreatorTest extends QpidTestCase } _storeCreator = new BrokerConfigurationStoreCreator(); _userStoreLocation = new File(TMP_FOLDER, "_store_" + System.currentTimeMillis() + "_" + getTestName()); + final BrokerOptions brokerOptions = mock(BrokerOptions.class); + when(brokerOptions.getConfigurationStoreLocation()).thenReturn(_userStoreLocation.getAbsolutePath()); + _systemContext = new SystemContext(new TaskExecutor(), + new ConfiguredObjectFactory(), + mock(EventLogger.class), + mock(LogRecorder.class), + brokerOptions); } public void tearDown() throws Exception @@ -73,13 +89,15 @@ public class BrokerConfigurationStoreCreatorTest extends QpidTestCase } } + public void testCreateJsonStore() { - ConfigurationEntryStore store = _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "json", BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, false, new BrokerOptions().getConfigProperties()); + ConfigurationEntryStore store = _storeCreator.createStore(_systemContext, "json", BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, false, new BrokerOptions().getConfigProperties()); assertNotNull("Store was not created", store); assertTrue("File should exists", _userStoreLocation.exists()); assertTrue("File size should be greater than 0", _userStoreLocation.length() > 0); - JsonConfigurationEntryStore jsonStore = new JsonConfigurationEntryStore(_userStoreLocation.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); + JsonConfigurationEntryStore jsonStore = new JsonConfigurationEntryStore(_systemContext, null, false, Collections + .<String,String>emptyMap()); Set<UUID> childrenIds = jsonStore.getRootEntry().getChildrenIds(); assertFalse("Unexpected children: " + childrenIds, childrenIds.isEmpty()); } @@ -116,11 +134,11 @@ public class BrokerConfigurationStoreCreatorTest extends QpidTestCase File _initialStoreFile = TestFileUtils.createTempFile(this, ".json", brokerJson); - ConfigurationEntryStore store = _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "json", _initialStoreFile.getAbsolutePath(), false, Collections.<String,String>emptyMap()); + ConfigurationEntryStore store = _storeCreator.createStore(_systemContext, "json", _initialStoreFile.getAbsolutePath(), false, Collections.<String,String>emptyMap()); assertNotNull("Store was not created", store); assertTrue("File should exists", _userStoreLocation.exists()); assertTrue("File size should be greater than 0", _userStoreLocation.length() > 0); - JsonConfigurationEntryStore jsonStore = new JsonConfigurationEntryStore(_userStoreLocation.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); + JsonConfigurationEntryStore jsonStore = new JsonConfigurationEntryStore(_systemContext, null, false, Collections.<String,String>emptyMap()); ConfigurationEntry entry = jsonStore.getRootEntry(); assertEquals("Unexpected root id", testBrokerId, entry.getId()); Map<String, Object> attributes = entry.getAttributes(); @@ -132,13 +150,13 @@ public class BrokerConfigurationStoreCreatorTest extends QpidTestCase if(overwrite) { - ConfigurationEntryStore overwrittenStore = _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "json", BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, true, new BrokerOptions().getConfigProperties()); + ConfigurationEntryStore overwrittenStore = _storeCreator.createStore(_systemContext, "json", BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, true, new BrokerOptions().getConfigProperties()); assertNotNull("Store was not created", overwrittenStore); assertTrue("File should exists", _userStoreLocation.exists()); assertTrue("File size should be greater than 0", _userStoreLocation.length() > 0); //check the contents reflect the test store content having been overwritten with the default store - JsonConfigurationEntryStore reopenedOverwrittenStore = new JsonConfigurationEntryStore(_userStoreLocation.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); + JsonConfigurationEntryStore reopenedOverwrittenStore = new JsonConfigurationEntryStore(_systemContext, null, false, Collections.<String,String>emptyMap()); entry = reopenedOverwrittenStore.getRootEntry(); assertFalse("Root id did not change, store content was not overwritten", testBrokerId.equals(entry.getId())); attributes = entry.getAttributes(); @@ -154,7 +172,7 @@ public class BrokerConfigurationStoreCreatorTest extends QpidTestCase { try { - _storeCreator.createStore(_userStoreLocation.getAbsolutePath(), "other", null, false, Collections.<String,String>emptyMap()); + _storeCreator.createStore(_systemContext, "other", null, false, Collections.<String,String>emptyMap()); fail("Store is not yet supported"); } catch(IllegalConfigurationException e) @@ -162,4 +180,5 @@ public class BrokerConfigurationStoreCreatorTest extends QpidTestCase // pass } } + } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecovererTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecovererTest.java deleted file mode 100644 index 8b2fa4c8d7..0000000000 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/AuthenticationProviderRecovererTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.adapter.AuthenticationProviderFactory; -import org.apache.qpid.server.model.adapter.FileSystemPreferencesProvider; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.security.auth.manager.PlainPasswordFileAuthenticationManagerFactory; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; - -public class AuthenticationProviderRecovererTest extends QpidTestCase -{ - private Broker _broker; - private AuthenticationProviderRecoverer _recoverer; - private ConfigurationEntryStore _configurationStore; - - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - _broker = BrokerTestHelper.createBrokerMock(); - QpidServiceLoader<AuthenticationManagerFactory> serviceLoader = new QpidServiceLoader<AuthenticationManagerFactory>(); - AuthenticationProviderFactory authenticationProviderFactory = new AuthenticationProviderFactory(serviceLoader); - StoreConfigurationChangeListener storeChangeListener = mock(StoreConfigurationChangeListener.class); - _recoverer = new AuthenticationProviderRecoverer(authenticationProviderFactory, storeChangeListener); - _configurationStore = mock(ConfigurationEntryStore.class); - } - - public void tearDown() throws Exception - { - try - { - BrokerTestHelper.tearDown(); - } - finally - { - super.tearDown(); - } - } - - public void testRecoverAuthenticationProviderWithPreferencesProvider() - { - File authenticationProviderFile = TestFileUtils.createTempFile(this, "test-authenticator.txt", "test_user:test_user"); - try - { - Map<String, Object> authenticationAttributes = new HashMap<String, Object>(); - authenticationAttributes.put(AuthenticationProvider.TYPE, - PlainPasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - authenticationAttributes.put(AuthenticationProvider.NAME, "test-authenticator"); - authenticationAttributes.put(PlainPasswordFileAuthenticationManagerFactory.ATTRIBUTE_PATH, - authenticationProviderFile.getAbsolutePath()); - UUID authenticationId = UUID.randomUUID(); - - final PreferencesProviderRecoverer preferencesRecoverer = new PreferencesProviderRecoverer(); - RecovererProvider recovererProvider = new RecovererProvider() - { - @Override - public ConfiguredObjectRecoverer<? extends ConfiguredObject> getRecoverer(String type) - { - return preferencesRecoverer; - } - }; - - Map<String, Object> preferencesAttributes = new HashMap<String, Object>(); - UUID preferencesId = UUID.randomUUID(); - preferencesAttributes.put(PreferencesProvider.TYPE, FileSystemPreferencesProvider.PROVIDER_TYPE); - preferencesAttributes.put(PreferencesProvider.NAME, "test-provider"); - File file = TestFileUtils.createTempFile(this, ".prefs.json", - "{\"test_user\":{\"pref1\": \"pref1Value\", \"pref2\": 1.0} }"); - preferencesAttributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - ConfigurationEntry preferencesEntry = new ConfigurationEntry(preferencesId, PreferencesProvider.class.getSimpleName(), - preferencesAttributes, Collections.<UUID> emptySet(), _configurationStore); - when(_configurationStore.getEntry(preferencesId)).thenReturn(preferencesEntry); - - ConfigurationEntry authenticationProviderEntry = new ConfigurationEntry(authenticationId, - AuthenticationProvider.class.getSimpleName(), authenticationAttributes, Collections.singleton(preferencesId), - _configurationStore); - try - { - AuthenticationProvider authenticationProvider = _recoverer.create(recovererProvider, authenticationProviderEntry, - _broker); - assertNotNull("Authentication provider was not recovered", authenticationProvider); - assertEquals("Unexpected name", "test-authenticator", authenticationProvider.getName()); - assertEquals("Unexpected id", authenticationId, authenticationProvider.getId()); - PreferencesProvider preferencesProvider = authenticationProvider.getPreferencesProvider(); - assertNotNull("Preferences provider was not recovered", preferencesProvider); - assertEquals("Unexpected path", file.getAbsolutePath(), - preferencesProvider.getAttribute(FileSystemPreferencesProvider.PATH)); - } - finally - { - file.delete(); - } - } - finally - { - authenticationProviderFile.delete(); - } - } - -} diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java index cec5dc281a..ad0cf7e1f2 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/BrokerRecovererTest.java @@ -20,74 +20,61 @@ */ package org.apache.qpid.server.configuration.startup; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import junit.framework.TestCase; +import org.apache.qpid.server.BrokerOptions; +import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.configuration.RecovererProvider; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.logging.EventLogger; +import org.apache.qpid.server.logging.LogRecorder; +import org.apache.qpid.server.model.*; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.ConfiguredObjectRecordImpl; +import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.store.TestMemoryMessageStore; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.UUID; -import junit.framework.TestCase; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Model; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.UUIDGenerator; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.adapter.AccessControlProviderFactory; -import org.apache.qpid.server.model.adapter.AuthenticationProviderFactory; -import org.apache.qpid.server.model.adapter.GroupProviderFactory; -import org.apache.qpid.server.model.adapter.PortFactory; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class BrokerRecovererTest extends TestCase { - private BrokerRecoverer _brokerRecoverer; - private ConfigurationEntry _brokerEntry = mock(ConfigurationEntry.class); + private ConfiguredObjectRecord _brokerEntry = mock(ConfiguredObjectRecord.class); private UUID _brokerId = UUID.randomUUID(); - private Map<String, Collection<ConfigurationEntry>> _brokerEntryChildren = new HashMap<String, Collection<ConfigurationEntry>>(); - private ConfigurationEntry _authenticationProviderEntry1; + private Map<String, Collection<ConfiguredObjectRecord>> _brokerEntryChildren = new HashMap<String, Collection<ConfiguredObjectRecord>>(); + private ConfiguredObjectRecord _authenticationProviderEntry1; private AuthenticationProvider _authenticationProvider1; private UUID _authenticationProvider1Id = UUID.randomUUID(); + private SystemContext _systemContext; + private ConfiguredObjectFactory _configuredObjectFactory; @Override protected void setUp() throws Exception { super.setUp(); - _brokerRecoverer = new BrokerRecoverer(mock(AuthenticationProviderFactory.class), mock(GroupProviderFactory.class), mock(AccessControlProviderFactory.class), mock(PortFactory.class), - mock(StatisticsGatherer.class), mock(VirtualHostRegistry.class), mock(LogRecorder.class), - mock(TaskExecutor.class), mock(BrokerOptions.class), - mock(StoreConfigurationChangeListener.class)); + _configuredObjectFactory = new ConfiguredObjectFactory(); + _systemContext = new SystemContext(mock(TaskExecutor.class), + _configuredObjectFactory, mock(EventLogger.class), mock(LogRecorder.class), mock(BrokerOptions.class)); + when(_brokerEntry.getId()).thenReturn(_brokerId); - when(_brokerEntry.getChildren()).thenReturn(_brokerEntryChildren); + when(_brokerEntry.getType()).thenReturn(Broker.class.getSimpleName()); when(_brokerEntry.getAttributes()).thenReturn(Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, Model.MODEL_VERSION)); + when(_brokerEntry.getParents()).thenReturn(Collections.singletonMap(SystemContext.class.getSimpleName(), _systemContext.asObjectRecord())); //Add a base AuthenticationProvider for all tests _authenticationProvider1 = mock(AuthenticationProvider.class); when(_authenticationProvider1.getName()).thenReturn("authenticationProvider1"); when(_authenticationProvider1.getId()).thenReturn(_authenticationProvider1Id); - _authenticationProviderEntry1 = mock(ConfigurationEntry.class); + _authenticationProviderEntry1 = mock(ConfiguredObjectRecord.class); _brokerEntryChildren.put(AuthenticationProvider.class.getSimpleName(), Arrays.asList(_authenticationProviderEntry1)); } @@ -120,16 +107,9 @@ public class BrokerRecovererTest extends TestCase when(_brokerEntry.getAttributes()).thenReturn(entryAttributes); - final ConfigurationEntry virtualHostEntry = mock(ConfigurationEntry.class); - String typeName = VirtualHost.class.getSimpleName(); - when(virtualHostEntry.getType()).thenReturn(typeName); - _brokerEntryChildren.put(typeName, Arrays.asList(virtualHostEntry)); - final VirtualHost virtualHost = mock(VirtualHost.class); - when(virtualHost.getName()).thenReturn("test"); + _systemContext.resolveObjects(_brokerEntry); + Broker broker = _systemContext.getBroker(); - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[] { virtualHostEntry, _authenticationProviderEntry1 }, - new ConfiguredObject[] { virtualHost, _authenticationProvider1 }); - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); assertNotNull(broker); assertEquals(_brokerId, broker.getId()); @@ -142,153 +122,136 @@ public class BrokerRecovererTest extends TestCase public void testCreateBrokerWithVirtualHost() { - final ConfigurationEntry virtualHostEntry = mock(ConfigurationEntry.class); + final ConfiguredObjectRecord virtualHostEntry = mock(ConfiguredObjectRecord.class); String typeName = VirtualHost.class.getSimpleName(); when(virtualHostEntry.getType()).thenReturn(typeName); _brokerEntryChildren.put(typeName, Arrays.asList(virtualHostEntry)); - final VirtualHost virtualHost = mock(VirtualHost.class); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{virtualHostEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{virtualHost, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); + UUID vhostId = UUID.randomUUID(); + _systemContext.resolveObjects(_brokerEntry, createVhostRecord(vhostId)); + Broker<?> broker = _systemContext.getBroker(); assertNotNull(broker); assertEquals(_brokerId, broker.getId()); assertEquals(1, broker.getVirtualHosts().size()); - assertEquals(virtualHost, broker.getVirtualHosts().iterator().next()); + assertEquals(vhostId, broker.getVirtualHosts().iterator().next().getId()); + } - public void testCreateBrokerWithPorts() + public ConfiguredObjectRecord createVhostRecord(UUID id) { - ConfigurationEntry portEntry = mock(ConfigurationEntry.class); - Port port = mock(Port.class); - _brokerEntryChildren.put(Port.class.getSimpleName(), Arrays.asList(portEntry)); - - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{portEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{port, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); - - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singletonList(port), broker.getPorts()); + final Map<String, Object> vhostAttributes = new HashMap<String, Object>(); + vhostAttributes.put(VirtualHost.NAME, "vhost"); + vhostAttributes.put(VirtualHost.TYPE, "STANDARD"); + vhostAttributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, Collections.singletonMap(MessageStore.STORE_TYPE, + TestMemoryMessageStore.TYPE)); + return new ConfiguredObjectRecordImpl(id, VirtualHost.class.getSimpleName(), vhostAttributes, Collections + .singletonMap(Broker.class.getSimpleName(), _brokerEntry)); } - public void testCreateBrokerWithOneAuthenticationProvider() + public ConfiguredObjectRecord createAuthProviderRecord(UUID id, String name) { - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{_authenticationProviderEntry1}, - new ConfiguredObject[]{_authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); + final Map<String, Object> authProviderAttrs = new HashMap<String, Object>(); + authProviderAttrs.put(AuthenticationProvider.NAME, name); + authProviderAttrs.put(AuthenticationProvider.TYPE, "Anonymous"); - assertNotNull(broker); - assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singletonList(_authenticationProvider1), broker.getAuthenticationProviders()); + return new ConfiguredObjectRecordImpl(id, AuthenticationProvider.class.getSimpleName(), authProviderAttrs, Collections + .singletonMap(Broker.class.getSimpleName(), _brokerEntry)); } - public void testCreateBrokerWithMultipleAuthenticationProvidersAndPorts() + + public ConfiguredObjectRecord createGroupProviderRecord(UUID id, String name) { - //Create a second authentication provider - AuthenticationProvider authenticationProvider2 = mock(AuthenticationProvider.class); - when(authenticationProvider2.getName()).thenReturn("authenticationProvider2"); - ConfigurationEntry authenticationProviderEntry2 = mock(ConfigurationEntry.class); - _brokerEntryChildren.put(AuthenticationProvider.class.getSimpleName(), Arrays.asList(_authenticationProviderEntry1, authenticationProviderEntry2)); - - //Add a couple ports - ConfigurationEntry portEntry1 = mock(ConfigurationEntry.class); - Port port1 = mock(Port.class); - when(port1.getId()).thenReturn(UUIDGenerator.generateRandomUUID()); - when(port1.getName()).thenReturn("port1"); - when(port1.getPort()).thenReturn(5671); - when(port1.getAttribute(Port.AUTHENTICATION_PROVIDER)).thenReturn("authenticationProvider1"); - ConfigurationEntry portEntry2 = mock(ConfigurationEntry.class); - Port port2 = mock(Port.class); - when(port2.getId()).thenReturn(UUIDGenerator.generateRandomUUID()); - when(port2.getName()).thenReturn("port2"); - when(port2.getPort()).thenReturn(5672); - when(port2.getAttribute(Port.AUTHENTICATION_PROVIDER)).thenReturn("authenticationProvider2"); - _brokerEntryChildren.put(Port.class.getSimpleName(), Arrays.asList(portEntry1, portEntry2)); - - RecovererProvider recovererProvider = createRecoveryProvider( - new ConfigurationEntry[]{portEntry1, portEntry2, authenticationProviderEntry2, _authenticationProviderEntry1}, - new ConfiguredObject[]{port1, port2, authenticationProvider2, _authenticationProvider1}); - - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); + final Map<String, Object> groupProviderAttrs = new HashMap<String, Object>(); + groupProviderAttrs.put(GroupProvider.NAME, name); + groupProviderAttrs.put(GroupProvider.TYPE, "GroupFile"); + groupProviderAttrs.put("path", "/no-such-path"); - assertNotNull(broker); - assertEquals("Unexpected number of authentication providers", 2, broker.getAuthenticationProviders().size()); + return new ConfiguredObjectRecordImpl(id, GroupProvider.class.getSimpleName(), groupProviderAttrs, Collections + .singletonMap(Broker.class.getSimpleName(), _brokerEntry)); + } - Collection<Port> ports = broker.getPorts(); - assertEquals("Unexpected number of ports", 2, ports.size()); - assertTrue(ports.contains(port1)); - assertTrue(ports.contains(port2)); + public ConfiguredObjectRecord createPortRecord(UUID id, int port, Object authProviderRef) + { + final Map<String, Object> portAttrs = new HashMap<String, Object>(); + portAttrs.put(Port.NAME, "port-"+port); + portAttrs.put(Port.TYPE, "HTTP"); + portAttrs.put(Port.PORT, port); + portAttrs.put(Port.AUTHENTICATION_PROVIDER, authProviderRef); + + return new ConfiguredObjectRecordImpl(id, Port.class.getSimpleName(), portAttrs, Collections + .singletonMap(Broker.class.getSimpleName(), _brokerEntry)); } - public void testCreateBrokerWithGroupProvider() + + public void testCreateBrokerWithPorts() { - ConfigurationEntry groupProviderEntry = mock(ConfigurationEntry.class); - GroupProvider groupProvider = mock(GroupProvider.class); - _brokerEntryChildren.put(GroupProvider.class.getSimpleName(), Arrays.asList(groupProviderEntry)); + UUID authProviderId = UUID.randomUUID(); + UUID portId = UUID.randomUUID(); - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{groupProviderEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{groupProvider, _authenticationProvider1}); + _systemContext.resolveObjects(_brokerEntry, createAuthProviderRecord(authProviderId, "authProvider"), createPortRecord( + portId, + 5672, + "authProvider")); + Broker<?> broker = _systemContext.getBroker(); - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); assertNotNull(broker); assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singletonList(groupProvider), broker.getGroupProviders()); + assertEquals(1, broker.getPorts().size()); } - public void testCreateBrokerWithPlugins() + public void testCreateBrokerWithOneAuthenticationProvider() { - ConfigurationEntry pluginEntry = mock(ConfigurationEntry.class); - Plugin plugin = mock(Plugin.class); - _brokerEntryChildren.put(Plugin.class.getSimpleName(), Arrays.asList(pluginEntry)); + UUID authProviderId = UUID.randomUUID(); - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{pluginEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{plugin, _authenticationProvider1}); + _systemContext.resolveObjects(_brokerEntry, createAuthProviderRecord(authProviderId, "authProvider")); + Broker<?> broker = _systemContext.getBroker(); - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); assertNotNull(broker); assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singleton(plugin), new HashSet<ConfiguredObject>(broker.getChildren(Plugin.class))); + assertEquals(1, broker.getAuthenticationProviders().size()); + } - public void testCreateBrokerWithKeyStores() + public void testCreateBrokerWithMultipleAuthenticationProvidersAndPorts() { - ConfigurationEntry pluginEntry = mock(ConfigurationEntry.class); - KeyStore keyStore = mock(KeyStore.class); - _brokerEntryChildren.put(KeyStore.class.getSimpleName(), Arrays.asList(pluginEntry)); + UUID authProviderId = UUID.randomUUID(); + UUID portId = UUID.randomUUID(); + UUID authProvider2Id = UUID.randomUUID(); + UUID port2Id = UUID.randomUUID(); - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{pluginEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{keyStore, _authenticationProvider1}); + _systemContext.resolveObjects(_brokerEntry, + createAuthProviderRecord(authProviderId, "authProvider"), + createPortRecord(portId, 5672, "authProvider"), + createAuthProviderRecord(authProvider2Id, "authProvider2"), + createPortRecord(port2Id, 5673, "authProvider2")); + Broker<?> broker = _systemContext.getBroker(); - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); assertNotNull(broker); assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singleton(keyStore), new HashSet<ConfiguredObject>(broker.getChildren(KeyStore.class))); + assertEquals(2, broker.getPorts().size()); + + assertEquals("Unexpected number of authentication providers", 2, broker.getAuthenticationProviders().size()); + } - public void testCreateBrokerWithTrustStores() + public void testCreateBrokerWithGroupProvider() { - ConfigurationEntry pluginEntry = mock(ConfigurationEntry.class); - TrustStore trustStore = mock(TrustStore.class); - _brokerEntryChildren.put(TrustStore.class.getSimpleName(), Arrays.asList(pluginEntry)); - RecovererProvider recovererProvider = createRecoveryProvider(new ConfigurationEntry[]{pluginEntry, _authenticationProviderEntry1}, - new ConfiguredObject[]{trustStore, _authenticationProvider1}); + UUID authProviderId = UUID.randomUUID(); + + _systemContext.resolveObjects(_brokerEntry, createGroupProviderRecord(authProviderId, "groupProvider")); + Broker<?> broker = _systemContext.getBroker(); - Broker broker = _brokerRecoverer.create(recovererProvider, _brokerEntry); assertNotNull(broker); assertEquals(_brokerId, broker.getId()); - assertEquals(Collections.singleton(trustStore), new HashSet<ConfiguredObject>(broker.getChildren(TrustStore.class))); + assertEquals(1, broker.getGroupProviders().size()); + } public void testModelVersionValidationForIncompatibleMajorVersion() throws Exception @@ -302,7 +265,8 @@ public class BrokerRecovererTest extends TestCase try { - _brokerRecoverer.create(null, _brokerEntry); + _systemContext.resolveObjects(_brokerEntry); + Broker<?> broker = _systemContext.getBroker(); fail("The broker creation should fail due to unsupported model version"); } catch (IllegalConfigurationException e) @@ -323,7 +287,7 @@ public class BrokerRecovererTest extends TestCase try { - _brokerRecoverer.create(null, _brokerEntry); + Broker broker = (Broker) _configuredObjectFactory.recover(_brokerEntry, _systemContext).resolve(); fail("The broker creation should fail due to unsupported model version"); } catch (IllegalConfigurationException e) @@ -344,7 +308,8 @@ public class BrokerRecovererTest extends TestCase try { - _brokerRecoverer.create(null, _brokerEntry); + Broker broker = (Broker) _configuredObjectFactory.recover(_brokerEntry, _systemContext).resolve(); + fail("The broker creation should fail due to unsupported model version"); } catch (IllegalConfigurationException e) @@ -359,7 +324,7 @@ public class BrokerRecovererTest extends TestCase return String.valueOf(attributeValue); } - private RecovererProvider createRecoveryProvider(final ConfigurationEntry[] entries, final ConfiguredObject[] objectsToRecoverer) + private RecovererProvider createRecoveryProvider(final ConfiguredObjectRecord[] entries, final ConfiguredObject[] objectsToRecoverer) { RecovererProvider recovererProvider = new RecovererProvider() { @@ -369,12 +334,11 @@ public class BrokerRecovererTest extends TestCase @SuppressWarnings({ "unchecked", "rawtypes" }) final ConfiguredObjectRecoverer<? extends ConfiguredObject> recoverer = new ConfiguredObjectRecoverer() { - @Override - public ConfiguredObject create(RecovererProvider recovererProvider, ConfigurationEntry entry, ConfiguredObject... parents) + public ConfiguredObject create(RecovererProvider recovererProvider, ConfiguredObjectRecord entry, ConfiguredObject... parents) { for (int i = 0; i < entries.length; i++) { - ConfigurationEntry e = entries[i]; + ConfiguredObjectRecord e = entries[i]; if (entry == e) { return objectsToRecoverer[i]; diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java deleted file mode 100644 index 57acea7351..0000000000 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/DefaultRecovererProviderTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import static org.mockito.Mockito.mock; -import junit.framework.TestCase; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.logging.LogRecorder; -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.virtualhost.VirtualHostRegistry; - -public class DefaultRecovererProviderTest extends TestCase -{ - public void testGetRecoverer() - { - String[] supportedTypes = {Broker.class.getSimpleName(), - VirtualHost.class.getSimpleName(), AuthenticationProvider.class.getSimpleName(), - GroupProvider.class.getSimpleName(), Plugin.class.getSimpleName(), Port.class.getSimpleName(), - KeyStore.class.getSimpleName(), TrustStore.class.getSimpleName()}; - - // mocking the required object - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); - VirtualHostRegistry virtualHostRegistry = mock(VirtualHostRegistry.class); - LogRecorder logRecorder = mock(LogRecorder.class); - - TaskExecutor taskExecutor = mock(TaskExecutor.class); - - DefaultRecovererProvider provider = new DefaultRecovererProvider(statisticsGatherer, virtualHostRegistry, - logRecorder, taskExecutor, mock(BrokerOptions.class), - mock(StoreConfigurationChangeListener.class)); - for (String configuredObjectType : supportedTypes) - { - ConfiguredObjectRecoverer<?> recoverer = provider.getRecoverer(configuredObjectType); - assertNotNull("Null recoverer for type: " + configuredObjectType, recoverer); - } - } - -} diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/KeyStoreRecovererTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/FileKeyStoreCreationTest.java index 55dc225326..580870c66e 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/KeyStoreRecovererTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/FileKeyStoreCreationTest.java @@ -20,29 +20,24 @@ */ package org.apache.qpid.server.configuration.startup; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import junit.framework.TestCase; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.KeyStore; +import org.apache.qpid.server.security.AbstractKeyStoreAdapter; +import org.apache.qpid.server.security.FileKeyStore; +import org.apache.qpid.server.security.SecurityManager; +import org.apache.qpid.test.utils.TestSSLConstants; +import javax.net.ssl.KeyManagerFactory; +import javax.security.auth.Subject; import java.security.PrivilegedAction; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import javax.net.ssl.KeyManagerFactory; -import javax.security.auth.Subject; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.adapter.AbstractKeyStoreAdapter; -import org.apache.qpid.server.security.*; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.test.utils.TestSSLConstants; +import static org.mockito.Mockito.mock; -public class KeyStoreRecovererTest extends TestCase +public class FileKeyStoreCreationTest extends TestCase { public void testCreateWithAllAttributesProvided() @@ -52,12 +47,8 @@ public class KeyStoreRecovererTest extends TestCase UUID id = UUID.randomUUID(); Broker broker = mock(Broker.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - when(entry.getAttributes()).thenReturn(attributes); - when(entry.getId()).thenReturn(id); - KeyStoreRecoverer recoverer = new KeyStoreRecoverer(); - final KeyStore keyStore = recoverer.create(null, entry, broker); + final KeyStore keyStore = new FileKeyStore(id,broker,attributes); assertNotNull("Key store configured object is not created", keyStore); assertEquals(id, keyStore.getId()); @@ -93,20 +84,15 @@ public class KeyStoreRecovererTest extends TestCase UUID id = UUID.randomUUID(); Broker broker = mock(Broker.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - when(entry.getId()).thenReturn(id); - - KeyStoreRecoverer recoverer = new KeyStoreRecoverer(); String[] mandatoryProperties = {KeyStore.NAME, KeyStore.PATH, KeyStore.PASSWORD}; for (int i = 0; i < mandatoryProperties.length; i++) { Map<String, Object> properties = new HashMap<String, Object>(attributes); properties.remove(mandatoryProperties[i]); - when(entry.getAttributes()).thenReturn(properties); try { - recoverer.create(null, entry, broker); + new FileKeyStore(id, broker, properties); fail("Cannot create key store without a " + mandatoryProperties[i]); } catch(IllegalArgumentException e) @@ -128,4 +114,5 @@ public class KeyStoreRecovererTest extends TestCase return attributes; } + } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/TrustStoreRecovererTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/FileTrustStoreCreationTest.java index 5e0ce9dbc4..33d53e7f3d 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/TrustStoreRecovererTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/FileTrustStoreCreationTest.java @@ -21,7 +21,6 @@ package org.apache.qpid.server.configuration.startup; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import java.security.PrivilegedAction; import java.util.HashMap; @@ -31,16 +30,15 @@ import java.util.UUID; import javax.net.ssl.TrustManagerFactory; import javax.security.auth.Subject; -import org.apache.qpid.server.configuration.ConfigurationEntry; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.adapter.AbstractKeyStoreAdapter; -import org.apache.qpid.server.security.*; +import org.apache.qpid.server.security.AbstractKeyStoreAdapter; +import org.apache.qpid.server.security.FileTrustStore; import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.test.utils.TestSSLConstants; -public class TrustStoreRecovererTest extends QpidTestCase +public class FileTrustStoreCreationTest extends QpidTestCase { public void testCreateWithAllAttributesProvided() { @@ -49,13 +47,8 @@ public class TrustStoreRecovererTest extends QpidTestCase UUID id = UUID.randomUUID(); Broker broker = mock(Broker.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - when(entry.getAttributes()).thenReturn(attributes); - when(entry.getId()).thenReturn(id); - TrustStoreRecoverer recoverer = new TrustStoreRecoverer(); - - final TrustStore trustStore = recoverer.create(null, entry, broker); + final TrustStore trustStore = new FileTrustStore(id, broker, attributes); assertNotNull("Trust store configured object is not created", trustStore); assertEquals(id, trustStore.getId()); @@ -90,21 +83,15 @@ public class TrustStoreRecovererTest extends QpidTestCase UUID id = UUID.randomUUID(); Broker broker = mock(Broker.class); - ConfigurationEntry entry = mock(ConfigurationEntry.class); - when(entry.getAttributes()).thenReturn(attributes); - when(entry.getId()).thenReturn(id); - - TrustStoreRecoverer recoverer = new TrustStoreRecoverer(); String[] mandatoryProperties = {TrustStore.NAME, TrustStore.PATH, TrustStore.PASSWORD}; for (int i = 0; i < mandatoryProperties.length; i++) { Map<String, Object> properties = new HashMap<String, Object>(attributes); properties.remove(mandatoryProperties[i]); - when(entry.getAttributes()).thenReturn(properties); try { - recoverer.create(null, entry, broker); + TrustStore trustStore = new FileTrustStore(id, broker, properties); fail("Cannot create key store without a " + mandatoryProperties[i]); } catch(IllegalArgumentException e) @@ -126,4 +113,5 @@ public class TrustStoreRecovererTest extends QpidTestCase return attributes; } + } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java deleted file mode 100644 index d6f03a9758..0000000000 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/GroupProviderRecovererTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; -import static org.mockito.Mockito.*; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.GroupProvider; -import org.apache.qpid.server.model.adapter.GroupProviderFactory; -import org.apache.qpid.server.plugin.GroupManagerFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; -import org.apache.qpid.server.security.group.GroupManager; - -import junit.framework.TestCase; - -public class GroupProviderRecovererTest extends TestCase -{ - - private UUID _id; - private Map<String, Object> _attributes; - - private GroupManagerFactory _factory; - private QpidServiceLoader<GroupManagerFactory> _groupManagerServiceLoader; - private Broker _broker; - private ConfigurationEntry _configurationEntry; - private GroupProviderFactory _groupProviderFactory; - - @SuppressWarnings("unchecked") - protected void setUp() throws Exception - { - super.setUp(); - _id = UUID.randomUUID(); - _attributes = new HashMap<String, Object>(); - - _factory = mock(GroupManagerFactory.class); - - _groupManagerServiceLoader = mock(QpidServiceLoader.class); - when(_groupManagerServiceLoader.instancesOf(GroupManagerFactory.class)).thenReturn(Collections.singletonList(_factory )); - _groupProviderFactory = new GroupProviderFactory(_groupManagerServiceLoader); - - _broker = mock(Broker.class); - - _configurationEntry = mock(ConfigurationEntry.class); - when(_configurationEntry.getId()).thenReturn(_id); - when(_configurationEntry.getAttributes()).thenReturn(_attributes); - } - - public void testCreate() - { - GroupManager groupManager = mock(GroupManager.class); - String name = groupManager.getClass().getSimpleName(); - _attributes.put(GroupProvider.NAME, name); - when(_factory.createInstance(_attributes)).thenReturn(groupManager); - GroupProviderRecoverer groupProviderRecoverer = new GroupProviderRecoverer(_groupProviderFactory); - GroupProvider groupProvider = groupProviderRecoverer.create(null, _configurationEntry, _broker); - assertNotNull("Null group provider", groupProvider); - assertEquals("Unexpected name", name, groupProvider.getName()); - assertEquals("Unexpected ID", _id, groupProvider.getId()); - } - - public void testCreateThrowsExceptionWhenNoGroupManagerIsCreated() - { - when(_factory.createInstance(_attributes)).thenReturn(null); - - GroupProviderRecoverer groupProviderRecoverer = new GroupProviderRecoverer(_groupProviderFactory); - try - { - groupProviderRecoverer.create(null, _configurationEntry, _broker); - fail("Configuration exception should be thrown when group manager is not created"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - -} diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java deleted file mode 100644 index 42fd742407..0000000000 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/PluginRecovererTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.Plugin; -import org.apache.qpid.server.plugin.PluginFactory; -import org.apache.qpid.server.plugin.QpidServiceLoader; - -public class PluginRecovererTest extends TestCase -{ - private UUID _id; - private Map<String, Object> _attributes; - - private PluginFactory _factory; - private QpidServiceLoader<PluginFactory> _pluginFactoryServiceLoader; - private Broker _broker; - private ConfigurationEntry _configurationEntry; - - @SuppressWarnings("unchecked") - protected void setUp() throws Exception - { - super.setUp(); - _id = UUID.randomUUID(); - _attributes = new HashMap<String, Object>(); - - _factory = mock(PluginFactory.class); - - _pluginFactoryServiceLoader = mock(QpidServiceLoader.class); - when(_pluginFactoryServiceLoader.instancesOf(PluginFactory.class)).thenReturn(Collections.singletonList(_factory )); - - _broker = mock(Broker.class); - - _configurationEntry = mock(ConfigurationEntry.class); - when(_configurationEntry.getId()).thenReturn(_id); - when(_configurationEntry.getAttributes()).thenReturn(_attributes); - } - - public void testCreate() - { - Plugin pluginFromFactory = mock(Plugin.class); - when(pluginFromFactory.getId()).thenReturn(_id); - when(_factory.createInstance(_id, _attributes, _broker)).thenReturn(pluginFromFactory); - - PluginRecoverer pluginRecoverer = new PluginRecoverer(_pluginFactoryServiceLoader); - ConfiguredObject pluginFromRecoverer = pluginRecoverer.create(null, _configurationEntry, _broker); - assertNotNull("Null group provider", pluginFromRecoverer); - assertSame("Unexpected plugin", pluginFromFactory, pluginFromRecoverer); - assertEquals("Unexpected ID", _id, pluginFromRecoverer.getId()); - } - - public void testCreateThrowsExceptionForUnexpectedId() - { - Plugin pluginFromFactory = mock(Plugin.class); - when(pluginFromFactory.getId()).thenReturn(UUID.randomUUID()); - when(_factory.createInstance(_id, _attributes, _broker)).thenReturn(pluginFromFactory); - - PluginRecoverer pluginRecoverer = new PluginRecoverer(_pluginFactoryServiceLoader); - try - { - pluginRecoverer.create(null, _configurationEntry, _broker); - fail("An exception should be thrown for incorrect id"); - } - catch(IllegalStateException e) - { - //pass - } - } - - public void testCreateThrowsExceptionWhenNoPluginIsCreated() - { - when(_factory.createInstance(_id, _attributes, _broker)).thenReturn(null); - - PluginRecoverer pluginRecoverer = new PluginRecoverer(_pluginFactoryServiceLoader); - try - { - pluginRecoverer.create(null, _configurationEntry, _broker); - fail("Configuration exception should be thrown when plugin is not created"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - -} diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/PreferencesProviderRecovererTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/PreferencesProviderCreationTest.java index 1fc630dae0..9c224aead3 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/PreferencesProviderRecovererTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/PreferencesProviderCreationTest.java @@ -21,18 +21,6 @@ package org.apache.qpid.server.configuration.startup; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.RecovererProvider; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.PreferencesProvider; @@ -41,6 +29,14 @@ import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.test.utils.TestFileUtils; +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /* * * Licensed to the Apache Software Foundation (ASF) under one @@ -61,7 +57,7 @@ import org.apache.qpid.test.utils.TestFileUtils; * under the License. * */ -public class PreferencesProviderRecovererTest extends QpidTestCase +public class PreferencesProviderCreationTest extends QpidTestCase { private AuthenticationProvider _authenticationProvider; private Broker _broker; @@ -89,18 +85,18 @@ public class PreferencesProviderRecovererTest extends QpidTestCase public void testRecoverFileSystemPreferencesProvider() { - PreferencesProviderRecoverer recoverer = new PreferencesProviderRecoverer(); Map<String, Object> attributes = new HashMap<String, Object>(); UUID id = UUID.randomUUID(); attributes.put(PreferencesProvider.TYPE, FileSystemPreferencesProvider.PROVIDER_TYPE); attributes.put(PreferencesProvider.NAME, "test-provider"); - File file = TestFileUtils.createTempFile(this, ".prefs.json", "{\"test_user\":{\"pref1\": \"pref1Value\", \"pref2\": 1.0} }"); + File file = TestFileUtils.createTempFile(this, + ".prefs.json", + "{\"test_user\":{\"pref1\": \"pref1Value\", \"pref2\": 1.0} }"); try { attributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - ConfigurationEntry entry = new ConfigurationEntry(id, PreferencesProvider.class.getSimpleName(), attributes, Collections.<UUID>emptySet(), mock(ConfigurationEntryStore.class)); - PreferencesProvider provider = recoverer.create(mock(RecovererProvider.class), entry, _authenticationProvider); + PreferencesProvider provider = new FileSystemPreferencesProvider(id,attributes,_authenticationProvider); assertNotNull("Preferences provider was not recovered", provider); assertEquals("Unexpected name", "test-provider", provider.getName()); assertEquals("Unexpected id", id, provider.getId()); diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/StoreUpgraderTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/StoreUpgraderTest.java deleted file mode 100644 index cc5137ed66..0000000000 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/StoreUpgraderTest.java +++ /dev/null @@ -1,415 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.configuration.startup; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.model.VirtualHost; - -public class StoreUpgraderTest extends TestCase -{ - - private final UUID _brokerId = UUID.randomUUID(); - private final UUID _virtualHostId = UUID.randomUUID(); - private ConfigurationEntryStore _store = mock(ConfigurationEntryStore.class); - - public void testUpgrade13To14_RejectsConfigPath() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("configPath", "/mypath"); - try - { - doTest(_store, virtualHostAttributes); - fail("Upgrade of virtual host with configuration XML is unsupported at the moment"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - - public void testUpgrade13To14_Derby() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("storeType", "DERBy"); - virtualHostAttributes.put("storePath", "/mystorepath"); - virtualHostAttributes.put("storeUnderfullSize", 1000); - virtualHostAttributes.put("storeOverfullSize", 2000); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostMessageSettings = new HashMap<String, Object>(); - expectedNewVirtualHostMessageSettings.put("storeType", "DERBY"); - expectedNewVirtualHostMessageSettings.put("storePath", "/mystorepath"); - expectedNewVirtualHostMessageSettings.put("storeUnderfullSize", 1000); - expectedNewVirtualHostMessageSettings.put("storeOverfullSize", 2000); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - expectedNewVirtualHostAttributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, expectedNewVirtualHostMessageSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - public void testUpgrade13To14_DerbyConfigurationStore() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("configStoreType", "DERBy"); - virtualHostAttributes.put("configStorePath", "/mystorepath"); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostConfigurationStoreSettings = new HashMap<String, Object>(); - expectedNewVirtualHostConfigurationStoreSettings.put("storeType", "DERBY"); - expectedNewVirtualHostConfigurationStoreSettings.put("storePath", "/mystorepath"); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - expectedNewVirtualHostAttributes.put(VirtualHost.CONFIGURATION_STORE_SETTINGS, expectedNewVirtualHostConfigurationStoreSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - public void testUpgrade13To14_JsonConfigurationStore() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("configStoreType", "JsoN"); - virtualHostAttributes.put("configStorePath", "/mystorepath"); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostConfigurationStoreSettings = new HashMap<String, Object>(); - expectedNewVirtualHostConfigurationStoreSettings.put("storeType", "JSON"); - expectedNewVirtualHostConfigurationStoreSettings.put("storePath", "/mystorepath"); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - expectedNewVirtualHostAttributes.put(VirtualHost.CONFIGURATION_STORE_SETTINGS, expectedNewVirtualHostConfigurationStoreSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - public void testUpgrade13To14_BdbHa() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "BDB_HA"); - virtualHostAttributes.put("storeType", "BdB-HA"); - virtualHostAttributes.put("storePath", "/mystorepath"); - virtualHostAttributes.put("storeUnderfullSize", 1000); - virtualHostAttributes.put("storeOverfullSize", 2000); - virtualHostAttributes.put("haNodeName", "node1"); - virtualHostAttributes.put("haGroupName", "group1"); - virtualHostAttributes.put("haHelperAddress", "helper:1000"); - virtualHostAttributes.put("haCoalescingSync", true); - virtualHostAttributes.put("haNodeAddress", "nodeaddr:1000"); - virtualHostAttributes.put("haDurability", "sync,sync,all"); - virtualHostAttributes.put("haDesignatedPrimary", true); - virtualHostAttributes.put("haReplicationConfig", Collections.singletonMap("hasettings", "havalue")); - virtualHostAttributes.put("bdbEnvironmentConfig", Collections.singletonMap("envsettings", "envvalue")); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostMessageSettings = new HashMap<String, Object>(); - expectedNewVirtualHostMessageSettings.put("storePath", "/mystorepath"); - expectedNewVirtualHostMessageSettings.put("storeUnderfullSize", 1000); - expectedNewVirtualHostMessageSettings.put("storeOverfullSize", 2000); - expectedNewVirtualHostMessageSettings.put("haNodeName", "node1"); - expectedNewVirtualHostMessageSettings.put("haGroupName", "group1"); - expectedNewVirtualHostMessageSettings.put("haHelperAddress", "helper:1000"); - expectedNewVirtualHostMessageSettings.put("haCoalescingSync", true); - expectedNewVirtualHostMessageSettings.put("haNodeAddress", "nodeaddr:1000"); - expectedNewVirtualHostMessageSettings.put("haDurability", "sync,sync,all"); - expectedNewVirtualHostMessageSettings.put("haDesignatedPrimary", true); - expectedNewVirtualHostMessageSettings.put("haReplicationConfig", Collections.singletonMap("hasettings", "havalue")); - expectedNewVirtualHostMessageSettings.put("bdbEnvironmentConfig", Collections.singletonMap("envsettings", "envvalue")); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "BDB_HA"); - expectedNewVirtualHostAttributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, expectedNewVirtualHostMessageSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - public void testUpgrade13To14_Bdb() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("storeType", "BdB"); - virtualHostAttributes.put("storePath", "/mystorepath"); - virtualHostAttributes.put("storeUnderfullSize", 1000); - virtualHostAttributes.put("storeOverfullSize", 2000); - virtualHostAttributes.put("bdbEnvironmentConfig", Collections.singletonMap("envsettings", "envvalue")); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostMessageSettings = new HashMap<String, Object>(); - expectedNewVirtualHostMessageSettings.put("storeType", "BDB"); - expectedNewVirtualHostMessageSettings.put("storePath", "/mystorepath"); - expectedNewVirtualHostMessageSettings.put("storeUnderfullSize", 1000); - expectedNewVirtualHostMessageSettings.put("storeOverfullSize", 2000); - expectedNewVirtualHostMessageSettings.put("bdbEnvironmentConfig", Collections.singletonMap("envsettings", "envvalue")); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - expectedNewVirtualHostAttributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, expectedNewVirtualHostMessageSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - public void testUpgrade13To14_BdbMessageStoreAndConfigurationStore() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("storeType", "BdB"); - virtualHostAttributes.put("storePath", "/mystorepath"); - virtualHostAttributes.put("storeUnderfullSize", 1000); - virtualHostAttributes.put("storeOverfullSize", 2000); - virtualHostAttributes.put("bdbEnvironmentConfig", Collections.singletonMap("envsettings", "envvalue")); - virtualHostAttributes.put("configStoreType", "BdB"); - virtualHostAttributes.put("configStorePath", "/mystorepath2"); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostMessageSettings = new HashMap<String, Object>(); - expectedNewVirtualHostMessageSettings.put("storeType", "BDB"); - expectedNewVirtualHostMessageSettings.put("storePath", "/mystorepath"); - expectedNewVirtualHostMessageSettings.put("storeUnderfullSize", 1000); - expectedNewVirtualHostMessageSettings.put("storeOverfullSize", 2000); - expectedNewVirtualHostMessageSettings.put("bdbEnvironmentConfig", Collections.singletonMap("envsettings", "envvalue")); - - Map<String, Object> expectedNewVirtualHostConfigurationSettings = new HashMap<String, Object>(); - expectedNewVirtualHostConfigurationSettings.put("storeType", "BDB"); - expectedNewVirtualHostConfigurationSettings.put("storePath", "/mystorepath2"); - expectedNewVirtualHostConfigurationSettings.put("bdbEnvironmentConfig", Collections.singletonMap("envsettings", "envvalue")); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - expectedNewVirtualHostAttributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, expectedNewVirtualHostMessageSettings); - expectedNewVirtualHostAttributes.put(VirtualHost.CONFIGURATION_STORE_SETTINGS, expectedNewVirtualHostConfigurationSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - public void testUpgrade13To14_JDBC() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("storeType", "JdBC"); - virtualHostAttributes.put("connectionURL", "jdbc:test"); - virtualHostAttributes.put("connectionPool", "BONECP"); - virtualHostAttributes.put("jdbcBigIntType", "NUMBER"); - virtualHostAttributes.put("jdbcBytesForBlob", true); - virtualHostAttributes.put("jdbcVarbinaryType", "TEST"); - virtualHostAttributes.put("jdbcBlobType", "BLOB"); - virtualHostAttributes.put("partitionCount", 10); - virtualHostAttributes.put("maxConnectionsPerPartition", 8); - virtualHostAttributes.put("minConnectionsPerPartition", 2); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostMessageSettings = new HashMap<String, Object>(); - expectedNewVirtualHostMessageSettings.put("storeType", "JDBC"); - expectedNewVirtualHostMessageSettings.put("connectionURL", "jdbc:test"); - expectedNewVirtualHostMessageSettings.put("connectionPool", "BONECP"); - expectedNewVirtualHostMessageSettings.put("jdbcBigIntType", "NUMBER"); - expectedNewVirtualHostMessageSettings.put("jdbcBytesForBlob", true); - expectedNewVirtualHostMessageSettings.put("jdbcVarbinaryType", "TEST"); - expectedNewVirtualHostMessageSettings.put("jdbcBlobType", "BLOB"); - expectedNewVirtualHostMessageSettings.put("partitionCount", 10); - expectedNewVirtualHostMessageSettings.put("maxConnectionsPerPartition", 8); - expectedNewVirtualHostMessageSettings.put("minConnectionsPerPartition", 2); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - expectedNewVirtualHostAttributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, expectedNewVirtualHostMessageSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - public void testUpgrade13To14_JDBC_withStorePath() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("storeType", "JdBC"); - virtualHostAttributes.put("storePath", "jdbc:test"); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostMessageSettings = new HashMap<String, Object>(); - expectedNewVirtualHostMessageSettings.put("storeType", "JDBC"); - expectedNewVirtualHostMessageSettings.put("connectionURL", "jdbc:test"); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - expectedNewVirtualHostAttributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, expectedNewVirtualHostMessageSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - public void testUpgrade13To14_JDBCConfigurationStoreAndMessageStore() throws Exception - { - HashMap<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put("name", "test"); - virtualHostAttributes.put("type", "STANDARD"); - virtualHostAttributes.put("storeType", "JdBC"); - virtualHostAttributes.put("connectionURL", "jdbc:test"); - virtualHostAttributes.put("connectionPool", "BONECP"); - virtualHostAttributes.put("jdbcBigIntType", "NUMBER"); - virtualHostAttributes.put("jdbcBytesForBlob", true); - virtualHostAttributes.put("jdbcVarbinaryType", "TEST"); - virtualHostAttributes.put("jdbcBlobType", "BLOB"); - virtualHostAttributes.put("partitionCount", 10); - virtualHostAttributes.put("maxConnectionsPerPartition", 8); - virtualHostAttributes.put("minConnectionsPerPartition", 2); - virtualHostAttributes.put("configStoreType", "JdBC"); - virtualHostAttributes.put("configConnectionURL", "jdbc:test2"); - - doTest(_store, virtualHostAttributes); - - ConfigurationEntry expectNewRoot = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.4"), Collections.singleton(_virtualHostId), _store); - ConfigurationEntry expectedNewVirtualHost; - { - Map<String, Object> expectedNewVirtualHostMessageSettings = new HashMap<String, Object>(); - expectedNewVirtualHostMessageSettings.put("storeType", "JDBC"); - expectedNewVirtualHostMessageSettings.put("connectionURL", "jdbc:test"); - expectedNewVirtualHostMessageSettings.put("connectionPool", "BONECP"); - expectedNewVirtualHostMessageSettings.put("jdbcBigIntType", "NUMBER"); - expectedNewVirtualHostMessageSettings.put("jdbcBytesForBlob", true); - expectedNewVirtualHostMessageSettings.put("jdbcVarbinaryType", "TEST"); - expectedNewVirtualHostMessageSettings.put("jdbcBlobType", "BLOB"); - expectedNewVirtualHostMessageSettings.put("partitionCount", 10); - expectedNewVirtualHostMessageSettings.put("maxConnectionsPerPartition", 8); - expectedNewVirtualHostMessageSettings.put("minConnectionsPerPartition", 2); - - Map<String, Object> expectedNewVirtualHostConfigurationSettings = new HashMap<String, Object>(); - expectedNewVirtualHostConfigurationSettings.put("storeType", "JDBC"); - expectedNewVirtualHostConfigurationSettings.put("connectionURL", "jdbc:test2"); - expectedNewVirtualHostConfigurationSettings.put("connectionPool", "BONECP"); - expectedNewVirtualHostConfigurationSettings.put("jdbcBigIntType", "NUMBER"); - expectedNewVirtualHostConfigurationSettings.put("jdbcBytesForBlob", true); - expectedNewVirtualHostConfigurationSettings.put("jdbcVarbinaryType", "TEST"); - expectedNewVirtualHostConfigurationSettings.put("jdbcBlobType", "BLOB"); - expectedNewVirtualHostConfigurationSettings.put("partitionCount", 10); - expectedNewVirtualHostConfigurationSettings.put("maxConnectionsPerPartition", 8); - expectedNewVirtualHostConfigurationSettings.put("minConnectionsPerPartition", 2); - - Map<String, Object> expectedNewVirtualHostAttributes = new HashMap<String, Object>(); - expectedNewVirtualHostAttributes.put(VirtualHost.NAME, "test"); - expectedNewVirtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - expectedNewVirtualHostAttributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, expectedNewVirtualHostMessageSettings); - expectedNewVirtualHostAttributes.put(VirtualHost.CONFIGURATION_STORE_SETTINGS, expectedNewVirtualHostConfigurationSettings); - - expectedNewVirtualHost = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), expectedNewVirtualHostAttributes, Collections.<UUID>emptySet(), _store); - } - verify(_store).save(expectedNewVirtualHost, expectNewRoot); - } - - private void doTest(ConfigurationEntryStore store, Map<String,Object> virtualHostAttributes) - { - final ConfigurationEntry virtualHostEntry = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, Collections.<UUID>emptySet(), store); - - final ConfigurationEntry rootEntry; - { - Map<String, Object> rootEntryAttributes = Collections.<String, Object>singletonMap(Broker.MODEL_VERSION, "1.3"); - rootEntry = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), rootEntryAttributes, Collections.singleton(_virtualHostId), store); - } - - when(store.getRootEntry()).thenReturn(rootEntry); - when(store.getEntry(_virtualHostId)).thenReturn(virtualHostEntry); - - StoreUpgrader.UPGRADE_1_3.doUpgrade(store); - } - -} diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostRecovererTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java index 472aa3fd7b..7a028a8113 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostRecovererTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java @@ -20,45 +20,44 @@ */ package org.apache.qpid.server.configuration.startup; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - import junit.framework.TestCase; - import org.apache.qpid.server.configuration.ConfigurationEntry; import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.VirtualHost; +import org.apache.qpid.server.model.adapter.StandardVirtualHostAdapter; import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.stats.StatisticsGatherer; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.store.TestMemoryMessageStore; import org.apache.qpid.server.virtualhost.StandardVirtualHostFactory; -public class VirtualHostRecovererTest extends TestCase +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class VirtualHostCreationTest extends TestCase { public void testCreateVirtualHostFromStoreConfigAttributes() { - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); SecurityManager securityManager = mock(SecurityManager.class); ConfigurationEntry entry = mock(ConfigurationEntry.class); Broker parent = mock(Broker.class); when(parent.getAttribute(Broker.VIRTUALHOST_HOUSEKEEPING_CHECK_PERIOD)).thenReturn(3000l); when(parent.getSecurityManager()).thenReturn(securityManager); - VirtualHostRecoverer recoverer = new VirtualHostRecoverer(statisticsGatherer); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(VirtualHost.NAME, getName()); attributes.put(VirtualHost.TYPE, StandardVirtualHostFactory.TYPE); + attributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, Collections.singletonMap(MessageStore.STORE_TYPE, TestMemoryMessageStore.TYPE)); when(entry.getAttributes()).thenReturn(attributes); - VirtualHost host = recoverer.create(null, entry, parent); + VirtualHost host = new StandardVirtualHostAdapter(UUID.randomUUID(),attributes,parent); assertNotNull("Null is returned", host); assertEquals("Unexpected name", getName(), host.getName()); @@ -69,7 +68,8 @@ public class VirtualHostRecovererTest extends TestCase Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(VirtualHost.NAME, getName()); attributes.put(VirtualHost.TYPE, StandardVirtualHostFactory.TYPE); - attributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, Collections.singletonMap(MessageStore.STORE_TYPE, TestMemoryMessageStore.TYPE)); + attributes.put(VirtualHost.MESSAGE_STORE_SETTINGS, Collections.singletonMap(MessageStore.STORE_TYPE, + TestMemoryMessageStore.TYPE)); String[] mandatoryAttributes = {VirtualHost.NAME, VirtualHost.TYPE, VirtualHost.MESSAGE_STORE_SETTINGS}; checkMandatoryAttributesAreValidated(mandatoryAttributes, attributes); @@ -77,12 +77,10 @@ public class VirtualHostRecovererTest extends TestCase public void checkMandatoryAttributesAreValidated(String[] mandatoryAttributes, Map<String, Object> attributes) { - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); SecurityManager securityManager = mock(SecurityManager.class); ConfigurationEntry entry = mock(ConfigurationEntry.class); Broker parent = mock(Broker.class); when(parent.getSecurityManager()).thenReturn(securityManager); - VirtualHostRecoverer recoverer = new VirtualHostRecoverer(statisticsGatherer); for (String name : mandatoryAttributes) { @@ -91,7 +89,7 @@ public class VirtualHostRecovererTest extends TestCase when(entry.getAttributes()).thenReturn(copy); try { - recoverer.create(null, entry, parent); + VirtualHost host = new StandardVirtualHostAdapter(UUID.randomUUID(),copy,parent); fail("Cannot create a virtual host without a mandatory attribute " + name); } catch(IllegalConfigurationException e) diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java index fdf3ec24a1..d9a07bc2e9 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java @@ -27,9 +27,10 @@ import java.util.Set; import java.util.UUID; import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; +import org.apache.qpid.server.configuration.ConfigurationEntryImpl; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.GroupProvider; import org.apache.qpid.server.model.KeyStore; import org.apache.qpid.server.model.Port; @@ -40,11 +41,12 @@ import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.adapter.FileSystemPreferencesProvider; import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManager; import org.apache.qpid.server.security.auth.manager.ExternalAuthenticationManager; +import org.apache.qpid.server.store.ConfiguredObjectRecord; import org.apache.qpid.test.utils.QpidTestCase; public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase { - private ConfigurationEntryStore _store; + private MemoryConfigurationEntryStore _store; private UUID _brokerId; private UUID _virtualHostId; @@ -92,7 +94,8 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase } // ??? perhaps it should not be abstract - protected abstract ConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception; + + protected abstract MemoryConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception; protected abstract void addConfiguration(UUID id, String type, Map<String, Object> attributes, UUID parentId); @@ -101,7 +104,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase addConfiguration(id, type, attributes, _brokerId); } - protected ConfigurationEntryStore getStore() + protected MemoryConfigurationEntryStore getStore() { return _store; } @@ -133,16 +136,49 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase public void testRemove() { - Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); + final Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); virtualHostAttributes.put(VirtualHost.NAME, getName()); virtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - UUID virtualHostId = UUID.randomUUID(); + final UUID virtualHostId = UUID.randomUUID(); addConfiguration(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes); assertNotNull("Virtual host with id " + virtualHostId + " should exist", _store.getEntry(virtualHostId)); - _store.remove(virtualHostId); - assertNull("Authentication provider configuration should be removed", _store.getEntry(virtualHostId)); + _store.remove(createConfiguredObjectRecord(virtualHostId, VirtualHost.class, virtualHostAttributes)); + assertNull("Virtual host configuration should be removed", _store.getEntry(virtualHostId)); + } + + protected ConfiguredObjectRecord createConfiguredObjectRecord(final UUID virtualHostId, + final Class<? extends ConfiguredObject> type, + final Map<String, Object> virtualHostAttributes) + { + return new ConfiguredObjectRecord() + { + @Override + public UUID getId() + { + return virtualHostId; + } + + @Override + public String getType() + { + return type.getSimpleName(); + } + + @Override + public Map<String, Object> getAttributes() + { + return virtualHostAttributes; + } + + @Override + public Map<String, ConfiguredObjectRecord> getParents() + { + // TODO RG : rectify this + return null; + } + }; } public void testRemoveMultipleEntries() @@ -162,7 +198,10 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase assertNotNull("Virtual host with id " + virtualHost1Id + " should exist", _store.getEntry(virtualHost1Id)); assertNotNull("Virtual host with id " + virtualHost2Id + " should exist", _store.getEntry(virtualHost2Id)); - UUID[] deletedIds = _store.remove(virtualHost1Id, virtualHost2Id); + UUID[] deletedIds = + _store.remove(createConfiguredObjectRecord(virtualHost1Id, VirtualHost.class, virtualHost1Attributes), + createConfiguredObjectRecord(virtualHost2Id, VirtualHost.class, virtualHost2Attributes)); + assertNotNull("Unexpected deleted ids", deletedIds); assertEquals("Unexpected id of first deleted virtual host", virtualHost1Id , deletedIds[0]); assertEquals("Unexpected id of second deleted virtual host", virtualHost2Id , deletedIds[1]); @@ -189,7 +228,8 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase attributes.put(Broker.CONNECTION_HEART_BEAT_DELAY, 12000); attributes.put(Broker.STATISTICS_REPORTING_PERIOD, 14000); attributes.put(Broker.STATISTICS_REPORTING_RESET_ENABLED, false); - ConfigurationEntry updatedBrokerEntry = new ConfigurationEntry(_brokerId, Broker.class.getSimpleName(), attributes, + ConfigurationEntry + updatedBrokerEntry = new ConfigurationEntryImpl(_brokerId, Broker.class.getSimpleName(), attributes, brokerConfigEntry.getChildrenIds(), _store); _store.save(updatedBrokerEntry); @@ -209,7 +249,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase virtualHostAttributes.put(VirtualHost.NAME, "test1"); virtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); UUID virtualHostId = UUID.randomUUID(); - ConfigurationEntry hostEntry = new ConfigurationEntry(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, + ConfigurationEntry hostEntry = new ConfigurationEntryImpl(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, Collections.<UUID> emptySet(), _store); _store.save(hostEntry); @@ -230,7 +270,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase virtualHostAttributes.put(VirtualHost.NAME, "test"); virtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - ConfigurationEntry updatedEntry = new ConfigurationEntry(_virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, + ConfigurationEntry updatedEntry = new ConfigurationEntryImpl(_virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, hostEntry.getChildrenIds(), _store); _store.save(updatedEntry); @@ -247,7 +287,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase Map<String, Object> authenticationProviderAttributes = new HashMap<String, Object>(); authenticationProviderAttributes.put(AuthenticationProvider.NAME, "authenticationProvider1"); authenticationProviderAttributes.put(AuthenticationProvider.TYPE, ExternalAuthenticationManager.class.getSimpleName()); - ConfigurationEntry providerEntry = new ConfigurationEntry(authenticationProviderId, AuthenticationProvider.class.getSimpleName(), + ConfigurationEntry providerEntry = new ConfigurationEntryImpl(authenticationProviderId, AuthenticationProvider.class.getSimpleName(), authenticationProviderAttributes, Collections.<UUID> emptySet(), _store); _store.save(providerEntry); @@ -267,7 +307,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase Map<String, Object> authenticationProviderAttributes = new HashMap<String, Object>(); authenticationProviderAttributes.put(AuthenticationProvider.NAME, "authenticationProvider1"); authenticationProviderAttributes.put(AuthenticationProvider.TYPE, ExternalAuthenticationManager.class.getSimpleName()); - ConfigurationEntry updatedEntry = new ConfigurationEntry(_authenticationProviderId, AuthenticationProvider.class.getSimpleName(), + ConfigurationEntry updatedEntry = new ConfigurationEntryImpl(_authenticationProviderId, AuthenticationProvider.class.getSimpleName(), authenticationProviderAttributes, Collections.<UUID> emptySet(), _store); _store.save(updatedEntry); @@ -289,7 +329,8 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase attributes.put(TrustStore.TRUST_MANAGER_FACTORY_ALGORITHM, "NON-STANDARD"); attributes.put(TrustStore.DESCRIPTION, "Description"); - ConfigurationEntry trustStoreEntry = new ConfigurationEntry(trustStoreId, TrustStore.class.getSimpleName(), attributes, + ConfigurationEntry + trustStoreEntry = new ConfigurationEntryImpl(trustStoreId, TrustStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), _store); _store.save(trustStoreEntry); @@ -313,7 +354,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase attributes.put(KeyStore.DESCRIPTION, "Description"); attributes.put(KeyStore.CERTIFICATE_ALIAS, "Alias"); - ConfigurationEntry keyStoreEntry = new ConfigurationEntry(keyStoreId, KeyStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), + ConfigurationEntry keyStoreEntry = new ConfigurationEntryImpl(keyStoreId, KeyStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), _store); _store.save(keyStoreEntry); @@ -331,7 +372,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(GroupProvider.NAME, getName()); - ConfigurationEntry groupProviderEntry = new ConfigurationEntry(groupProviderId, GroupProvider.class.getSimpleName(), attributes, + ConfigurationEntry groupProviderEntry = new ConfigurationEntryImpl(groupProviderId, GroupProvider.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), _store); _store.save(groupProviderEntry); @@ -356,7 +397,8 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase attributes.put(Port.NEED_CLIENT_AUTH, true); attributes.put(Port.WANT_CLIENT_AUTH, true); - ConfigurationEntry portEntry = new ConfigurationEntry(portId, Port.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), _store); + ConfigurationEntry portEntry = new ConfigurationEntryImpl(portId, Port.class.getSimpleName(), attributes, Collections + .<UUID> emptySet(), _store); _store.save(portEntry); @@ -373,7 +415,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); virtualHostAttributes.put(VirtualHost.NAME, "test1"); virtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - ConfigurationEntry hostEntry = new ConfigurationEntry(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, + ConfigurationEntry hostEntry = new ConfigurationEntryImpl(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, Collections.<UUID> emptySet(), _store); UUID keyStoreId = UUID.randomUUID(); @@ -386,7 +428,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase attributes.put(KeyStore.DESCRIPTION, "Description"); attributes.put(KeyStore.CERTIFICATE_ALIAS, "Alias"); - ConfigurationEntry keyStoreEntry = new ConfigurationEntry(keyStoreId, KeyStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), + ConfigurationEntry keyStoreEntry = new ConfigurationEntryImpl(keyStoreId, KeyStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), _store); _store.save(hostEntry, keyStoreEntry); @@ -418,7 +460,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase protected void addPreferencesProvider(UUID preferencesProviderId, String name, String path) { ConfigurationEntry authenticationProviderEntry = _store.getEntry(_authenticationProviderId); - ConfigurationEntry newAuthenticationProviderConfigEntry = new ConfigurationEntry(authenticationProviderEntry.getId(), + ConfigurationEntry newAuthenticationProviderConfigEntry = new ConfigurationEntryImpl(authenticationProviderEntry.getId(), authenticationProviderEntry.getType(), authenticationProviderEntry.getAttributes(), Collections.<UUID>singleton(preferencesProviderId), _store); @@ -427,7 +469,7 @@ public abstract class ConfigurationEntryStoreTestCase extends QpidTestCase preferencesProviderAttributes.put(FileSystemPreferencesProvider.PATH, path); preferencesProviderAttributes.put(PreferencesProvider.NAME, name); - ConfigurationEntry preferencesProviderEntry = new ConfigurationEntry(preferencesProviderId, PreferencesProvider.class.getSimpleName(), + ConfigurationEntry preferencesProviderEntry = new ConfigurationEntryImpl(preferencesProviderId, PreferencesProvider.class.getSimpleName(), preferencesProviderAttributes, Collections.<UUID> emptySet(), _store); _store.save(newAuthenticationProviderConfigEntry, preferencesProviderEntry); diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java index 2c59bfd453..c8003d909f 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java @@ -20,6 +20,9 @@ */ package org.apache.qpid.server.configuration.store; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import java.io.File; import java.io.IOException; import java.io.StringWriter; @@ -30,17 +33,26 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.codehaus.jackson.map.SerializationConfig; + +import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; +import org.apache.qpid.server.configuration.ConfigurationEntryImpl; import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.logging.EventLogger; +import org.apache.qpid.server.logging.LogRecorder; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObjectFactory; import org.apache.qpid.server.model.PreferencesProvider; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.server.model.adapter.FileSystemPreferencesProvider; +import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.test.utils.TestFileUtils; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; + public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTestCase { @@ -64,15 +76,41 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest } @Override - protected ConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception + protected JsonConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception { _storeFile = createStoreFile(brokerId, brokerAttributes); - JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(_storeFile.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); + return createStore(); + } + + private JsonConfigurationEntryStore createStore() + { + String absolutePath = _storeFile.getAbsolutePath(); + return createStore(absolutePath); + } + + private JsonConfigurationEntryStore createStore(final String absolutePath) + { + return createStore(absolutePath, null); + } + + private JsonConfigurationEntryStore createStore(final String absolutePath, + final DurableConfigurationStore initialStore) + { + final BrokerOptions brokerOptions = mock(BrokerOptions.class); + when(brokerOptions.getConfigurationStoreLocation()).thenReturn(absolutePath); + SystemContext context = new SystemContext(new TaskExecutor(), + new ConfiguredObjectFactory(), + mock(EventLogger.class), + mock(LogRecorder.class), + brokerOptions); + + JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(context, initialStore, false, + Collections.<String,String>emptyMap()); return store; } private File createStoreFile(UUID brokerId, Map<String, Object> brokerAttributes) throws IOException, - JsonGenerationException, JsonMappingException + JsonGenerationException, JsonMappingException { return createStoreFile(brokerId, brokerAttributes, true); } @@ -100,12 +138,12 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest @Override protected void addConfiguration(UUID id, String type, Map<String, Object> attributes, UUID parentId) { - ConfigurationEntryStore store = getStore(); + MemoryConfigurationEntryStore store = getStore(); ConfigurationEntry parentEntry = getStore().getEntry(parentId); Set<UUID> children = new HashSet<UUID>(parentEntry.getChildrenIds()); children.add(id); - ConfigurationEntry newParentEntry = new ConfigurationEntry(parentEntry.getId(), parentEntry.getType(), parentEntry.getAttributes(), children, store); - store.save(newParentEntry, new ConfigurationEntry(id, type, attributes, Collections.<UUID> emptySet(), store)); + ConfigurationEntry newParentEntry = new ConfigurationEntryImpl(parentEntry.getId(), parentEntry.getType(), parentEntry.getAttributes(), children, store); + store.save(newParentEntry, new ConfigurationEntryImpl(id, type, attributes, Collections.<UUID> emptySet(), store)); } public void testAttributeIsResolvedFromSystemProperties() @@ -113,15 +151,16 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest String defaultVhost = getTestName(); setTestSystemProperty("my.test.property", defaultVhost); - ConfigurationEntryStore store = getStore(); + MemoryConfigurationEntryStore store = getStore(); ConfigurationEntry brokerConfigEntry = store.getRootEntry(); Map<String, Object> attributes = new HashMap<String, Object>(brokerConfigEntry.getAttributes()); attributes.put(Broker.DEFAULT_VIRTUAL_HOST, "${my.test.property}"); - ConfigurationEntry updatedBrokerEntry = new ConfigurationEntry(brokerConfigEntry.getId(), Broker.class.getSimpleName(), + ConfigurationEntry + updatedBrokerEntry = new ConfigurationEntryImpl(brokerConfigEntry.getId(), Broker.class.getSimpleName(), attributes, brokerConfigEntry.getChildrenIds(), store); store.save(updatedBrokerEntry); - JsonConfigurationEntryStore store2 = new JsonConfigurationEntryStore(_storeFile.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); + JsonConfigurationEntryStore store2 = createStore(); assertEquals("Unresolved default virtualhost value", defaultVhost, store2.getRootEntry().getAttributes().get(Broker.DEFAULT_VIRTUAL_HOST)); } @@ -131,7 +170,7 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest File file = TestFileUtils.createTempFile(this, ".json"); try { - new JsonConfigurationEntryStore(file.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); + createStore(file.getAbsolutePath()); fail("Cannot create a new store without initial store"); } catch(IllegalConfigurationException e) @@ -147,7 +186,7 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest brokerAttributes.put(Broker.NAME, getTestName()); File file = createStoreFile(brokerId, brokerAttributes); - JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(file.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); + JsonConfigurationEntryStore store = createStore(file.getAbsolutePath()); ConfigurationEntry root = store.getRootEntry(); assertNotNull("Root entry is not found", root); assertEquals("Unexpected root entry", brokerId, root.getId()); @@ -164,10 +203,10 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest Map<String, Object> brokerAttributes = new HashMap<String, Object>(); File initialStoreFile = createStoreFile(brokerId, brokerAttributes); - JsonConfigurationEntryStore initialStore = new JsonConfigurationEntryStore(initialStoreFile.getAbsolutePath(), null, false, Collections.<String,String>emptyMap()); + JsonConfigurationEntryStore initialStore = createStore(initialStoreFile.getAbsolutePath()); File storeFile = TestFileUtils.createTempFile(this, ".json"); - JsonConfigurationEntryStore store = new JsonConfigurationEntryStore(storeFile.getAbsolutePath(), initialStore, false, Collections.<String,String>emptyMap()); + JsonConfigurationEntryStore store = createStore(storeFile.getAbsolutePath(), initialStore); ConfigurationEntry root = store.getRootEntry(); assertNotNull("Root entry is not found", root); @@ -201,7 +240,7 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest try { storeFile = createStoreFile(brokerId, brokerAttributes); - new JsonConfigurationEntryStore(storeFile.getAbsolutePath(), null, false, Collections.<String, String>emptyMap()); + createStore(storeFile.getAbsolutePath()); fail("The store creation should fail due to unsupported store version"); } catch (IllegalConfigurationException e) @@ -227,7 +266,7 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest try { storeFile = createStoreFile(brokerId, brokerAttributes, false); - new JsonConfigurationEntryStore(storeFile.getAbsolutePath(), null, false, Collections.<String, String>emptyMap()); + createStore(storeFile.getAbsolutePath()); fail("The store creation should fail due to unspecified store version"); } catch (IllegalConfigurationException e) @@ -252,7 +291,7 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest addPreferencesProvider(preferencesProviderId, name, path); // verify that store can deserialise child of a child - JsonConfigurationEntryStore newStore = new JsonConfigurationEntryStore(_storeFile.getAbsolutePath(), null, false, Collections.<String, String>emptyMap()); + JsonConfigurationEntryStore newStore = createStore(); ConfigurationEntry authenticationProviderEntry = newStore.getEntry(_authenticationProviderId); assertEquals("Unexpected preference provider ID in authentication provider children set", preferencesProviderId, authenticationProviderEntry.getChildrenIds().iterator().next()); @@ -265,4 +304,5 @@ public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTest assertEquals("Unexpected preferences provider type", FileSystemPreferencesProvider.PROVIDER_TYPE, attributes.get(PreferencesProvider.TYPE)); } + } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java index bcdfce1d0a..1de857d224 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java @@ -20,12 +20,13 @@ */ package org.apache.qpid.server.configuration.store; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.any; +import static org.mockito.Mockito.when; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -33,59 +34,119 @@ import java.util.HashSet; import java.util.Map; import java.util.UUID; +import org.mockito.ArgumentCaptor; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.logging.EventLogger; +import org.apache.qpid.server.logging.LogRecorder; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObjectFactory; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.State; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.server.model.VirtualHost; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.ConfiguredObjectRecordImpl; +import org.apache.qpid.server.store.DurableConfigurationStore; +import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; import org.apache.qpid.test.utils.QpidTestCase; public class ManagementModeStoreHandlerTest extends QpidTestCase { private ManagementModeStoreHandler _handler; private BrokerOptions _options; - private ConfigurationEntryStore _store; - private ConfigurationEntry _root; - private ConfigurationEntry _portEntry; + private DurableConfigurationStore _store; + private ConfiguredObjectRecord _root; + private ConfiguredObjectRecord _portEntry; private UUID _rootId, _portEntryId; + private SystemContext _systemContext; protected void setUp() throws Exception { super.setUp(); _rootId = UUID.randomUUID(); _portEntryId = UUID.randomUUID(); - _store = mock(ConfigurationEntryStore.class); - _root = mock(ConfigurationEntry.class); - _portEntry = mock(ConfigurationEntry.class); - when(_store.getRootEntry()).thenReturn(_root); - when(_root.getId()).thenReturn(_rootId); + _store = mock(DurableConfigurationStore.class); + + + _systemContext = new SystemContext(new TaskExecutor(), new ConfiguredObjectFactory(), mock( + EventLogger.class), mock(LogRecorder.class), new BrokerOptions()); + + + ConfiguredObjectRecord systemContextRecord = _systemContext.asObjectRecord(); + + + + _root = new ConfiguredObjectRecordImpl(_rootId, Broker.class.getSimpleName(), Collections.<String,Object>emptyMap(), Collections.singletonMap(SystemContext.class.getSimpleName(), systemContextRecord)); + + _portEntry = mock(ConfiguredObjectRecord.class); when(_portEntry.getId()).thenReturn(_portEntryId); - when(_store.getEntry(_portEntryId)).thenReturn(_portEntry); - when(_store.getEntry(_rootId)).thenReturn(_root); - when(_root.getChildrenIds()).thenReturn(Collections.singleton(_portEntryId)); + when(_portEntry.getParents()).thenReturn(Collections.singletonMap(Broker.class.getSimpleName(), _root)); when(_portEntry.getType()).thenReturn(Port.class.getSimpleName()); + + final ArgumentCaptor<ConfiguredObjectRecordHandler> recovererArgumentCaptor = ArgumentCaptor.forClass(ConfiguredObjectRecordHandler.class); + doAnswer( + new Answer() + { + @Override + public Object answer(final InvocationOnMock invocation) throws Throwable + { + ConfiguredObjectRecordHandler recoverer = recovererArgumentCaptor.getValue(); + if(recoverer.handle(_root)) + { + recoverer.handle(_portEntry); + } + return null; + } + } + ).when(_store).visitConfiguredObjectRecords(recovererArgumentCaptor.capture()); _options = new BrokerOptions(); _handler = new ManagementModeStoreHandler(_store, _options); + + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + } + + private ConfiguredObjectRecord getRootEntry() + { + BrokerFinder brokerFinder = new BrokerFinder(); + _handler.visitConfiguredObjectRecords(brokerFinder); + return brokerFinder.getBrokerRecord(); + } + + private ConfiguredObjectRecord getEntry(UUID id) + { + RecordFinder recordFinder = new RecordFinder(id); + _handler.visitConfiguredObjectRecords(recordFinder); + return recordFinder.getFoundRecord(); + } + + private Collection<UUID> getChildrenIds(ConfiguredObjectRecord record) + { + ChildFinder childFinder = new ChildFinder(record); + _handler.visitConfiguredObjectRecords(childFinder); + return childFinder.getChildIds(); } public void testGetRootEntryWithEmptyOptions() { - ConfigurationEntry root = _handler.getRootEntry(); + ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); - assertEquals("Unexpected children", Collections.singleton(_portEntryId), root.getChildrenIds()); + assertEquals("Unexpected children", Collections.singleton(_portEntryId), getChildrenIds(root)); } public void testGetRootEntryWithHttpPortOverriden() { _options.setManagementModeHttpPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - ConfigurationEntry root = _handler.getRootEntry(); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); + Collection<UUID> childrenIds = getChildrenIds(root); assertEquals("Unexpected children size", 2, childrenIds.size()); assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); } @@ -94,9 +155,11 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeRmiPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - ConfigurationEntry root = _handler.getRootEntry(); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + + ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); + Collection<UUID> childrenIds = getChildrenIds(root); assertEquals("Unexpected children size", 3, childrenIds.size()); assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); } @@ -105,9 +168,11 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeJmxPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - ConfigurationEntry root = _handler.getRootEntry(); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + + ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); + Collection<UUID> childrenIds = getChildrenIds(root); assertEquals("Unexpected children size", 2, childrenIds.size()); assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); } @@ -118,25 +183,27 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase _options.setManagementModeRmiPortOverride(2000); _options.setManagementModeJmxPortOverride(3000); _handler = new ManagementModeStoreHandler(_store, _options); - ConfigurationEntry root = _handler.getRootEntry(); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + + ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); + Collection<UUID> childrenIds = getChildrenIds(root); assertEquals("Unexpected children size", 4, childrenIds.size()); assertTrue("Store port entry id is not found", childrenIds.contains(_portEntryId)); } public void testGetEntryByRootId() { - ConfigurationEntry root = _handler.getEntry(_rootId); + ConfiguredObjectRecord root = getEntry(_rootId); assertEquals("Unexpected root id", _rootId, root.getId()); - assertEquals("Unexpected children", Collections.singleton(_portEntryId), root.getChildrenIds()); + assertEquals("Unexpected children", Collections.singleton(_portEntryId), getChildrenIds(root)); } public void testGetEntryByPortId() { - ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); + ConfiguredObjectRecord portEntry = getEntry(_portEntryId); assertEquals("Unexpected entry id", _portEntryId, portEntry.getId()); - assertTrue("Unexpected children", portEntry.getChildrenIds().isEmpty()); + assertTrue("Unexpected children", getChildrenIds(portEntry).isEmpty()); assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); } @@ -144,9 +211,11 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeJmxPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + UUID optionsPort = getOptionsPortId(); - ConfigurationEntry portEntry = _handler.getEntry(optionsPort); + ConfiguredObjectRecord portEntry = getEntry(optionsPort); assertCLIPortEntry(portEntry, optionsPort, Protocol.JMX_RMI); } @@ -154,9 +223,11 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeHttpPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + UUID optionsPort = getOptionsPortId(); - ConfigurationEntry portEntry = _handler.getEntry(optionsPort); + ConfiguredObjectRecord portEntry = getEntry(optionsPort); assertCLIPortEntry(portEntry, optionsPort, Protocol.HTTP); } @@ -167,8 +238,10 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase when(_portEntry.getAttributes()).thenReturn(attributes); _options.setManagementModeHttpPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + - ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); + ConfiguredObjectRecord portEntry = getEntry(_portEntryId); assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); } @@ -179,8 +252,10 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase when(_portEntry.getAttributes()).thenReturn(attributes); _options.setManagementModeRmiPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); - ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); + + ConfiguredObjectRecord portEntry = getEntry(_portEntryId); assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); } @@ -191,8 +266,10 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase when(_portEntry.getAttributes()).thenReturn(attributes); _options.setManagementModeRmiPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + - ConfigurationEntry portEntry = _handler.getEntry(_portEntryId); + ConfiguredObjectRecord portEntry = getEntry(_portEntryId); assertEquals("Unexpected state", State.QUIESCED, portEntry.getAttributes().get(Port.STATE)); } @@ -209,14 +286,29 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase private void virtualHostEntryQuiescedStatusTestImpl(boolean mmQuiesceVhosts) { UUID virtualHostId = UUID.randomUUID(); - ConfigurationEntry virtualHost = mock(ConfigurationEntry.class); - when(virtualHost.getId()).thenReturn(virtualHostId); - when(virtualHost.getType()).thenReturn(VirtualHost.class.getSimpleName()); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(VirtualHost.TYPE, "STANDARD"); - when(virtualHost.getAttributes()).thenReturn(attributes); - when(_store.getEntry(virtualHostId)).thenReturn(virtualHost); - when(_root.getChildrenIds()).thenReturn(new HashSet<UUID>(Arrays.asList(_portEntryId, virtualHostId))); + + final ConfiguredObjectRecord virtualHost = new ConfiguredObjectRecordImpl(virtualHostId, VirtualHost.class.getSimpleName(), attributes, Collections.singletonMap(Broker.class.getSimpleName(), _root)); + final ArgumentCaptor<ConfiguredObjectRecordHandler> recovererArgumentCaptor = ArgumentCaptor.forClass(ConfiguredObjectRecordHandler.class); + doAnswer( + new Answer() + { + @Override + public Object answer(final InvocationOnMock invocation) throws Throwable + { + ConfiguredObjectRecordHandler recoverer = recovererArgumentCaptor.getValue(); + if(recoverer.handle(_root)) + { + if(recoverer.handle(_portEntry)) + { + recoverer.handle(virtualHost); + } + } + return null; + } + } + ).when(_store).visitConfiguredObjectRecords(recovererArgumentCaptor.capture()); State expectedState = mmQuiesceVhosts ? State.QUIESCED : null; if(mmQuiesceVhosts) @@ -225,19 +317,20 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase } _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); - ConfigurationEntry hostEntry = _handler.getEntry(virtualHostId); - Map<String, Object> hostAttributes = hostEntry.getAttributes(); + ConfiguredObjectRecord hostEntry = getEntry(virtualHostId); + Map<String, Object> hostAttributes = new HashMap<String, Object>(hostEntry.getAttributes()); assertEquals("Unexpected state", expectedState, hostAttributes.get(VirtualHost.STATE)); hostAttributes.remove(VirtualHost.STATE); assertEquals("Unexpected attributes", attributes, hostAttributes); } @SuppressWarnings("unchecked") - private void assertCLIPortEntry(ConfigurationEntry portEntry, UUID optionsPort, Protocol protocol) + private void assertCLIPortEntry(ConfiguredObjectRecord portEntry, UUID optionsPort, Protocol protocol) { assertEquals("Unexpected entry id", optionsPort, portEntry.getId()); - assertTrue("Unexpected children", portEntry.getChildrenIds().isEmpty()); + assertTrue("Unexpected children", getChildrenIds(portEntry).isEmpty()); Map<String, Object> attributes = portEntry.getAttributes(); assertEquals("Unexpected name", "MANAGEMENT-MODE-PORT-" + protocol.name(), attributes.get(Port.NAME)); assertEquals("Unexpected protocol", Collections.singleton(protocol), new HashSet<Protocol>( @@ -250,13 +343,15 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase _options.setManagementModeRmiPortOverride(2000); _options.setManagementModeJmxPortOverride(3000); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, "TEST"); - ConfigurationEntry configurationEntry = new ConfigurationEntry(_portEntryId, Port.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), null); - _handler.save(configurationEntry); - verify(_store).save(any(ConfigurationEntry.class)); + ConfiguredObjectRecord + configurationEntry = new ConfiguredObjectRecordImpl(_portEntryId, Port.class.getSimpleName(), attributes, + Collections.singletonMap(Broker.class.getSimpleName(), getRootEntry())); + _handler.create(configurationEntry); + verify(_store).create(any(ConfiguredObjectRecord.class)); } public void testSaveRoot() @@ -265,29 +360,33 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase _options.setManagementModeRmiPortOverride(2000); _options.setManagementModeJmxPortOverride(3000); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); - ConfigurationEntry root = _handler.getRootEntry(); + ConfiguredObjectRecord root = getRootEntry(); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Broker.NAME, "TEST"); - ConfigurationEntry configurationEntry = new ConfigurationEntry(_rootId, Broker.class.getSimpleName(), attributes, - root.getChildrenIds(), null); - _handler.save(configurationEntry); - verify(_store).save(any(ConfigurationEntry.class)); + ConfiguredObjectRecord + configurationEntry = new ConfiguredObjectRecordImpl(_rootId, Broker.class.getSimpleName(), attributes,root.getParents()); + _handler.update(false, configurationEntry); + verify(_store).update(anyBoolean(), any(ConfiguredObjectRecord.class)); } public void testSaveCLIHttpPort() { _options.setManagementModeHttpPortOverride(1000); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); UUID portId = getOptionsPortId(); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, "TEST"); - ConfigurationEntry configurationEntry = new ConfigurationEntry(portId, Port.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), null); + ConfiguredObjectRecord + configurationEntry = new ConfiguredObjectRecordImpl(portId, Port.class.getSimpleName(), attributes, + Collections.singletonMap(Broker.class.getSimpleName(), + getRootEntry())); try { - _handler.save(configurationEntry); + _handler.update(false, configurationEntry); fail("Exception should be thrown on trying to save CLI port"); } catch (IllegalConfigurationException e) @@ -300,19 +399,50 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeHttpPortOverride(1000); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); - _handler.remove(_portEntryId); - verify(_store).remove(_portEntryId); + ConfiguredObjectRecord record = new ConfiguredObjectRecord() + { + @Override + public UUID getId() + { + return _portEntryId; + } + + @Override + public String getType() + { + return Port.class.getSimpleName(); + } + + @Override + public Map<String, Object> getAttributes() + { + return Collections.emptyMap(); + } + + @Override + public Map<String, ConfiguredObjectRecord> getParents() + { + return null; + } + }; + _handler.remove(record); + verify(_store).remove(record); } public void testRemoveCLIPort() { _options.setManagementModeHttpPortOverride(1000); _handler = new ManagementModeStoreHandler(_store, _options); + _handler.openConfigurationStore(_systemContext,Collections.<String,Object>emptyMap()); + UUID portId = getOptionsPortId(); + ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class); + when(record.getId()).thenReturn(portId); try { - _handler.remove(portId); + _handler.remove(record); fail("Exception should be thrown on trying to remove CLI port"); } catch (IllegalConfigurationException e) @@ -323,13 +453,134 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase private UUID getOptionsPortId() { - ConfigurationEntry root = _handler.getRootEntry(); + ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); - Collection<UUID> childrenIds = root.getChildrenIds(); + Collection<UUID> childrenIds = getChildrenIds(root); childrenIds.remove(_portEntryId); UUID optionsPort = childrenIds.iterator().next(); return optionsPort; } + + private class BrokerFinder implements ConfiguredObjectRecordHandler + { + private ConfiguredObjectRecord _brokerRecord; + private int _version; + + @Override + public void begin(final int configVersion) + { + _version = configVersion; + } + + @Override + public boolean handle(final ConfiguredObjectRecord object) + { + if(object.getType().equals(Broker.class.getSimpleName())) + { + _brokerRecord = object; + return false; + } + return true; + } + + @Override + public int end() + { + return _version; + } + + public ConfiguredObjectRecord getBrokerRecord() + { + return _brokerRecord; + } + } + + private class RecordFinder implements ConfiguredObjectRecordHandler + { + private final UUID _id; + private ConfiguredObjectRecord _foundRecord; + private int _version; + + private RecordFinder(final UUID id) + { + _id = id; + } + + @Override + public void begin(final int configVersion) + { + _version = configVersion; + } + + @Override + public boolean handle(final ConfiguredObjectRecord object) + { + if(object.getId().equals(_id)) + { + _foundRecord = object; + return false; + } + return true; + } + + @Override + public int end() + { + return _version; + } + + public ConfiguredObjectRecord getFoundRecord() + { + return _foundRecord; + } + } + + private class ChildFinder implements ConfiguredObjectRecordHandler + { + private final Collection<UUID> _childIds = new HashSet<UUID>(); + private final ConfiguredObjectRecord _parent; + private int _version; + + private ChildFinder(final ConfiguredObjectRecord parent) + { + _parent = parent; + } + + @Override + public void begin(final int configVersion) + { + _version = configVersion; + } + + @Override + public boolean handle(final ConfiguredObjectRecord object) + { + + if(object.getParents() != null) + { + for(ConfiguredObjectRecord parent : object.getParents().values()) + { + if(parent.getId().equals(_parent.getId())) + { + _childIds.add(object.getId()); + } + } + + } + return true; + } + + @Override + public int end() + { + return _version; + } + + public Collection<UUID> getChildIds() + { + return _childIds; + } + } } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java index 508cd2b321..86098729d5 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java @@ -20,6 +20,8 @@ */ package org.apache.qpid.server.configuration.store; +import static org.mockito.Mockito.mock; + import java.io.File; import java.util.Collections; import java.util.HashMap; @@ -28,18 +30,35 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import org.codehaus.jackson.map.ObjectMapper; + import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; +import org.apache.qpid.server.configuration.ConfigurationEntryImpl; import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.logging.EventLogger; +import org.apache.qpid.server.logging.LogRecorder; import org.apache.qpid.server.model.Broker; -import org.codehaus.jackson.map.ObjectMapper; +import org.apache.qpid.server.model.ConfiguredObjectFactory; +import org.apache.qpid.server.model.SystemContext; public class MemoryConfigurationEntryStoreTest extends ConfigurationEntryStoreTestCase { + private SystemContext _systemContext; + + @Override + public void setUp() throws Exception + { + super.setUp(); + _systemContext = new SystemContext(new TaskExecutor(), new ConfiguredObjectFactory(), + mock(EventLogger.class), mock(LogRecorder.class), + new BrokerOptions()); + + } @Override - protected ConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception + protected MemoryConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception { Map<String, Object> broker = new HashMap<String, Object>(); broker.put(Broker.ID, brokerId); @@ -52,19 +71,19 @@ public class MemoryConfigurationEntryStoreTest extends ConfigurationEntryStoreTe @Override protected void addConfiguration(UUID id, String type, Map<String, Object> attributes, UUID parentId) { - ConfigurationEntryStore store = getStore(); + MemoryConfigurationEntryStore store = getStore(); ConfigurationEntry parentEntry = getStore().getEntry(parentId); Set<UUID> children = new HashSet<UUID>(parentEntry.getChildrenIds()); children.add(id); - ConfigurationEntry newParentEntry = new ConfigurationEntry(parentEntry.getId(), parentEntry.getType(), parentEntry.getAttributes(), children, store); - store.save(newParentEntry, new ConfigurationEntry(id, type, attributes, Collections.<UUID> emptySet(), store)); + ConfigurationEntry newParentEntry = new ConfigurationEntryImpl(parentEntry.getId(), parentEntry.getType(), parentEntry.getAttributes(), children, store); + store.save(newParentEntry, new ConfigurationEntryImpl(id, type, attributes, Collections.<UUID> emptySet(), store)); } public void testCreateWithNullLocationAndNullInitialStore() { try { - new MemoryConfigurationEntryStore(null, null, Collections.<String,String>emptyMap()); + new MemoryConfigurationEntryStore(null, null, null, Collections.<String,String>emptyMap()); fail("Cannot create a memory store without either initial store or path to an initial store file"); } catch(IllegalConfigurationException e) @@ -86,8 +105,8 @@ public class MemoryConfigurationEntryStoreTest extends ConfigurationEntryStoreTe UUID brokerId = UUID.randomUUID(); Map<String, Object> brokerAttributes = new HashMap<String, Object>(); brokerAttributes.put(Broker.NAME, getTestName()); - MemoryConfigurationEntryStore initialStoreFile = (MemoryConfigurationEntryStore)createStore(brokerId, brokerAttributes); - MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(null, initialStoreFile, Collections.<String,String>emptyMap()); + MemoryConfigurationEntryStore initialStoreFile = createStore(brokerId, brokerAttributes); + MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(_systemContext, null, initialStoreFile, Collections.<String,String>emptyMap()); ConfigurationEntry root = store.getRootEntry(); assertNotNull("Root entry is not found", root); @@ -108,11 +127,11 @@ public class MemoryConfigurationEntryStoreTest extends ConfigurationEntryStoreTe setTestSystemProperty("QPID_HOME", TMP_FOLDER); setTestSystemProperty("QPID_WORK", TMP_FOLDER + File.separator + "work"); } - MemoryConfigurationEntryStore initialStore = new MemoryConfigurationEntryStore(BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, null, new BrokerOptions().getConfigProperties()); + MemoryConfigurationEntryStore initialStore = new MemoryConfigurationEntryStore(_systemContext,BrokerOptions.DEFAULT_INITIAL_CONFIG_LOCATION, null, new BrokerOptions().getConfigProperties()); ConfigurationEntry initialStoreRoot = initialStore.getRootEntry(); assertNotNull("Initial store root entry is not found", initialStoreRoot); - MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(null, initialStore, Collections.<String,String>emptyMap()); + MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(_systemContext, null, initialStore, Collections.<String,String>emptyMap()); ConfigurationEntry root = store.getRootEntry(); assertNotNull("Root entry is not found", root); @@ -130,4 +149,5 @@ public class MemoryConfigurationEntryStoreTest extends ConfigurationEntryStoreTe { assertEquals("Unexpected type", "memory", getStore().getType()); } + } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java index c5786fb981..925cdecf81 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java @@ -20,6 +20,7 @@ */ package org.apache.qpid.server.configuration.store; +import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verify; @@ -28,13 +29,13 @@ import static org.mockito.Mockito.when; import java.util.UUID; -import org.apache.qpid.server.configuration.ConfigurationEntry; import org.apache.qpid.server.configuration.ConfigurationEntryStore; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.Queue; import org.apache.qpid.server.model.State; import org.apache.qpid.server.model.VirtualHost; +import org.apache.qpid.server.store.ConfiguredObjectRecord; import org.apache.qpid.test.utils.QpidTestCase; public class StoreConfigurationChangeListenerTest extends QpidTestCase @@ -55,8 +56,10 @@ public class StoreConfigurationChangeListenerTest extends QpidTestCase UUID id = UUID.randomUUID(); ConfiguredObject object = mock(VirtualHost.class); when(object.getId()).thenReturn(id); + ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class); + when(object.asObjectRecord()).thenReturn(record); _listener.stateChanged(object, State.ACTIVE, State.DELETED); - verify(_store).remove(id); + verify(_store).remove(record); } public void testChildAdded() @@ -67,18 +70,7 @@ public class StoreConfigurationChangeListenerTest extends QpidTestCase VirtualHost child = mock(VirtualHost.class); when(child.getCategoryClass()).thenReturn(VirtualHost.class); _listener.childAdded(broker, child); - verify(_store).save(any(ConfigurationEntry.class), any(ConfigurationEntry.class)); - } - - public void testChildRemoved() - { - notifyBrokerStarted(); - Broker broker = mock(Broker.class); - when(broker.getCategoryClass()).thenReturn(Broker.class); - VirtualHost child = mock(VirtualHost.class); - when(child.getCategoryClass()).thenReturn(VirtualHost.class); - _listener.childRemoved(broker, child); - verify(_store).save(any(ConfigurationEntry.class)); + verify(_store).update(eq(true), any(ConfiguredObjectRecord.class)); } public void testAttributeSet() @@ -87,7 +79,7 @@ public class StoreConfigurationChangeListenerTest extends QpidTestCase Broker broker = mock(Broker.class); when(broker.getCategoryClass()).thenReturn(Broker.class); _listener.attributeSet(broker, Broker.QUEUE_FLOW_CONTROL_SIZE_BYTES, null, 1); - verify(_store).save(any(ConfigurationEntry.class)); + verify(_store).update(eq(false),any(ConfiguredObjectRecord.class)); } public void testChildAddedForVirtualHost() diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/ConfiguredObjectStateTransitionTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/ConfiguredObjectStateTransitionTest.java deleted file mode 100644 index a6d4f57996..0000000000 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/ConfiguredObjectStateTransitionTest.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.model; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.ConfiguredObjectRecoverer; -import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.startup.DefaultRecovererProvider; -import org.apache.qpid.server.configuration.store.StoreConfigurationChangeListener; -import org.apache.qpid.server.configuration.updater.TaskExecutor; -import org.apache.qpid.server.security.auth.manager.AnonymousAuthenticationManagerFactory; -import org.apache.qpid.server.security.group.FileGroupManagerFactory; -import org.apache.qpid.server.stats.StatisticsGatherer; -import org.apache.qpid.server.util.BrokerTestHelper; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ConfiguredObjectStateTransitionTest extends QpidTestCase -{ - private Broker _broker; - private RecovererProvider _recovererProvider; - private ConfigurationEntryStore _store; - private File _resourceToDelete; - - @Override - public void setUp() throws Exception - { - super.setUp(); - BrokerTestHelper.setUp(); - - _broker = BrokerTestHelper.createBrokerMock(); - StatisticsGatherer statisticsGatherer = mock(StatisticsGatherer.class); - TaskExecutor executor = mock(TaskExecutor.class); - when(executor.isTaskExecutorThread()).thenReturn(true); - when(_broker.getTaskExecutor()).thenReturn(executor); - - _recovererProvider = new DefaultRecovererProvider(statisticsGatherer, _broker.getVirtualHostRegistry(), - _broker.getLogRecorder(), executor, new BrokerOptions(), mock(StoreConfigurationChangeListener.class)); - - _store = mock(ConfigurationEntryStore.class); - - _resourceToDelete = new File(TMP_FOLDER, getTestName()); - } - - @Override - public void tearDown() throws Exception - { - try - { - BrokerTestHelper.tearDown(); - if (_resourceToDelete.exists()) - { - _resourceToDelete.delete(); - } - } - finally - { - super.tearDown(); - } - } - - public void testGroupProviderValidStateTransitions() throws Exception - { - ConfigurationEntry providerEntry = getGroupProviderConfigurationEntry(); - ConfiguredObject provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertValidStateTransition(provider, State.QUIESCED, State.STOPPED); - - provider = createConfiguredObject(providerEntry); - assertValidStateTransition(provider, State.INITIALISING, State.DELETED); - - providerEntry = getGroupProviderConfigurationEntry(); - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertValidStateTransition(provider, State.QUIESCED, State.DELETED); - - providerEntry = getGroupProviderConfigurationEntry(); - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.ACTIVE); - assertValidStateTransition(provider, State.ACTIVE, State.DELETED); - } - - public void testGroupProviderInvalidStateTransitions() throws Exception - { - ConfigurationEntry providerEntry = getGroupProviderConfigurationEntry(); - assertAllInvalidStateTransitions(providerEntry); - } - - public void testAuthenticationProviderValidStateTransitions() - { - ConfigurationEntry providerEntry = getAuthenticationProviderConfigurationEntry(); - assertAllValidStateTransitions(providerEntry); - } - - public void testAuthenticationProviderInvalidStateTransitions() - { - ConfigurationEntry providerEntry = getAuthenticationProviderConfigurationEntry(); - assertAllInvalidStateTransitions(providerEntry); - } - - public void testPortValidStateTransitions() - { - ConfigurationEntry providerEntry = getPortConfigurationEntry(); - assertAllValidStateTransitions(providerEntry); - } - - public void testPortInvalidStateTransitions() - { - ConfigurationEntry providerEntry = getPortConfigurationEntry(); - assertAllInvalidStateTransitions(providerEntry); - } - - private void assertAllInvalidStateTransitions(ConfigurationEntry providerEntry) - { - ConfiguredObject provider = createConfiguredObject(providerEntry); - assertInvalidStateTransition(provider, State.INITIALISING, State.REPLICA); - - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertInvalidStateTransition(provider, State.QUIESCED, State.INITIALISING); - - provider.setDesiredState(State.QUIESCED, State.ACTIVE); - assertInvalidStateTransition(provider, State.ACTIVE, State.INITIALISING); - - provider.setDesiredState(State.ACTIVE, State.DELETED); - assertInvalidStateTransition(provider, State.DELETED, State.INITIALISING); - assertInvalidStateTransition(provider, State.DELETED, State.QUIESCED); - assertInvalidStateTransition(provider, State.DELETED, State.ACTIVE); - assertInvalidStateTransition(provider, State.DELETED, State.REPLICA); - assertInvalidStateTransition(provider, State.DELETED, State.ERRORED); - } - - private void assertAllValidStateTransitions(ConfigurationEntry providerEntry) - { - ConfiguredObject provider = createConfiguredObject(providerEntry); - assertNormalStateTransition(provider); - - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertValidStateTransition(provider, State.QUIESCED, State.STOPPED); - - provider = createConfiguredObject(providerEntry); - assertValidStateTransition(provider, State.INITIALISING, State.DELETED); - - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.QUIESCED); - assertValidStateTransition(provider, State.QUIESCED, State.DELETED); - - provider = createConfiguredObject(providerEntry); - provider.setDesiredState(State.INITIALISING, State.ACTIVE); - assertValidStateTransition(provider, State.ACTIVE, State.DELETED); - } - - private void assertInvalidStateTransition(ConfiguredObject object, State initialState, State... invalidStates) - { - assertEquals("Unexpected state", initialState, object.getState()); - for (State state : invalidStates) - { - try - { - object.setDesiredState(initialState, state); - } - catch (IllegalStateException e) - { - // expected - } - assertEquals("Transition from state " + initialState + " into state " + state + " did occur", initialState, - object.getState()); - } - } - - private void assertValidStateTransition(ConfiguredObject object, State initialState, State... validStateSequence) - { - assertEquals("Unexpected state", initialState, object.getState()); - State currentState = initialState; - for (State state : validStateSequence) - { - object.setDesiredState(currentState, state); - assertEquals("Transition from state " + currentState + " into state " + state + " did not occur", state, - object.getState()); - currentState = state; - } - } - - private void assertNormalStateTransition(ConfiguredObject object) - { - assertValidStateTransition(object, State.INITIALISING, State.QUIESCED, State.ACTIVE, State.STOPPED, State.DELETED); - } - - private ConfiguredObject createConfiguredObject(ConfigurationEntry entry) - { - @SuppressWarnings("unchecked") - ConfiguredObjectRecoverer<ConfiguredObject> recoverer = - (ConfiguredObjectRecoverer<ConfiguredObject>)_recovererProvider.getRecoverer(entry.getType()); - return recoverer.create(_recovererProvider, entry, _broker); - } - - private ConfigurationEntry createConfigurationEntry(String type, Map<String, Object> attributes, ConfigurationEntryStore store) - { - return new ConfigurationEntry(UUID.randomUUID(), type, attributes, Collections.<UUID>emptySet(), store); - } - - private ConfigurationEntry getAuthenticationProviderConfigurationEntry() - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(AuthenticationProvider.NAME, getTestName()); - attributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManagerFactory.PROVIDER_TYPE); - return createConfigurationEntry(AuthenticationProvider.class.getSimpleName(), attributes , _store); - } - - private ConfigurationEntry getGroupProviderConfigurationEntry() throws Exception - { - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(GroupProvider.NAME, getTestName()); - attributes.put(GroupProvider.TYPE, FileGroupManagerFactory.GROUP_FILE_PROVIDER_TYPE); - attributes.put(FileGroupManagerFactory.PATH, _resourceToDelete.getAbsolutePath()); - if (!_resourceToDelete.exists()) - { - _resourceToDelete.createNewFile(); - } - return createConfigurationEntry(GroupProvider.class.getSimpleName(), attributes , _store); - } - - private ConfigurationEntry getPortConfigurationEntry() - { - ConfigurationEntry authProviderEntry = getAuthenticationProviderConfigurationEntry(); - AuthenticationProvider authProvider = (AuthenticationProvider)createConfiguredObject(authProviderEntry); - - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Port.NAME, getTestName()); - attributes.put(Port.PROTOCOLS, Collections.<Protocol>singleton(Protocol.HTTP)); - attributes.put(Port.AUTHENTICATION_PROVIDER, authProvider.getName()); - attributes.put(Port.PORT, 0); - - when(_broker.findAuthenticationProviderByName(authProvider.getName())).thenReturn(authProvider); - return createConfigurationEntry(Port.class.getSimpleName(), attributes , _store); - } - -} diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/VirtualHostTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/VirtualHostTest.java index 266049e611..53cbf5b32a 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/VirtualHostTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/VirtualHostTest.java @@ -20,18 +20,9 @@ */ package org.apache.qpid.server.model; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.apache.qpid.server.configuration.ConfigurationEntry; import org.apache.qpid.server.configuration.RecovererProvider; -import org.apache.qpid.server.configuration.startup.VirtualHostRecoverer; import org.apache.qpid.server.configuration.updater.TaskExecutor; +import org.apache.qpid.server.model.adapter.StandardVirtualHostAdapter; import org.apache.qpid.server.stats.StatisticsGatherer; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.store.TestMemoryMessageStore; @@ -39,6 +30,14 @@ import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.server.virtualhost.StandardVirtualHostFactory; import org.apache.qpid.test.utils.QpidTestCase; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + public class VirtualHostTest extends QpidTestCase { @@ -158,10 +157,7 @@ public class VirtualHostTest extends QpidTestCase private VirtualHost createHost(Map<String, Object> attributes) { - ConfigurationEntry entry = new ConfigurationEntry(UUID.randomUUID(), VirtualHost.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), null); - - return new VirtualHostRecoverer(_statisticsGatherer).create(_recovererProvider, entry, _broker); + return new StandardVirtualHostAdapter(UUID.randomUUID(), attributes, _broker); } } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactoryTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactoryTest.java index 64dfad94c3..27ad46dcfc 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactoryTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderFactoryTest.java @@ -32,6 +32,7 @@ import java.util.UUID; import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.PreferencesProvider; import org.apache.qpid.server.util.BrokerTestHelper; import org.apache.qpid.test.utils.QpidTestCase; @@ -80,7 +81,8 @@ public class FileSystemPreferencesProviderFactoryTest extends QpidTestCase try { attributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - PreferencesProvider provider = _factory.createInstance(id, attributes, _authenticationProvider); + attributes.put(ConfiguredObject.ID, id); + PreferencesProvider provider = _factory.create(attributes, _authenticationProvider); assertNotNull("Preferences provider was not instantiated", provider); assertEquals("Unexpected name", "test-provider", provider.getName()); assertEquals("Unexpected id", id, provider.getId()); @@ -104,7 +106,8 @@ public class FileSystemPreferencesProviderFactoryTest extends QpidTestCase try { attributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - _factory.createInstance(id, attributes, _authenticationProvider); + attributes.put(ConfiguredObject.ID, id); + _factory.create(attributes, _authenticationProvider); } catch (IllegalConfigurationException e) { @@ -123,7 +126,8 @@ public class FileSystemPreferencesProviderFactoryTest extends QpidTestCase try { attributes.put(FileSystemPreferencesProvider.PATH, file.getAbsolutePath()); - PreferencesProvider provider = _factory.createInstance(id, attributes, _authenticationProvider); + attributes.put(ConfiguredObject.ID, id); + PreferencesProvider provider = _factory.create(attributes, _authenticationProvider); assertNotNull("Preferences provider was not recovered", provider); assertEquals("Unexpected name", "test-provider", provider.getName()); assertEquals("Unexpected id", id, provider.getId()); diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderTest.java index 3b8ab12384..70cbfae9d4 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/FileSystemPreferencesProviderTest.java @@ -97,7 +97,7 @@ public class FileSystemPreferencesProviderTest extends QpidTestCase Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(FileSystemPreferencesProvider.PATH, nonExistingFile.getAbsolutePath()); attributes.put(FileSystemPreferencesProvider.NAME, getTestName()); - _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider, _broker.getTaskExecutor()); + _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider); _preferencesProvider.createStoreIfNotExist(); assertEquals(State.INITIALISING, _preferencesProvider.getState()); assertTrue("Preferences file was not created", nonExistingFile.exists()); @@ -118,7 +118,7 @@ public class FileSystemPreferencesProviderTest extends QpidTestCase Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(FileSystemPreferencesProvider.NAME, getTestName()); attributes.put(FileSystemPreferencesProvider.PATH, emptyPrefsFile.getAbsolutePath()); - _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider, _broker.getTaskExecutor()); + _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider); assertEquals(State.INITIALISING, _preferencesProvider.getState()); } finally @@ -278,7 +278,7 @@ public class FileSystemPreferencesProviderTest extends QpidTestCase Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(FileSystemPreferencesProvider.PATH, _preferencesFile.getAbsolutePath()); attributes.put(FileSystemPreferencesProvider.NAME, "test"); - return _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider, _broker.getTaskExecutor()); + return _preferencesProvider = new FileSystemPreferencesProvider(UUID.randomUUID(), attributes, _authenticationProvider); } private void assertUser1Preferences(Map<String, Object> preferences1) diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java index c4b0134ab1..d9dffc6855 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/adapter/PortFactoryTest.java @@ -43,6 +43,8 @@ import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.Transport; import org.apache.qpid.server.model.TrustStore; +import org.apache.qpid.server.model.port.AmqpPort; +import org.apache.qpid.server.model.port.PortFactory; import org.apache.qpid.test.utils.QpidTestCase; public class PortFactoryTest extends QpidTestCase @@ -63,6 +65,7 @@ public class PortFactoryTest extends QpidTestCase private AuthenticationProvider _authProvider = mock(AuthenticationProvider.class); private PortFactory _portFactory; + @Override protected void setUp() throws Exception { @@ -83,7 +86,13 @@ public class PortFactoryTest extends QpidTestCase public void testDefaultProtocols() { - Collection<Protocol> protocols = _portFactory.getDefaultProtocols(); + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.put(Port.PORT, 1); + attributes.put(Port.AUTHENTICATION_PROVIDER, _authProviderName); + Port port = _portFactory.createPort(_portId, _broker, attributes); + + Collection<Protocol> protocols = port.getProtocols(); + EnumSet<Protocol> expected = EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1, Protocol.AMQP_0_10, Protocol.AMQP_1_0); assertEquals("Unexpected protocols", new HashSet<Protocol>(expected), new HashSet<Protocol>(protocols)); @@ -93,8 +102,14 @@ public class PortFactoryTest extends QpidTestCase { setTestSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_EXCLUDES, Protocol.AMQP_1_0.name() + "," + Protocol.AMQP_0_10.name()); - _portFactory = new PortFactory(); - Collection<Protocol> protocols = _portFactory.getDefaultProtocols(); + + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.put(Port.PORT, 1); + attributes.put(Port.AUTHENTICATION_PROVIDER, _authProviderName); + Port port = _portFactory.createPort(_portId, _broker, attributes); + + Collection<Protocol> protocols = port.getProtocols(); + EnumSet<Protocol> expected = EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1); assertEquals("Unexpected protocols", new HashSet<Protocol>(expected), new HashSet<Protocol>(protocols)); } @@ -105,8 +120,14 @@ public class PortFactoryTest extends QpidTestCase + Protocol.AMQP_0_10.name() + "," + Protocol.AMQP_0_9_1.name()); setTestSystemProperty(BrokerProperties.PROPERTY_BROKER_DEFAULT_AMQP_PROTOCOL_INCLUDES, Protocol.AMQP_0_10.name() + "," + Protocol.AMQP_0_9_1.name()); - _portFactory = new PortFactory(); - Collection<Protocol> protocols = _portFactory.getDefaultProtocols(); + + Map<String, Object> attributes = new HashMap<String, Object>(); + attributes.put(Port.PORT, 1); + attributes.put(Port.AUTHENTICATION_PROVIDER, _authProviderName); + Port port = _portFactory.createPort(_portId, _broker, attributes); + + Collection<Protocol> protocols = port.getProtocols(); + EnumSet<Protocol> expected = EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1, Protocol.AMQP_0_10); assertEquals("Unexpected protocols", new HashSet<Protocol>(expected), new HashSet<Protocol>(protocols)); } @@ -119,10 +140,11 @@ public class PortFactoryTest extends QpidTestCase Port port = _portFactory.createPort(_portId, _broker, attributes); assertNotNull(port); - assertTrue(port instanceof AmqpPortAdapter); + assertTrue(port instanceof AmqpPort); assertEquals("Unexpected port", 1, port.getPort()); assertEquals("Unexpected transports", Collections.singleton(PortFactory.DEFAULT_TRANSPORT), port.getTransports()); - assertEquals("Unexpected protocols", _portFactory.getDefaultProtocols(), port.getProtocols()); + assertEquals("Unexpected protocols", EnumSet.of(Protocol.AMQP_0_8, Protocol.AMQP_0_9, Protocol.AMQP_0_9_1, Protocol.AMQP_0_10, + Protocol.AMQP_1_0), port.getProtocols()); assertEquals("Unexpected send buffer size", PortFactory.DEFAULT_AMQP_SEND_BUFFER_SIZE, port.getAttribute(Port.SEND_BUFFER_SIZE)); assertEquals("Unexpected receive buffer size", PortFactory.DEFAULT_AMQP_RECEIVE_BUFFER_SIZE, @@ -252,7 +274,7 @@ public class PortFactoryTest extends QpidTestCase Port port = _portFactory.createPort(_portId, _broker, _attributes); assertNotNull(port); - assertTrue(port instanceof AmqpPortAdapter); + assertTrue(port instanceof AmqpPort); assertEquals(_portId, port.getId()); assertEquals(_portNumber, port.getPort()); if(useSslTransport) @@ -285,7 +307,7 @@ public class PortFactoryTest extends QpidTestCase Port port = _portFactory.createPort(_portId, _broker, _attributes); assertNotNull(port); - assertFalse("Port should be a PortAdapter, not its AMQP-specific subclass", port instanceof AmqpPortAdapter); + assertFalse("Port should be a PortAdapter, not its AMQP-specific subclass", port instanceof AmqpPort); assertEquals(_portId, port.getId()); assertEquals(_portNumber, port.getPort()); assertEquals(_tcpTransportSet, port.getTransports()); @@ -310,7 +332,7 @@ public class PortFactoryTest extends QpidTestCase Port port = _portFactory.createPort(_portId, _broker, _attributes); assertNotNull(port); - assertFalse("Port should be a PortAdapter, not its AMQP-specific subclass", port instanceof AmqpPortAdapter); + assertFalse("Port should be a PortAdapter, not its AMQP-specific subclass", port instanceof AmqpPort); assertEquals(_portId, port.getId()); assertEquals(_portNumber, port.getPort()); assertEquals(Collections.singleton(PortFactory.DEFAULT_TRANSPORT), port.getTransports()); diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java index e2f2dff298..e72880e19a 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java @@ -35,7 +35,8 @@ import java.util.UUID; import junit.framework.TestCase; import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; +import org.apache.qpid.server.configuration.ConfigurationEntryImpl; +import org.apache.qpid.server.configuration.store.MemoryConfigurationEntryStore; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.Port; import org.apache.qpid.server.model.VirtualHost; @@ -44,13 +45,13 @@ public class ConfigurationEntryTest extends TestCase { public void testGetChildren() { - ConfigurationEntryStore store = mock(ConfigurationEntryStore.class); + MemoryConfigurationEntryStore store = mock(MemoryConfigurationEntryStore.class); - ConfigurationEntry virtualHostEntry1 = new ConfigurationEntry(UUID.randomUUID(), VirtualHost.class.getSimpleName(), + ConfigurationEntry virtualHostEntry1 = new ConfigurationEntryImpl(UUID.randomUUID(), VirtualHost.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); - ConfigurationEntry virtualHostEntry2 = new ConfigurationEntry(UUID.randomUUID(), VirtualHost.class.getSimpleName(), + ConfigurationEntry virtualHostEntry2 = new ConfigurationEntryImpl(UUID.randomUUID(), VirtualHost.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); - ConfigurationEntry portEntry = new ConfigurationEntry(UUID.randomUUID(), Port.class.getSimpleName(), + ConfigurationEntry portEntry = new ConfigurationEntryImpl(UUID.randomUUID(), Port.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); when(store.getEntry(virtualHostEntry1.getId())).thenReturn(virtualHostEntry1); @@ -61,7 +62,7 @@ public class ConfigurationEntryTest extends TestCase childrenIds.add(virtualHostEntry1.getId()); childrenIds.add(virtualHostEntry2.getId()); childrenIds.add(portEntry.getId()); - ConfigurationEntry parentEntry = new ConfigurationEntry(UUID.randomUUID(), Broker.class.getSimpleName(), + ConfigurationEntry parentEntry = new ConfigurationEntryImpl(UUID.randomUUID(), Broker.class.getSimpleName(), Collections.<String, Object> emptyMap(), childrenIds, store); Map<String, Collection<ConfigurationEntry>> children = parentEntry.getChildren(); @@ -78,14 +79,14 @@ public class ConfigurationEntryTest extends TestCase public void testHashCode() { - ConfigurationEntryStore store = mock(ConfigurationEntryStore.class); + MemoryConfigurationEntryStore store = mock(MemoryConfigurationEntryStore.class); UUID id = UUID.randomUUID(); - ConfigurationEntry entry1 = new ConfigurationEntry(id, VirtualHost.class.getSimpleName(), + ConfigurationEntry entry1 = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); - ConfigurationEntry entry2 = new ConfigurationEntry(id, VirtualHost.class.getSimpleName(), + ConfigurationEntry entry2 = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); - ConfigurationEntry entryWithDifferentId = new ConfigurationEntry(UUID.randomUUID(), + ConfigurationEntry entryWithDifferentId = new ConfigurationEntryImpl(UUID.randomUUID(), VirtualHost.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); assertTrue(entry1.hashCode() == entry2.hashCode()); @@ -94,35 +95,35 @@ public class ConfigurationEntryTest extends TestCase public void testEqualsObject() { - ConfigurationEntryStore store = mock(ConfigurationEntryStore.class); + MemoryConfigurationEntryStore store = mock(MemoryConfigurationEntryStore.class); UUID id = UUID.randomUUID(); Map<String, Object> attributes1 = new HashMap<String, Object>(); attributes1.put(VirtualHost.NAME, "name1"); Set<UUID> childrenIds = Collections.singleton(UUID.randomUUID()); - ConfigurationEntry entry1 = new ConfigurationEntry(id, VirtualHost.class.getSimpleName(), attributes1, + ConfigurationEntry entry1 = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), attributes1, childrenIds, store); Map<String, Object> attributes2 = new HashMap<String, Object>(); attributes2.put(VirtualHost.NAME, "name2"); - ConfigurationEntry entry2 = new ConfigurationEntry(id, VirtualHost.class.getSimpleName(), attributes1, + ConfigurationEntry entry2 = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), attributes1, childrenIds, store); - ConfigurationEntry entryWithDifferentId = new ConfigurationEntry(UUID.randomUUID(), + ConfigurationEntry entryWithDifferentId = new ConfigurationEntryImpl(UUID.randomUUID(), VirtualHost.class.getSimpleName(), attributes1, childrenIds, store); assertTrue(entry1.equals(entry2)); assertFalse("Entries should be different because of different IDs", entry1.equals(entryWithDifferentId)); - ConfigurationEntry entryWithDifferentChildId = new ConfigurationEntry(id, + ConfigurationEntry entryWithDifferentChildId = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), attributes1, Collections.singleton(UUID.randomUUID()), store); assertFalse("Entries should be different because of different children", entry1.equals(entryWithDifferentChildId)); - ConfigurationEntry entryWithDifferentName = new ConfigurationEntry(id, + ConfigurationEntry entryWithDifferentName = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), attributes2, childrenIds, store); assertFalse("Entries should be different because of different attributes", entry1.equals(entryWithDifferentName)); - ConfigurationEntry entryWithDifferentType = new ConfigurationEntry(id, + ConfigurationEntry entryWithDifferentType = new ConfigurationEntryImpl(id, Broker.class.getSimpleName(), attributes1, childrenIds, store); assertFalse("Entries should be different because of different types", entry1.equals(entryWithDifferentType)); } diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java deleted file mode 100644 index c911a88aa2..0000000000 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/Base64MD5PasswordFileAuthenticationManagerFactoryTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.security.auth.manager; - -import static org.mockito.Mockito.mock; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.model.AuthenticationProvider; -import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.AuthenticationManagerFactory; -import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase; - -public class Base64MD5PasswordFileAuthenticationManagerFactoryTest extends TestCase -{ - AuthenticationManagerFactory _factory = new Base64MD5PasswordFileAuthenticationManagerFactory(); - private Map<String, Object> _configuration = new HashMap<String, Object>(); - private File _emptyPasswordFile; - private Broker _broker = mock(Broker.class); - - @Override - protected void setUp() throws Exception - { - super.setUp(); - _emptyPasswordFile = File.createTempFile(getName(), "passwd"); - _emptyPasswordFile.deleteOnExit(); - - _configuration.put(AuthenticationProvider.ID, UUID.randomUUID()); - _configuration.put(AuthenticationProvider.NAME, getName()); - } - - public void testBase64MD5InstanceCreated() throws Exception - { - _configuration.put(AuthenticationProvider.TYPE, Base64MD5PasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - _configuration.put("path", _emptyPasswordFile.getAbsolutePath()); - - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); - assertNotNull(manager); - assertTrue(manager instanceof PrincipalDatabaseAuthenticationManager); - assertTrue(((PrincipalDatabaseAuthenticationManager)manager).getPrincipalDatabase() instanceof Base64MD5PasswordFilePrincipalDatabase); - } - - public void testPasswordFileNotFound() throws Exception - { - //delete the file - _emptyPasswordFile.delete(); - - _configuration.put(AuthenticationProvider.TYPE, Base64MD5PasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - _configuration.put("path", _emptyPasswordFile.getAbsolutePath()); - - try - { - _factory.createInstance(_broker, _configuration, false); - } - catch (RuntimeException re) - { - assertTrue(re.getCause() instanceof FileNotFoundException); - } - } - - public void testReturnsNullWhenNoConfig() throws Exception - { - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); - assertNull(manager); - } - - public void testReturnsNullWhenConfigForOtherAuthManagerType() throws Exception - { - _configuration.put(AuthenticationProvider.TYPE, "other-auth-manager"); - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); - assertNull(manager); - } - - public void testThrowsExceptionWhenConfigForPlainPDImplementationNoPasswordFileValueSpecified() throws Exception - { - _configuration.put(AuthenticationProvider.TYPE, Base64MD5PasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); - - try - { - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); - fail("No authentication manager should be created"); - } - catch(IllegalArgumentException e) - { - // pass - } - } - - @Override - protected void tearDown() throws Exception - { - try - { - if (_emptyPasswordFile == null && _emptyPasswordFile.exists()) - { - _emptyPasswordFile.delete(); - } - } - finally - { - super.tearDown(); - } - } -}
\ No newline at end of file diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java index e37bee0832..21d35815f9 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/PlainPasswordFileAuthenticationManagerFactoryTest.java @@ -35,7 +35,8 @@ import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalD public class PlainPasswordFileAuthenticationManagerFactoryTest extends TestCase { - AuthenticationManagerFactory _factory = new PlainPasswordFileAuthenticationManagerFactory(); + + PlainPasswordFileAuthenticationManagerFactory _factory = new PlainPasswordFileAuthenticationManagerFactory(); private Map<String, Object> _configuration = new HashMap<String, Object>(); private File _emptyPasswordFile; private Broker _broker = mock(Broker.class); @@ -55,7 +56,7 @@ public class PlainPasswordFileAuthenticationManagerFactoryTest extends TestCase _configuration.put(AuthenticationProvider.TYPE, PlainPasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); _configuration.put("path", _emptyPasswordFile.getAbsolutePath()); - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); + AuthenticationManager manager = _factory.create(_configuration, _broker); assertNotNull(manager); assertTrue(manager instanceof PrincipalDatabaseAuthenticationManager); assertTrue(((PrincipalDatabaseAuthenticationManager)manager).getPrincipalDatabase() instanceof PlainPasswordFilePrincipalDatabase); @@ -70,33 +71,20 @@ public class PlainPasswordFileAuthenticationManagerFactoryTest extends TestCase _configuration.put("path", _emptyPasswordFile.getAbsolutePath()); - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); + AuthenticationManager manager = _factory.create(_configuration, _broker); assertNotNull(manager); assertTrue(manager instanceof PrincipalDatabaseAuthenticationManager); assertTrue(((PrincipalDatabaseAuthenticationManager)manager).getPrincipalDatabase() instanceof PlainPasswordFilePrincipalDatabase); } - public void testReturnsNullWhenNoConfig() throws Exception - { - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); - assertNull(manager); - } - - public void testReturnsNullWhenConfigForOtherAuthManagerType() throws Exception - { - _configuration.put(AuthenticationProvider.TYPE, "other-auth-manager"); - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); - assertNull(manager); - } - public void testThrowsExceptionWhenConfigForPlainPDImplementationNoPasswordFileValueSpecified() throws Exception { _configuration.put(AuthenticationProvider.TYPE, PlainPasswordFileAuthenticationManagerFactory.PROVIDER_TYPE); try { - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); + AuthenticationManager manager = _factory.create(_configuration, _broker); fail("No authentication manager should be created"); } catch (IllegalArgumentException e) diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManagerTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManagerTest.java index 033e0afde8..7d8d6ad6e2 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManagerTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/ScramSHA1AuthenticationManagerTest.java @@ -58,7 +58,7 @@ public class ScramSHA1AuthenticationManagerTest extends QpidTestCase final Map<String, Object> attributesMap = new HashMap<String, Object>(); attributesMap.put(AuthenticationProvider.NAME, getTestName()); attributesMap.put(AuthenticationProvider.ID, UUID.randomUUID()); - _authManager = new ScramSHA1AuthenticationManager(_broker, Collections.<String,Object>emptyMap(),attributesMap,false); + _authManager = new ScramSHA1AuthenticationManager(_broker, Collections.<String,Object>emptyMap(),attributesMap); } @Override diff --git a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java index 967ae2e4f9..1ea74acd00 100644 --- a/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java +++ b/qpid/java/broker-core/src/test/java/org/apache/qpid/server/security/auth/manager/SimpleLDAPAuthenticationManagerFactoryTest.java @@ -29,9 +29,9 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.SystemContext; import org.apache.qpid.server.model.TrustStore; @@ -42,6 +42,8 @@ public class SimpleLDAPAuthenticationManagerFactoryTest extends TestCase private SimpleLDAPAuthenticationManagerFactory _factory = new SimpleLDAPAuthenticationManagerFactory(); private Map<String, Object> _configuration = new HashMap<String, Object>(); private Broker _broker = mock(Broker.class); + private SystemContext _systemContext = mock(SystemContext.class); + private TrustStore _trustStore = mock(TrustStore.class); public void setUp() throws Exception @@ -51,6 +53,9 @@ public class SimpleLDAPAuthenticationManagerFactoryTest extends TestCase when(_trustStore.getName()).thenReturn("mytruststore"); when(_trustStore.getId()).thenReturn(UUID.randomUUID()); + when(_broker.getParent(eq(SystemContext.class))).thenReturn(_systemContext); + when(_systemContext.getChildren(eq(Broker.class))).thenReturn(Collections.singleton(_broker)); + _configuration.put(AuthenticationProvider.ID, UUID.randomUUID()); _configuration.put(AuthenticationProvider.NAME, getName()); } @@ -61,7 +66,7 @@ public class SimpleLDAPAuthenticationManagerFactoryTest extends TestCase _configuration.put("providerUrl", "ldap://example.com:389/"); _configuration.put("searchContext", "dc=example"); - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); + AuthenticationManager manager = _factory.create(_configuration, _broker); assertNotNull(manager); } @@ -72,7 +77,7 @@ public class SimpleLDAPAuthenticationManagerFactoryTest extends TestCase _configuration.put("providerUrl", "ldaps://example.com:636/"); _configuration.put("searchContext", "dc=example"); - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); + AuthenticationManager manager = _factory.create(_configuration, _broker); assertNotNull(manager); } @@ -87,7 +92,7 @@ public class SimpleLDAPAuthenticationManagerFactoryTest extends TestCase _configuration.put("searchContext", "dc=example"); _configuration.put("trustStore", "mytruststore"); - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); + AuthenticationManager manager = _factory.create(_configuration, _broker); assertNotNull(manager); } @@ -102,7 +107,7 @@ public class SimpleLDAPAuthenticationManagerFactoryTest extends TestCase try { - _factory.createInstance(_broker, _configuration, false); + _factory.create(_configuration, _broker); fail("Exception not thrown"); } catch(IllegalArgumentException e) @@ -111,9 +116,4 @@ public class SimpleLDAPAuthenticationManagerFactoryTest extends TestCase } } - public void testReturnsNullWhenNoConfig() throws Exception - { - AuthenticationManager manager = _factory.createInstance(_broker, _configuration, false); - assertNull(manager); - } } |
