diff options
author | Robert Godfrey <rgodfrey@apache.org> | 2014-07-26 22:57:11 +0000 |
---|---|---|
committer | Robert Godfrey <rgodfrey@apache.org> | 2014-07-26 22:57:11 +0000 |
commit | 449848716c33fc8c24903b349867c13defcfa5b1 (patch) | |
tree | 13775e1ff30fbdae2951deddba59361046275e39 | |
parent | 0fbeae8c30a0c8e38968e903aac2f6139170e130 (diff) | |
download | qpid-python-449848716c33fc8c24903b349867c13defcfa5b1.tar.gz |
QPID-5165 : Change the Broker stores to use the generic ConfigurationStore implementations and remove old EntryStore implementations
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk/qpid@1613739 13f79535-47bb-0310-9956-ffa450edef68
84 files changed, 1586 insertions, 3569 deletions
diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBConfigurationStore.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBConfigurationStore.java index 9c58be7694..bbcf6db2fe 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBConfigurationStore.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBConfigurationStore.java @@ -20,9 +20,9 @@ */ package org.apache.qpid.server.store.berkeleydb; +import static org.apache.qpid.server.store.berkeleydb.BDBUtils.DEFAULT_DATABASE_CONFIG; import static org.apache.qpid.server.store.berkeleydb.BDBUtils.abortTransactionSafely; import static org.apache.qpid.server.store.berkeleydb.BDBUtils.closeCursorSafely; -import static org.apache.qpid.server.store.berkeleydb.BDBUtils.DEFAULT_DATABASE_CONFIG; import java.io.File; import java.util.ArrayList; @@ -78,19 +78,25 @@ public class BDBConfigurationStore implements MessageStoreProvider, DurableConfi private String _storeLocation; private ConfiguredObject<?> _parent; + private final Class<? extends ConfiguredObject> _rootClass; + private boolean _overwrite; + private ConfiguredObjectRecord[] _initialRecords; - public BDBConfigurationStore() + public BDBConfigurationStore(final Class<? extends ConfiguredObject> rootClass) { - this(new StandardEnvironmentFacadeFactory()); + this(new StandardEnvironmentFacadeFactory(), rootClass); } - public BDBConfigurationStore(EnvironmentFacadeFactory environmentFacadeFactory) + public BDBConfigurationStore(EnvironmentFacadeFactory environmentFacadeFactory, Class<? extends ConfiguredObject> rootClass) { _environmentFacadeFactory = environmentFacadeFactory; + _rootClass = rootClass; } @Override - public void openConfigurationStore(ConfiguredObject<?> parent) + public void openConfigurationStore(ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) { if (_configurationStoreOpen.compareAndSet(false, true)) { @@ -100,6 +106,8 @@ public class BDBConfigurationStore implements MessageStoreProvider, DurableConfi { _environmentFacade = _environmentFacadeFactory.createEnvironmentFacade(parent); _storeLocation = _environmentFacade.getStoreLocation(); + _overwrite = overwrite; + _initialRecords = initialRecords; } else { @@ -108,12 +116,30 @@ public class BDBConfigurationStore implements MessageStoreProvider, DurableConfi } } + private void clearConfigurationRecords() + { + checkConfigurationStoreOpen(); + + _environmentFacade.clearDatabase(CONFIGURED_OBJECTS_DB_NAME, DEFAULT_DATABASE_CONFIG); + _environmentFacade.clearDatabase(CONFIGURED_OBJECT_HIERARCHY_DB_NAME, DEFAULT_DATABASE_CONFIG); + } + @Override public void upgradeStoreStructure() throws StoreException { try { new Upgrader(_environmentFacade.getEnvironment(), _parent).upgradeIfNecessary(); + if(_overwrite) + { + clearConfigurationRecords(); + _overwrite = false; + } + if(getConfiguredObjectsDb().count() == 0l) + { + update(true, _initialRecords); + } + _initialRecords = new ConfiguredObjectRecord[0]; } catch(DatabaseException e) { @@ -397,11 +423,11 @@ public class BDBConfigurationStore implements MessageStoreProvider, DurableConfi DatabaseEntry hierarchyKey = new DatabaseEntry(); DatabaseEntry hierarchyValue = new DatabaseEntry(); - for(Map.Entry<String, ConfiguredObjectRecord> parent : configuredObject.getParents().entrySet()) + for(Map.Entry<String, UUID> parent : configuredObject.getParents().entrySet()) { hierarchyBinding.objectToEntry(new HierarchyKey(configuredObject.getId(), parent.getKey()), hierarchyKey); - UUIDTupleBinding.getInstance().objectToEntry(parent.getValue().getId(), hierarchyValue); + UUIDTupleBinding.getInstance().objectToEntry(parent.getValue(), hierarchyValue); status = getConfiguredObjectHierarchyDb().put(txn, hierarchyKey, hierarchyValue); if (status != OperationStatus.SUCCESS) { @@ -414,7 +440,7 @@ public class BDBConfigurationStore implements MessageStoreProvider, DurableConfi private OperationStatus removeConfiguredObject(Transaction tx, ConfiguredObjectRecord record) throws StoreException { UUID id = record.getId(); - Map<String, ConfiguredObjectRecord> parents = record.getParents(); + Map<String, UUID> parents = record.getParents(); if (LOGGER.isDebugEnabled()) { diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBConfiguredObjectRecord.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBConfiguredObjectRecord.java index a5eac25968..6db6217769 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBConfiguredObjectRecord.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBConfiguredObjectRecord.java @@ -20,19 +20,19 @@ */ package org.apache.qpid.server.store.berkeleydb; -import org.apache.qpid.server.store.ConfiguredObjectRecord; - import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; +import org.apache.qpid.server.store.ConfiguredObjectRecord; + public class BDBConfiguredObjectRecord implements ConfiguredObjectRecord { private final UUID _id; private final String _type; private final Map<String,Object> _attributes; - private Map<String, ConfiguredObjectRecord> _parents = new HashMap<String, ConfiguredObjectRecord>(); + private Map<String, UUID> _parents = new HashMap<>(); public BDBConfiguredObjectRecord(final UUID id, final String type, final Map<String, Object> attributes) { @@ -58,11 +58,11 @@ public class BDBConfiguredObjectRecord implements ConfiguredObjectRecord void addParent(String parentType, ConfiguredObjectRecord parent) { - _parents.put(parentType, parent); + _parents.put(parentType, parent.getId()); } @Override - public Map<String, ConfiguredObjectRecord> getParents() + public Map<String, UUID> getParents() { return Collections.unmodifiableMap(_parents); } diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBSystemConfig.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBSystemConfig.java new file mode 100644 index 0000000000..9fc0b14af8 --- /dev/null +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBSystemConfig.java @@ -0,0 +1,39 @@ +/* + * + * 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.berkeleydb; + +import org.apache.qpid.server.model.ManagedAttribute; +import org.apache.qpid.server.model.SystemConfig; +import org.apache.qpid.server.store.FileBasedSettings; +import org.apache.qpid.server.store.SizeMonitoringSettings; + +public interface BDBSystemConfig<X extends BDBSystemConfig<X>> extends SystemConfig<X>, FileBasedSettings, + SizeMonitoringSettings +{ + @ManagedAttribute(mandatory = true) + String getStorePath(); + + @ManagedAttribute(mandatory = true, defaultValue = "0") + Long getStoreUnderfullSize(); + + @ManagedAttribute(mandatory = true, defaultValue = "0") + Long getStoreOverfullSize(); +} diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBSystemConfigImpl.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBSystemConfigImpl.java new file mode 100644 index 0000000000..0fc44605fe --- /dev/null +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBSystemConfigImpl.java @@ -0,0 +1,79 @@ +/* + * + * 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.berkeleydb; + +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.model.AbstractSystemConfig; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedAttributeField; +import org.apache.qpid.server.model.ManagedObject; +import org.apache.qpid.server.model.SystemConfigFactoryConstructor; +import org.apache.qpid.server.store.DurableConfigurationStore; + +@ManagedObject(category = false, type = BDBSystemConfigImpl.SYSTEM_CONFIG_TYPE) +public class BDBSystemConfigImpl extends AbstractSystemConfig<BDBSystemConfigImpl> implements BDBSystemConfig<BDBSystemConfigImpl> +{ + public static final String SYSTEM_CONFIG_TYPE = "BDB"; + + @ManagedAttributeField + private String _storePath; + @ManagedAttributeField + private Long _storeUnderfullSize; + @ManagedAttributeField + private Long _storeOverfullSize; + + + @SystemConfigFactoryConstructor + public BDBSystemConfigImpl(final TaskExecutor taskExecutor, + final EventLogger eventLogger, + final LogRecorder logRecorder, + final BrokerOptions brokerOptions) + { + super(taskExecutor, eventLogger, logRecorder, brokerOptions); + } + + @Override + protected DurableConfigurationStore createStoreObject() + { + return new BDBConfigurationStore(Broker.class); + } + + @Override + public String getStorePath() + { + return _storePath; + } + + @Override + public Long getStoreUnderfullSize() + { + return _storeUnderfullSize; + } + + @Override + public Long getStoreOverfullSize() + { + return _storeOverfullSize; + } +} diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/EnvironmentFacade.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/EnvironmentFacade.java index 3c8fe00d01..bd078bb0f7 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/EnvironmentFacade.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/EnvironmentFacade.java @@ -24,8 +24,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.apache.qpid.server.store.StoreFuture; - import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; @@ -36,6 +34,8 @@ import com.sleepycat.je.Sequence; import com.sleepycat.je.SequenceConfig; import com.sleepycat.je.Transaction; +import org.apache.qpid.server.store.StoreFuture; + public interface EnvironmentFacade { @SuppressWarnings("serial") @@ -49,6 +49,7 @@ public interface EnvironmentFacade Environment getEnvironment(); Database openDatabase(String databaseName, DatabaseConfig databaseConfig); + Database clearDatabase(String databaseName, DatabaseConfig databaseConfig); Sequence openSequence(Database database, DatabaseEntry sequenceKey, SequenceConfig sequenceConfig); diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacade.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacade.java index c8f2250566..55966ebce4 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacade.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/StandardEnvironmentFacade.java @@ -275,6 +275,15 @@ public class StandardEnvironmentFacade implements EnvironmentFacade return cachedHandle; } + + @Override + public Database clearDatabase(String name, DatabaseConfig databaseConfig) + { + closeDatabase(name); + _environment.removeDatabase(null, name); + return openDatabase(name, databaseConfig); + } + @Override public Sequence openSequence(final Database database, final DatabaseEntry sequenceKey, diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/replication/ReplicatedEnvironmentFacade.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/replication/ReplicatedEnvironmentFacade.java index e7874c317a..20a6bf058c 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/replication/ReplicatedEnvironmentFacade.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/replication/ReplicatedEnvironmentFacade.java @@ -44,46 +44,20 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; -import com.sleepycat.je.DatabaseEntry; -import com.sleepycat.je.Sequence; -import com.sleepycat.je.SequenceConfig; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.store.StoreFuture; -import org.apache.qpid.server.store.berkeleydb.CoalescingCommiter; -import org.apache.qpid.server.store.berkeleydb.EnvironmentFacade; -import org.apache.qpid.server.store.berkeleydb.LoggingAsyncExceptionListener; -import org.apache.qpid.server.util.DaemonThreadFactory; -import org.codehaus.jackson.map.ObjectMapper; - import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; +import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.Durability; import com.sleepycat.je.Durability.ReplicaAckPolicy; import com.sleepycat.je.Durability.SyncPolicy; import com.sleepycat.je.EnvironmentConfig; import com.sleepycat.je.EnvironmentFailureException; +import com.sleepycat.je.Sequence; +import com.sleepycat.je.SequenceConfig; import com.sleepycat.je.Transaction; import com.sleepycat.je.TransactionConfig; -import com.sleepycat.je.rep.AppStateMonitor; -import com.sleepycat.je.rep.InsufficientLogException; -import com.sleepycat.je.rep.InsufficientAcksException; -import com.sleepycat.je.rep.InsufficientReplicasException; -import com.sleepycat.je.rep.NetworkRestore; -import com.sleepycat.je.rep.NetworkRestoreConfig; -import com.sleepycat.je.rep.NodeType; -import com.sleepycat.je.rep.NodeState; -import com.sleepycat.je.rep.RepInternal; -import com.sleepycat.je.rep.ReplicatedEnvironment; -import com.sleepycat.je.rep.ReplicationConfig; -import com.sleepycat.je.rep.ReplicationGroup; -import com.sleepycat.je.rep.ReplicationMutableConfig; -import com.sleepycat.je.rep.ReplicationNode; -import com.sleepycat.je.rep.RestartRequiredException; -import com.sleepycat.je.rep.StateChangeEvent; -import com.sleepycat.je.rep.StateChangeListener; +import com.sleepycat.je.rep.*; import com.sleepycat.je.rep.util.DbPing; import com.sleepycat.je.rep.util.ReplicationGroupAdmin; import com.sleepycat.je.rep.utilint.HostPortPair; @@ -91,6 +65,15 @@ import com.sleepycat.je.rep.utilint.ServiceDispatcher.ServiceConnectFailedExcept import com.sleepycat.je.rep.vlsn.VLSNRange; import com.sleepycat.je.utilint.PropUtil; import com.sleepycat.je.utilint.VLSN; +import org.apache.log4j.Logger; +import org.codehaus.jackson.map.ObjectMapper; + +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.server.store.StoreFuture; +import org.apache.qpid.server.store.berkeleydb.CoalescingCommiter; +import org.apache.qpid.server.store.berkeleydb.EnvironmentFacade; +import org.apache.qpid.server.store.berkeleydb.LoggingAsyncExceptionListener; +import org.apache.qpid.server.util.DaemonThreadFactory; public class ReplicatedEnvironmentFacade implements EnvironmentFacade, StateChangeListener { @@ -401,6 +384,15 @@ public class ReplicatedEnvironmentFacade implements EnvironmentFacade, StateChan return cachedHandle; } + + @Override + public Database clearDatabase(String name, DatabaseConfig databaseConfig) + { + closeDatabase(name); + _environment.removeDatabase(null, name); + return openDatabase(name, databaseConfig); + } + @Override public void closeDatabase(final String databaseName) { diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeImpl.java b/java/bdbstore/src/main/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeImpl.java index 8b3b45c63f..388e2e7608 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeImpl.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeImpl.java @@ -66,7 +66,6 @@ import org.apache.qpid.server.store.berkeleydb.replication.ReplicatedEnvironment import org.apache.qpid.server.store.berkeleydb.replication.ReplicatedEnvironmentFacadeFactory; import org.apache.qpid.server.store.berkeleydb.replication.ReplicationGroupListener; import org.apache.qpid.server.util.ServerScopedRuntimeException; -import org.apache.qpid.server.virtualhost.berkeleydb.BDBHAVirtualHost; import org.apache.qpid.server.virtualhost.berkeleydb.BDBHAVirtualHostImpl; import org.apache.qpid.server.virtualhostnode.AbstractVirtualHostNode; @@ -265,7 +264,7 @@ public class BDBHAVirtualHostNodeImpl extends AbstractVirtualHostNode<BDBHAVirtu @Override protected DurableConfigurationStore createConfigurationStore() { - return new BDBConfigurationStore(new ReplicatedEnvironmentFacadeFactory()); + return new BDBConfigurationStore(new ReplicatedEnvironmentFacadeFactory(), VirtualHost.class); } @Override @@ -276,7 +275,7 @@ public class BDBHAVirtualHostNodeImpl extends AbstractVirtualHostNode<BDBHAVirtu LOGGER.debug("Activating virtualhost node " + this); } - getConfigurationStore().openConfigurationStore(this); + getConfigurationStore().openConfigurationStore(this, false); getEventLogger().message(getVirtualHostNodeLogSubject(), HighAvailabilityMessages.ATTACHED(getName(), getGroupName(), getRole())); diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBVirtualHostNodeImpl.java b/java/bdbstore/src/main/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBVirtualHostNodeImpl.java index 27a2177b80..e9edf9f544 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBVirtualHostNodeImpl.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBVirtualHostNodeImpl.java @@ -27,6 +27,7 @@ import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ManagedAttributeField; import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.berkeleydb.BDBConfigurationStore; import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; @@ -54,7 +55,7 @@ public class BDBVirtualHostNodeImpl extends AbstractStandardVirtualHostNode<BDBV @Override protected DurableConfigurationStore createConfigurationStore() { - return new BDBConfigurationStore(); + return new BDBConfigurationStore(VirtualHost.class); } @Override diff --git a/java/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreConfigurationTest.java b/java/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreConfigurationTest.java index e4e7286e5a..a58b1e7c2e 100644 --- a/java/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreConfigurationTest.java +++ b/java/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreConfigurationTest.java @@ -20,15 +20,16 @@ */ package org.apache.qpid.server.store.berkeleydb; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.qpid.server.model.ConfiguredObjectFactory; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.store.AbstractDurableConfigurationStoreTestCase; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.virtualhostnode.berkeleydb.BDBVirtualHostNode; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class BDBMessageStoreConfigurationTest extends AbstractDurableConfigurationStoreTestCase { @Override @@ -42,6 +43,6 @@ public class BDBMessageStoreConfigurationTest extends AbstractDurableConfigurati @Override protected DurableConfigurationStore createConfigStore() throws Exception { - return new BDBConfigurationStore(); + return new BDBConfigurationStore(VirtualHost.class); } } diff --git a/java/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeOperationalLoggingTest.java b/java/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeOperationalLoggingTest.java index ac67c86f5e..9090435e73 100644 --- a/java/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeOperationalLoggingTest.java +++ b/java/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeOperationalLoggingTest.java @@ -31,7 +31,7 @@ import org.apache.qpid.server.logging.EventLogger; import org.apache.qpid.server.logging.LogMessage; import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.logging.messages.HighAvailabilityMessages; -import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.test.utils.QpidTestCase; import org.hamcrest.Description; import org.mockito.ArgumentCaptor; @@ -51,7 +51,7 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends QpidTestCase super.setUp(); _helper = new BDBHAVirtualHostNodeTestHelper(getTestName()); _eventLogger = mock(EventLogger.class); - SystemContext<?> context = (SystemContext<?>) _helper.getBroker().getParent(SystemContext.class); + SystemConfig<?> context = (SystemConfig<?>) _helper.getBroker().getParent(SystemConfig.class); when(context.getEventLogger()).thenReturn(_eventLogger); } @@ -379,7 +379,7 @@ public class BDBHAVirtualHostNodeOperationalLoggingTest extends QpidTestCase private EventLogger resetEventLogger() { EventLogger eventLogger = mock(EventLogger.class); - SystemContext<?> context = (SystemContext<?>) _helper.getBroker().getParent(SystemContext.class); + SystemConfig<?> context = (SystemConfig<?>) _helper.getBroker().getParent(SystemConfig.class); when(context.getEventLogger()).thenReturn(eventLogger); return eventLogger; } diff --git a/java/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeTestHelper.java b/java/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeTestHelper.java index ac9ad8251a..754d8d1d09 100644 --- a/java/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeTestHelper.java +++ b/java/bdbstore/src/test/java/org/apache/qpid/server/virtualhostnode/berkeleydb/BDBHAVirtualHostNodeTestHelper.java @@ -20,15 +20,14 @@ */ package org.apache.qpid.server.virtualhostnode.berkeleydb; -import static org.mockito.Mockito.when; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.Mockito.when; import java.io.File; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -36,6 +35,7 @@ import java.util.Set; import java.util.UUID; import com.sleepycat.je.rep.ReplicationConfig; + import org.apache.qpid.server.configuration.updater.TaskExecutor; import org.apache.qpid.server.configuration.updater.TaskExecutorImpl; import org.apache.qpid.server.model.Broker; @@ -45,7 +45,6 @@ import org.apache.qpid.server.model.ConfiguredObjectFactory; import org.apache.qpid.server.model.RemoteReplicationNode; import org.apache.qpid.server.model.State; import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.store.ConfiguredObjectRecord; import org.apache.qpid.server.store.ConfiguredObjectRecordImpl; import org.apache.qpid.server.store.UnresolvedConfiguredObject; import org.apache.qpid.server.util.BrokerTestHelper; @@ -199,8 +198,8 @@ public class BDBHAVirtualHostNodeTestHelper public BDBHAVirtualHostNode<?> recoverHaVHN(UUID id, Map<String, Object> attributes) { - Map<String,ConfiguredObjectRecord> parents = new HashMap<>(); - parents.put(Broker.class.getSimpleName(),new ConfiguredObjectRecordImpl(_broker.getId(), Broker.class.getSimpleName(), Collections.<String, Object>singletonMap(Broker.NAME, _broker.getName()) )); + Map<String,UUID> parents = new HashMap<>(); + parents.put(Broker.class.getSimpleName(),_broker.getId()); ConfiguredObjectRecordImpl record = new ConfiguredObjectRecordImpl(id, VirtualHostNode.class.getSimpleName(), attributes, parents ); @SuppressWarnings("unchecked") diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntry.java b/java/broker-codegen/src/main/java/org/apache/qpid/server/model/SystemConfigFactoryConstructor.java index 02451ad94c..38551c8cac 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntry.java +++ b/java/broker-codegen/src/main/java/org/apache/qpid/server/model/SystemConfigFactoryConstructor.java @@ -18,28 +18,15 @@ * under the License. * */ -package org.apache.qpid.server.configuration; +package org.apache.qpid.server.model; -import java.util.Collection; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; -public interface ConfigurationEntry +@Retention(RetentionPolicy.CLASS) +@Target(ElementType.CONSTRUCTOR) +public @interface SystemConfigFactoryConstructor { - String ATTRIBUTE_NAME = "name"; - - UUID getId(); - - String getType(); - - Map<String, Object> getAttributes(); - - Set<UUID> getChildrenIds(); - - ConfigurationEntryStore getStore(); - - Map<String, Collection<ConfigurationEntry>> getChildren(); - - boolean hasChild(UUID id); } diff --git a/java/broker-codegen/src/main/java/org/apache/qpid/server/model/SystemConfigFactoryGenerator.java b/java/broker-codegen/src/main/java/org/apache/qpid/server/model/SystemConfigFactoryGenerator.java new file mode 100644 index 0000000000..c569bc4641 --- /dev/null +++ b/java/broker-codegen/src/main/java/org/apache/qpid/server/model/SystemConfigFactoryGenerator.java @@ -0,0 +1,163 @@ +/* + * + * 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 java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.util.Collections; +import java.util.Set; + +import javax.annotation.processing.AbstractProcessor; +import javax.annotation.processing.Filer; +import javax.annotation.processing.RoundEnvironment; +import javax.lang.model.SourceVersion; +import javax.lang.model.element.Element; +import javax.lang.model.element.ElementKind; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.PackageElement; +import javax.lang.model.element.TypeElement; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +import org.apache.qpid.server.License; + +public class SystemConfigFactoryGenerator extends AbstractProcessor +{ + @Override + public SourceVersion getSupportedSourceVersion() + { + return SourceVersion.latest(); + } + + @Override + public Set<String> getSupportedAnnotationTypes() + { + return Collections.singleton(SystemConfigFactoryConstructor.class.getName()); + } + + @Override + public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) + { + + if(roundEnv.processingOver()) + { + + return true; + } + + Filer filer = processingEnv.getFiler(); + + try + { + + for (Element e : roundEnv.getElementsAnnotatedWith(SystemConfigFactoryConstructor.class)) + { + if(e.getKind() == ElementKind.CONSTRUCTOR) + { + ExecutableElement constructorElement = (ExecutableElement) e; + String factoryName = generateObjectFactory(filer, constructorElement); + } + } + + } + catch (Exception e) + { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error: " + e.getLocalizedMessage()); + } + + return true; + } + + private String generateObjectFactory(final Filer filer, final ExecutableElement constructorElement) + { + TypeElement classElement = (TypeElement) constructorElement.getEnclosingElement(); + String factoryName = classElement.getQualifiedName().toString() + "Factory"; + String factorySimpleName = classElement.getSimpleName().toString() + "Factory"; + String objectSimpleName = classElement.getSimpleName().toString(); + processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Generating factory file for " + classElement.getQualifiedName().toString()); + + PackageElement packageElement = (PackageElement) classElement.getEnclosingElement(); + + try + { + JavaFileObject factoryFile = filer.createSourceFile(factoryName); + PrintWriter pw = new PrintWriter(new OutputStreamWriter(factoryFile.openOutputStream(), "UTF-8")); + pw.println("/*"); + for(String headerLine : License.LICENSE) + { + pw.println(" *" + headerLine); + } + pw.println(" */"); + pw.println(); + pw.print("package "); + pw.print(packageElement.getQualifiedName()); + pw.println(";"); + pw.println(); + + pw.println("import org.apache.qpid.server.BrokerOptions;"); + pw.println("import org.apache.qpid.server.configuration.updater.TaskExecutor;"); + pw.println("import org.apache.qpid.server.logging.EventLogger;"); + pw.println("import org.apache.qpid.server.logging.LogRecorder;"); + pw.println("import org.apache.qpid.server.model.SystemConfig;"); + pw.println("import org.apache.qpid.server.model.ConfiguredObjectTypeRegistry;"); + pw.println(); + pw.println("import org.apache.qpid.server.plugin.PluggableService;"); + pw.println("import org.apache.qpid.server.plugin.SystemConfigFactory;"); + pw.println(); + pw.println("@PluggableService"); + pw.println("public final class " + factorySimpleName + " implements SystemConfigFactory<"+ objectSimpleName +">"); + pw.println("{"); + pw.println(" public " + factorySimpleName + "()"); + pw.println(" {"); + pw.println(" }"); + pw.println(); + pw.println(" @Override"); + pw.println(" public final String getType()"); + pw.println(" {"); + pw.println(" return ConfiguredObjectTypeRegistry.getType(" + objectSimpleName + ".class);"); + pw.println(" }"); + pw.println(); + pw.println(" @Override"); + pw.println(" public "+objectSimpleName+" newInstance(final TaskExecutor taskExecutor,"); + pw.println(" final EventLogger eventLogger,"); + pw.println(" final LogRecorder logRecorder,"); + pw.println(" final BrokerOptions brokerOptions)"); + pw.println(" {"); + pw.println(" return new "+objectSimpleName+"(taskExecutor, eventLogger, logRecorder, brokerOptions);"); + pw.println(" }"); + pw.println("}"); + + pw.close(); + } + catch (IOException e) + { + processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, + "Failed to write factory file: " + + factoryName + + " - " + + e.getLocalizedMessage()); + } + + return factoryName; + } + +} diff --git a/java/broker-codegen/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/java/broker-codegen/src/main/resources/META-INF/services/javax.annotation.processing.Processor index 49964e3354..64440bb999 100644 --- a/java/broker-codegen/src/main/resources/META-INF/services/javax.annotation.processing.Processor +++ b/java/broker-codegen/src/main/resources/META-INF/services/javax.annotation.processing.Processor @@ -17,6 +17,7 @@ # under the License. # org.apache.qpid.server.model.ConfiguredObjectFactoryGenerator +org.apache.qpid.server.model.SystemConfigFactoryGenerator org.apache.qpid.server.plugin.PluggableProcessor org.apache.qpid.server.model.ConfiguredObjectRegistrationGenerator org.apache.qpid.server.model.validation.AttributeAnnotationValidator diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/Broker.java b/java/broker-core/src/main/java/org/apache/qpid/server/Broker.java index 1bbeaaca9d..0a1979128f 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/Broker.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/Broker.java @@ -25,9 +25,7 @@ import java.io.IOException; import java.io.InputStream; import java.security.PrivilegedAction; import java.security.PrivilegedExceptionAction; -import java.util.List; import java.util.Properties; -import java.util.Set; import javax.security.auth.Subject; @@ -35,8 +33,6 @@ import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; -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.configuration.updater.TaskExecutorImpl; import org.apache.qpid.server.logging.EventLogger; @@ -44,8 +40,9 @@ 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.SystemContext; -import org.apache.qpid.server.model.SystemContextImpl; +import org.apache.qpid.server.model.SystemConfig; +import org.apache.qpid.server.plugin.PluggableFactoryLoader; +import org.apache.qpid.server.plugin.SystemConfigFactory; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.IApplicationRegistry; import org.apache.qpid.server.security.SecurityManager; @@ -126,6 +123,14 @@ public class Broker String storeLocation = options.getConfigurationStoreLocation(); String storeType = options.getConfigurationStoreType(); + PluggableFactoryLoader<SystemConfigFactory> configFactoryLoader = new PluggableFactoryLoader<>(SystemConfigFactory.class); + SystemConfigFactory configFactory = configFactoryLoader.get(storeType); + if(configFactory == null) + { + LOGGER.fatal("Unknown config store type '"+storeType+"', only the following types are supported: " + configFactoryLoader.getSupportedTypes()); + throw new IllegalArgumentException("Unknown config store type '"+storeType+"', only the following types are supported: " + configFactoryLoader.getSupportedTypes()); + } + _eventLogger.message(BrokerMessages.CONFIG(storeLocation)); //Allow skipping the logging configuration for people who are @@ -138,20 +143,11 @@ public class Broker LogRecorder logRecorder = new LogRecorder(); _taskExecutor.start(); - SystemContext systemContext = new SystemContextImpl(_taskExecutor, _eventLogger, logRecorder, options); - - BrokerConfigurationStoreCreator storeCreator = new BrokerConfigurationStoreCreator(); - DurableConfigurationStore store = storeCreator.createStore(systemContext, storeType, options.getInitialConfigurationLocation(), - options.isOverwriteConfigurationStore(), options.getConfigProperties()); - - if (options.isManagementMode()) - { - store = new ManagementModeStoreHandler(store, options); - } - - store.openConfigurationStore(systemContext); + SystemConfig systemConfig = configFactory.newInstance(_taskExecutor, _eventLogger, logRecorder, options); + systemConfig.open(); + DurableConfigurationStore store = systemConfig.getConfigurationStore(); - _applicationRegistry = new ApplicationRegistry(store,systemContext); + _applicationRegistry = new ApplicationRegistry(store, systemConfig); try { _applicationRegistry.initialise(options); @@ -172,24 +168,6 @@ public class Broker } - public static void parsePortList(Set<Integer> output, List<?> ports) throws InitException - { - if(ports != null) - { - for(Object o : ports) - { - try - { - output.add(Integer.parseInt(String.valueOf(o))); - } - catch (NumberFormatException e) - { - throw new InitException("Invalid port: " + o, e); - } - } - } - } - private void configureLogging(File logConfigFile, int logWatchTime) throws InitException, IOException { _configuringOwnLogging = true; diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/BrokerOptions.java b/java/broker-core/src/main/java/org/apache/qpid/server/BrokerOptions.java index 36d5b95936..fc3ec82041 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/BrokerOptions.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/BrokerOptions.java @@ -27,8 +27,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.qpid.server.configuration.BrokerProperties; -import org.apache.qpid.server.configuration.ConfigurationEntryStore; -import org.apache.qpid.server.configuration.store.MemoryConfigurationEntryStore; +import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.util.StringUtil; public class BrokerOptions @@ -50,7 +49,7 @@ public class BrokerOptions public static final String QPID_HOME_DIR = "qpid.home_dir"; public static final String DEFAULT_INITIAL_CONFIG_NAME = "initial-config.json"; - public static final String DEFAULT_STORE_TYPE = "json"; + public static final String DEFAULT_STORE_TYPE = "JSON"; public static final String DEFAULT_CONFIG_NAME_PREFIX = "config"; public static final String DEFAULT_LOG_CONFIG_FILE = "etc/log4j.xml"; public static final String DEFAULT_INITIAL_CONFIG_LOCATION = @@ -78,6 +77,16 @@ public class BrokerOptions private boolean _overwriteConfigurationStore; private Map<String, String> _configProperties = new HashMap<String,String>(); + public Map<String, Object> convertToSystemAttributes() + { + Map<String,Object> attributes = new HashMap<String, Object>(); + + attributes.put("storePath", getConfigurationStoreLocation()); + attributes.put("storeTye", getConfigurationStoreType()); + attributes.put(ConfiguredObject.CONTEXT, getConfigProperties()); + return attributes; + } + public String getManagementModePassword() { if(_managementModePassword == null) @@ -197,7 +206,7 @@ public class BrokerOptions String workDir = getWorkDir(); String storeType = getConfigurationStoreType(); - return new File(workDir, DEFAULT_CONFIG_NAME_PREFIX + "." + storeType).getAbsolutePath(); + return new File(workDir, DEFAULT_CONFIG_NAME_PREFIX + "." + storeType.toLowerCase()).getAbsolutePath(); } return _configurationStoreLocation; @@ -250,7 +259,7 @@ public class BrokerOptions /** * Set the absolute path or URL to use for the initial JSON configuration, which is loaded with the - * {@link MemoryConfigurationEntryStore} in order to initialise any new {@link ConfigurationEntryStore} for the broker. + * in order to initialise any new store for the broker. * * Passing null clears any previously set value and returns to the default. */ diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreator.java b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreator.java deleted file mode 100644 index dd33d9ab09..0000000000 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreator.java +++ /dev/null @@ -1,83 +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; - -import java.util.Collection; -import java.util.Collections; -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; - -/** - * A helper class responsible for creation and opening of broker store. - */ -public class BrokerConfigurationStoreCreator -{ - private Map<String, ConfigurationStoreFactory> _factories = new HashMap<String, ConfigurationStoreFactory>(); - - public BrokerConfigurationStoreCreator() - { - QpidServiceLoader<ConfigurationStoreFactory> serviceLoader = new QpidServiceLoader<ConfigurationStoreFactory>(); - Iterable<ConfigurationStoreFactory> configurationStoreFactories = serviceLoader - .instancesOf(ConfigurationStoreFactory.class); - for (ConfigurationStoreFactory storeFactory : configurationStoreFactories) - { - String type = storeFactory.getType(); - ConfigurationStoreFactory factory = _factories.put(type.toLowerCase(), storeFactory); - if (factory != null) - { - throw new IllegalStateException("ConfigurationStoreFactory with type name '" + type - + "' is already registered using class '" + factory.getClass().getName() + "', can not register class '" - + storeFactory.getClass().getName() + "'"); - } - } - } - - /** - * Create broker configuration store for a given store location, store type, initial json config 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(SystemContext systemContext, String storeType, String initialConfigLocation, boolean overwrite, Map<String, String> 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(systemContext, initialStore, overwrite, configProperties); - } - - public Collection<String> getStoreTypes() - { - return Collections.unmodifiableCollection(_factories.keySet()); - } -} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryImpl.java b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryImpl.java deleted file mode 100644 index 46fd5e0e0a..0000000000 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryImpl.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; - -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/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreUtil.java b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreUtil.java deleted file mode 100644 index 6d895892b3..0000000000 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreUtil.java +++ /dev/null @@ -1,91 +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.store; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; - -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.util.FileUtils; - -public class ConfigurationEntryStoreUtil -{ - public void copyInitialConfigFile(String initialConfigLocation, File destinationFile) - { - URL initialStoreURL = toURL(initialConfigLocation); - InputStream in = null; - try - { - in = initialStoreURL.openStream(); - FileUtils.copy(in, destinationFile); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot create file " + destinationFile + " by copying initial config from " + initialConfigLocation , e); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot close initial config input stream: " + initialConfigLocation , e); - } - } - } - } - - public URL toURL(String location) - { - URL url = null; - try - { - url = new URL(location); - } - catch (MalformedURLException e) - { - File locationFile = new File(location); - url = fileToURL(locationFile); - } - return url; - } - - protected URL fileToURL(File storeFile) - { - URL storeURL = null; - try - { - storeURL = storeFile.toURI().toURL(); - } - catch (MalformedURLException e) - { - throw new IllegalConfigurationException("Cannot create URL for file " + storeFile, e); - } - return storeURL; - } -} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStore.java b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStore.java deleted file mode 100644 index db8af346a6..0000000000 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStore.java +++ /dev/null @@ -1,153 +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.store; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -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.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(ConfiguredObject<?> parentObject, DurableConfigurationStore initialStore, boolean overwrite, Map<String, String> configProperties) - { - super(parentObject, configProperties); - _parentObject = parentObject; - String storeLocation = (String) parentObject.getAttribute("storePath"); - _storeFile = new File(storeLocation); - - if(_storeFile.isDirectory()) - { - throw new IllegalConfigurationException("A directory exists at the location for the broker configuration store file: " + storeLocation); - } - - if(overwrite && _storeFile.exists()) - { - if(!_storeFile.delete()) - { - throw new StoreException("Unable to overwrite existing configuration store file as requested: " + storeLocation); - } - } - - if ((!_storeFile.exists() || _storeFile.length() == 0)) - { - initialiseStore(_storeFile, initialStore); - } - else - { - load(getConfigurationEntryStoreUtil().fileToURL(_storeFile)); - } - if(isGeneratedObjectIdDuringLoad()) - { - saveAsTree(_storeFile); - } - } - - @Override - public synchronized UUID[] remove(final ConfiguredObjectRecord... records) - { - UUID[] removedIds = super.remove(records); - if (removedIds.length > 0) - { - saveAsTree(_storeFile); - } - return removedIds; - } - - @Override - public synchronized void save(ConfigurationEntry... entries) - { - if (replaceEntries(entries)) - { - saveAsTree(_storeFile); - } - } - - @Override - public String getStoreLocation() - { - return _storeFile.getAbsolutePath(); - } - - @Override - public String getType() - { - return STORE_TYPE; - } - - @Override - public String toString() - { - return "JsonConfigurationEntryStore [_storeFile=" + _storeFile + ", _rootId=" + getRootEntry().getId() + "]"; - } - - private void initialiseStore(File storeFile, DurableConfigurationStore initialStore) - { - createFileIfNotExist(storeFile); - if (initialStore == null) - { - throw new IllegalConfigurationException("Cannot create new store without an initial store"); - } - else - { - final Collection<ConfiguredObjectRecord> records = new ArrayList<ConfiguredObjectRecord>(); - final ConfiguredObjectRecordHandler replayHandler = new ConfiguredObjectRecordHandler() - { - @Override - public void begin() - { - } - - @Override - public boolean handle(ConfiguredObjectRecord record) - { - records.add(record); - return true; - } - - @Override - public void end() - { - } - }; - - initialStore.openConfigurationStore(_parentObject); - initialStore.visitConfiguredObjectRecords(replayHandler); - - update(true, records.toArray(new ConfiguredObjectRecord[records.size()])); - } - } - -} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandler.java b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandler.java index 04ca68efae..2a39cfa642 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandler.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandler.java @@ -59,7 +59,7 @@ public class ManagementModeStoreHandler implements DurableConfigurationStore private final DurableConfigurationStore _store; private Map<UUID, ConfiguredObjectRecord> _cliEntries; - private final Map<UUID, Object> _quiescedEntriesOriginalState; + private Map<UUID, Object> _quiescedEntriesOriginalState; private final BrokerOptions _options; private ConfiguredObject<?> _parent; private HashMap<UUID, ConfiguredObjectRecord> _records; @@ -69,15 +69,18 @@ public class ManagementModeStoreHandler implements DurableConfigurationStore { _options = options; _store = store; - _quiescedEntriesOriginalState = quiesceEntries(options); } @Override - public void openConfigurationStore(final ConfiguredObject<?> parent) + public void openConfigurationStore(final ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) throws StoreException { _parent = parent; - _store.openConfigurationStore(parent); + _store.openConfigurationStore(parent, overwrite, initialRecords); + + _quiescedEntriesOriginalState = quiesceEntries(_options); _records = new HashMap<UUID, ConfiguredObjectRecord>(); @@ -342,7 +345,7 @@ public class ManagementModeStoreHandler implements DurableConfigurationStore attributes.put(Port.AUTHENTICATION_PROVIDER, BrokerAdapter.MANAGEMENT_MODE_AUTHENTICATION); } ConfiguredObjectRecord portEntry = new ConfiguredObjectRecordImpl(UUID.randomUUID(), PORT_TYPE, attributes, - Collections.singletonMap(parent.getType(),parent)); + Collections.singletonMap(parent.getType(),parent.getId())); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Add management mode port configuration " + portEntry + " for port " + port + " and protocol " diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStore.java b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStore.java deleted file mode 100644 index d13fb29c2b..0000000000 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStore.java +++ /dev/null @@ -1,906 +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.store; - -import static org.apache.qpid.server.configuration.ConfigurationEntry.ATTRIBUTE_NAME; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -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.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; - -public class MemoryConfigurationEntryStore implements ConfigurationEntryStore -{ - - public static final String STORE_TYPE = "memory"; - - private static final String DEFAULT_BROKER_NAME = "Broker"; - private static final String ID = "id"; - private static final String TYPE = "@type"; - - static final int STORE_VERSION = 1; - - private final ObjectMapper _objectMapper; - private final Map<UUID, ConfigurationEntry> _entries; - private final Map<String, Class<? extends ConfiguredObject>> _brokerChildrenRelationshipMap; - private final ConfigurationEntryStoreUtil _util = new ConfigurationEntryStoreUtil(); - - private String _storeLocation; - private UUID _rootId; - - private boolean _generatedObjectIdDuringLoad; - - private ConfiguredObject<?> _parent; - - protected MemoryConfigurationEntryStore(ConfiguredObject parentObject, Map<String, String> configProperties) - { - _parent = parentObject; - _objectMapper = new ObjectMapper(); - _objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - _objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); - _entries = new HashMap<UUID, ConfigurationEntry>(); - _brokerChildrenRelationshipMap = buildRelationshipClassMap(); - } - - MemoryConfigurationEntryStore(ConfiguredObject parentObject, String json, Map<String, String> configProperties) - { - this(parentObject, configProperties); - if (json == null || "".equals(json)) - { - createRootEntry(); - } - else - { - loadFromJson(json); - } - } - - public MemoryConfigurationEntryStore(ConfiguredObject parentObject, String initialStoreLocation, ConfigurationEntryStore initialStore, Map<String, String> configProperties) - { - this(parentObject, 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"); - } - if (initialStore != null) - { - if (initialStore instanceof MemoryConfigurationEntryStore) - { - _storeLocation = initialStore.getStoreLocation(); - } - final Collection<ConfiguredObjectRecord> records = new ArrayList<ConfiguredObjectRecord>(); - final ConfiguredObjectRecordHandler replayHandler = new ConfiguredObjectRecordHandler() - { - @Override - public void begin() - { - } - - @Override - public boolean handle(ConfiguredObjectRecord record) - { - records.add(record); - return true; - } - - @Override - public void end() - { - } - }; - - initialStore.openConfigurationStore(parentObject); - initialStore.visitConfiguredObjectRecords(replayHandler); - - update(true, records.toArray(new ConfiguredObjectRecord[records.size()])); - - } - else - { - _storeLocation = initialStoreLocation; - load(_util.toURL(_storeLocation)); - } - } - - - @Override - 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) - { - if (_rootId.equals(uuid)) - { - throw new IllegalConfigurationException("Cannot remove root entry"); - } - } - for (UUID uuid : entryIds) - { - if (removeInternal(uuid)) - { - // remove references to the entry from parent entries - for (ConfigurationEntry entry : _entries.values()) - { - if (entry.hasChild(uuid)) - { - Set<UUID> children = new HashSet<UUID>(entry.getChildrenIds()); - children.remove(uuid); - ConfigurationEntry referral = new ConfigurationEntryImpl(entry.getId(), entry.getType(), - entry.getAttributes(), children, this); - _entries.put(entry.getId(), referral); - } - } - removedIds.add(uuid); - } - } - - return removedIds.toArray(new UUID[removedIds.size()]); - } - - public synchronized void save(ConfigurationEntry... entries) - { - replaceEntries(entries); - } - - public ConfigurationEntry getRootEntry() - { - return getEntry(_rootId); - } - - public synchronized ConfigurationEntry getEntry(UUID id) - { - return _entries.get(id); - } - - /** - * Copies the store into the given location - * - * @param copyLocation location to copy store into - * @throws IllegalConfigurationException if store cannot be copied into given location - */ - public void copyTo(String copyLocation) - { - File file = new File(copyLocation); - if (!file.exists()) - { - createFileIfNotExist(file); - } - saveAsTree(file); - } - - @Override - public String getStoreLocation() - { - return _storeLocation; - } - - @Override - public int getVersion() - { - return STORE_VERSION; - } - - @Override - public String getType() - { - return STORE_TYPE; - } - - @Override - public String toString() - { - 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 openConfigurationStore(final ConfiguredObject<?> parent) - throws StoreException - { - _parent = parent; - } - - @Override - public void upgradeStoreStructure() throws StoreException - { - } - - @Override - public void closeConfigurationStore() throws StoreException - { - } - - @Override - public void onDelete() - { - } - - @Override - public void visitConfiguredObjectRecords(final ConfiguredObjectRecordHandler recoveryHandler) throws StoreException - { - - recoveryHandler.begin(); - - 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; - for (ConfigurationEntry entry : entries) - { - ConfigurationEntry oldEntry = _entries.put(entry.getId(), entry); - if (!entry.equals(oldEntry)) - { - anySaved = true; - } - } - return anySaved; - } - - protected ObjectMapper getObjectMapper() - { - return _objectMapper; - } - - protected void saveAsTree(File file) - { - saveAsTree(_rootId, _entries, _objectMapper, file, STORE_VERSION); - } - - protected void saveAsTree(UUID rootId, Map<UUID, ConfigurationEntry> entries, ObjectMapper mapper, File file, int version) - { - Map<String, Object> tree = toTree(rootId, entries); - tree.put(Broker.STORE_VERSION, version); - try - { - mapper.writeValue(file, tree); - } - catch (JsonGenerationException e) - { - throw new IllegalConfigurationException("Cannot generate json!", e); - } - catch (JsonMappingException e) - { - throw new IllegalConfigurationException("Cannot map objects for json serialization!", e); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot save configuration into " + file + "!", e); - } - } - - protected void load(URL url) - { - InputStream is = null; - try - { - is = url.openStream(); - JsonNode node = loadJsonNodes(is, _objectMapper); - - int storeVersion = 0; - JsonNode storeVersionNode = node.get(Broker.STORE_VERSION); - if (storeVersionNode == null || storeVersionNode.isNull()) - { - throw new IllegalConfigurationException("Broker " + Broker.STORE_VERSION + " attribute must be specified"); - } - else - { - storeVersion = storeVersionNode.getIntValue(); - } - - if (storeVersion != STORE_VERSION) - { - throw new IllegalConfigurationException("The data of version " + storeVersion - + " can not be loaded by store of version " + STORE_VERSION); - } - - ConfigurationEntry brokerEntry = toEntry(node, Broker.class, _entries); - _rootId = brokerEntry.getId(); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot load store from: " + url, e); - } - finally - { - if (is != null) - { - try - { - is.close(); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot close input stream for: " + url, e); - } - - } - } - } - - protected void createFileIfNotExist(File file) - { - File parent = file.getParentFile(); - if (!parent.exists()) - { - if (!parent.mkdirs()) - { - throw new IllegalConfigurationException("Cannot create folders " + parent); - } - } - try - { - file.createNewFile(); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot create file " + file, e); - } - } - - private void loadFromJson(String json) - { - ByteArrayInputStream bais = null; - try - { - byte[] bytes = json.getBytes("UTF-8"); - bais = new ByteArrayInputStream(bytes); - JsonNode node = loadJsonNodes(bais, _objectMapper); - ConfigurationEntry brokerEntry = toEntry(node, Broker.class, _entries); - _rootId = brokerEntry.getId(); - } - catch(Exception e) - { - throw new IllegalConfigurationException("Cannot create store from json:" + json); - } - finally - { - if (bais != null) - { - try - { - bais.close(); - } - catch (IOException e) - { - // ByteArrayInputStream#close() is an empty method - } - } - } - } - - private void createRootEntry() - { - ConfigurationEntry brokerEntry = new ConfigurationEntryImpl(UUIDGenerator.generateRandomUUID(), - Broker.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), this); - _rootId = brokerEntry.getId(); - _entries.put(_rootId, brokerEntry); - } - - private Map<String, Object> toTree(UUID rootId, Map<UUID, ConfigurationEntry> entries) - { - ConfigurationEntry entry = entries.get(rootId); - if (entry == null || !entry.getId().equals(rootId)) - { - throw new IllegalConfigurationException("Cannot find entry with id " + rootId + "!"); - } - Map<String, Object> tree = new TreeMap<String, Object>(); - Map<String, Object> attributes = entry.getAttributes(); - if (attributes != null) - { - tree.putAll(attributes); - } - tree.put(ID, entry.getId()); - Set<UUID> childrenIds = entry.getChildrenIds(); - if (childrenIds != null && !childrenIds.isEmpty()) - { - for (UUID relationship : childrenIds) - { - ConfigurationEntry child = entries.get(relationship); - if (child != null) - { - String relationshipName = child.getType().toLowerCase() + "s"; - - @SuppressWarnings("unchecked") - Collection<Map<String, Object>> children = (Collection<Map<String, Object>>) tree.get(relationshipName); - if (children == null) - { - children = new ArrayList<Map<String, Object>>(); - tree.put(relationshipName, children); - } - Map<String, Object> childAsMap = toTree(relationship, entries); - children.add(childAsMap); - } - } - } - return tree; - } - - private Map<String, Class<? extends ConfiguredObject>> buildRelationshipClassMap() - { - Map<String, Class<? extends ConfiguredObject>> relationships = new HashMap<String, Class<? extends ConfiguredObject>>(); - - Collection<Class<? extends ConfiguredObject>> categories = _parent.getModel().getSupportedCategories(); - for (Class<? extends ConfiguredObject> childClass : categories) - { - String name = childClass.getSimpleName().toLowerCase(); - String relationshipName = name + (name.endsWith("s") ? "es" : "s"); - relationships.put(relationshipName, childClass); - } - return relationships; - } - - private boolean removeInternal(UUID entryId) - { - ConfigurationEntry oldEntry = _entries.remove(entryId); - if (oldEntry != null) - { - Set<UUID> children = oldEntry.getChildrenIds(); - if (children != null && !children.isEmpty()) - { - for (UUID childId : children) - { - removeInternal(childId); - } - } - return true; - } - return false; - } - - private JsonNode loadJsonNodes(InputStream is, ObjectMapper mapper) - { - JsonNode root = null; - try - { - root = mapper.readTree(is); - } - catch (JsonProcessingException e) - { - throw new IllegalConfigurationException("Cannot parse json", e); - } - catch (IOException e) - { - throw new IllegalConfigurationException("Cannot read json", e); - } - return root; - } - - private ConfigurationEntry toEntry(JsonNode parent, Class<? extends ConfiguredObject> expectedConfiguredObjectClass, Map<UUID, ConfigurationEntry> entries) - { - Map<String, Object> attributes = null; - Set<UUID> childrenIds = new TreeSet<UUID>(); - Iterator<String> fieldNames = parent.getFieldNames(); - String type = null; - String idAsString = null; - while (fieldNames.hasNext()) - { - String fieldName = fieldNames.next(); - JsonNode fieldNode = parent.get(fieldName); - if (fieldName.equals(ID)) - { - idAsString = fieldNode.asText(); - } - else if (fieldName.equals(TYPE)) - { - type = fieldNode.asText(); - } - else if (fieldNode.isArray()) - { - // array containing either broker children or attribute values - Iterator<JsonNode> elements = fieldNode.getElements(); - List<Object> fieldValues = null; - while (elements.hasNext()) - { - JsonNode element = elements.next(); - if (element.isObject()) - { - Class<? extends ConfiguredObject> expectedChildConfiguredObjectClass = findExpectedChildConfiguredObjectClass( - fieldName, expectedConfiguredObjectClass); - - // assuming it is a child node - ConfigurationEntry entry = toEntry(element, expectedChildConfiguredObjectClass, entries); - childrenIds.add(entry.getId()); - } - else - { - if (fieldValues == null) - { - fieldValues = new ArrayList<Object>(); - } - fieldValues.add(toObject(element)); - } - } - if (fieldValues != null) - { - Object[] array = fieldValues.toArray(new Object[fieldValues.size()]); - if (attributes == null) - { - attributes = new HashMap<String, Object>(); - } - attributes.put(fieldName, array); - } - } - else if (fieldNode.isObject()) - { - if (attributes == null) - { - attributes = new HashMap<String, Object>(); - } - attributes.put(fieldName, toObject(fieldNode) ); - } - else - { - // primitive attribute - Object value = toObject(fieldNode); - if (attributes == null) - { - attributes = new HashMap<String, Object>(); - } - attributes.put(fieldName, value); - } - } - - if (type == null) - { - if (expectedConfiguredObjectClass == null) - { - throw new IllegalConfigurationException("Type attribute is not provided for configuration entry " + parent); - } - else - { - type = expectedConfiguredObjectClass.getSimpleName(); - } - } - String name = null; - if (attributes != null) - { - name = (String) attributes.get(ATTRIBUTE_NAME); - } - if ((name == null || "".equals(name))) - { - if (expectedConfiguredObjectClass == Broker.class) - { - name = DEFAULT_BROKER_NAME; - } - else - { - throw new IllegalConfigurationException("Name attribute is not provided for configuration entry " + parent); - } - } - UUID id = null; - if (idAsString == null) - { - id = UUID.randomUUID(); - - _generatedObjectIdDuringLoad = true; - } - else - { - try - { - id = UUID.fromString(idAsString); - } - catch (Exception e) - { - throw new IllegalConfigurationException( - "ID attribute value does not conform to UUID format for configuration entry " + parent); - } - } - ConfigurationEntry entry = new ConfigurationEntryImpl(id, type, attributes, childrenIds, this); - if (entries.containsKey(id)) - { - throw new IllegalConfigurationException("Duplicate id is found: " + id - + "! The following configuration entries have the same id: " + entries.get(id) + ", " + entry); - } - entries.put(id, entry); - return entry; - } - - private Class<? extends ConfiguredObject> findExpectedChildConfiguredObjectClass(String parentFieldName, - Class<? extends ConfiguredObject> parentConfiguredObjectClass) - { - return _brokerChildrenRelationshipMap.get(parentFieldName); - } - - private Object toObject(JsonNode node) - { - if (node.isValueNode()) - { - if (node.isBoolean()) - { - return node.asBoolean(); - } - else if (node.isDouble()) - { - return node.asDouble(); - } - else if (node.isInt()) - { - return node.asInt(); - } - else if (node.isLong()) - { - return node.asLong(); - } - else if (node.isNull()) - { - return null; - } - else - { - return node.asText(); - } - } - else if (node.isArray()) - { - return toArray(node); - } - else if (node.isObject()) - { - return toMap(node); - } - else - { - throw new IllegalConfigurationException("Unexpected node: " + node); - } - } - - private Map<String, Object> toMap(JsonNode node) - { - Map<String, Object> object = new TreeMap<String, Object>(); - Iterator<String> fieldNames = node.getFieldNames(); - while (fieldNames.hasNext()) - { - String name = fieldNames.next(); - Object value = toObject(node.get(name)); - object.put(name, value); - } - return object; - } - - private Object toArray(JsonNode node) - { - ArrayNode arrayNode = (ArrayNode) node; - Object[] array = new Object[arrayNode.size()]; - Iterator<JsonNode> elements = arrayNode.getElements(); - for (int i = 0; i < array.length; i++) - { - array[i] = toObject(elements.next()); - } - return array; - } - - protected boolean isGeneratedObjectIdDuringLoad() - { - return _generatedObjectIdDuringLoad; - } - - protected ConfigurationEntryStoreUtil getConfigurationEntryStoreUtil() - { - return _util; - } - -} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/JsonConfigurationStoreFactory.java b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/JsonConfigurationStoreFactory.java deleted file mode 100644 index 930fb5fa23..0000000000 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/JsonConfigurationStoreFactory.java +++ /dev/null @@ -1,45 +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.store.factory; - -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; -import org.apache.qpid.server.plugin.PluggableService; - -@PluggableService -public class JsonConfigurationStoreFactory implements ConfigurationStoreFactory -{ - @Override - public ConfigurationEntryStore createStore(SystemContext systemContext, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties) - { - return new JsonConfigurationEntryStore(systemContext, initialStore, overwrite, configProperties); - } - - @Override - public String getType() - { - return JsonConfigurationEntryStore.STORE_TYPE; - } -} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/MemoryConfigurationStoreFactory.java b/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/MemoryConfigurationStoreFactory.java deleted file mode 100644 index 971e9d08db..0000000000 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/store/factory/MemoryConfigurationStoreFactory.java +++ /dev/null @@ -1,45 +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.store.factory; - -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; -import org.apache.qpid.server.plugin.PluggableService; - -@PluggableService -public class MemoryConfigurationStoreFactory implements ConfigurationStoreFactory -{ - @Override - public ConfigurationEntryStore createStore(SystemContext systemContext, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties) - { - return new MemoryConfigurationEntryStore(systemContext, null, initialStore, configProperties); - } - - @Override - public String getType() - { - return MemoryConfigurationEntryStore.STORE_TYPE; - } -} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObject.java b/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObject.java index 41578272f7..83e2cc06ec 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObject.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractConfiguredObject.java @@ -1045,15 +1045,15 @@ public abstract class AbstractConfiguredObject<X extends ConfiguredObject<X>> im } @Override - public Map<String, ConfiguredObjectRecord> getParents() + public Map<String, UUID> getParents() { - Map<String, ConfiguredObjectRecord> parents = new LinkedHashMap<String, ConfiguredObjectRecord>(); + Map<String, UUID> parents = new LinkedHashMap<>(); for(Class<? extends ConfiguredObject> parentClass : getModel().getParentTypes(getCategoryClass())) { ConfiguredObject parent = getParent(parentClass); if(parent != null) { - parents.put(parentClass.getSimpleName(), parent.asObjectRecord()); + parents.put(parentClass.getSimpleName(), parent.getId()); } } return parents; diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemContextImpl.java b/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractSystemConfig.java index ef4ea8aad7..0f4ecb09dc 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemContextImpl.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/model/AbstractSystemConfig.java @@ -20,6 +20,12 @@ */ package org.apache.qpid.server.model; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.MalformedURLException; +import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -27,47 +33,44 @@ import java.util.UUID; import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.configuration.IllegalConfigurationException; +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.messages.BrokerMessages; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.ConfiguredObjectRecordConverter; +import org.apache.qpid.server.store.DurableConfigurationStore; -public class SystemContextImpl extends AbstractConfiguredObject<SystemContextImpl> implements SystemContext<SystemContextImpl> +public abstract class AbstractSystemConfig<X extends SystemConfig<X>> + extends AbstractConfiguredObject<X> implements SystemConfig<X> { private static final UUID SYSTEM_ID = new UUID(0l, 0l); private final EventLogger _eventLogger; private final LogRecorder _logRecorder; private final BrokerOptions _brokerOptions; - @ManagedAttributeField - private String _storePath; + private DurableConfigurationStore _configurationStore; - @ManagedAttributeField - private String _storeType; - - public SystemContextImpl(final TaskExecutor taskExecutor, - final EventLogger eventLogger, - final LogRecorder logRecorder, - final BrokerOptions brokerOptions) + public AbstractSystemConfig(final TaskExecutor taskExecutor, + final EventLogger eventLogger, + final LogRecorder logRecorder, + final BrokerOptions brokerOptions) { super(parentsMap(), - createAttributes(brokerOptions), + updateAttributes(brokerOptions.convertToSystemAttributes()), taskExecutor, BrokerModel.getInstance()); _eventLogger = eventLogger; getTaskExecutor().start(); _logRecorder = logRecorder; _brokerOptions = brokerOptions; - open(); } - public static Map<String, Object> createAttributes(final BrokerOptions brokerOptions) + private static Map<String, Object> updateAttributes(Map<String, Object> attributes) { - Map<String,Object> attributes = new HashMap<String, Object>(); + attributes = new HashMap<>(attributes); + attributes.put(ConfiguredObject.NAME, "System"); attributes.put(ID, SYSTEM_ID); - attributes.put(NAME, "System"); - attributes.put("storePath", brokerOptions.getConfigurationStoreLocation()); - attributes.put("storeTye", brokerOptions.getConfigurationStoreType()); - attributes.put(ConfiguredObject.CONTEXT, brokerOptions.getConfigProperties()); return attributes; } @@ -101,18 +104,6 @@ public class SystemContextImpl extends AbstractConfiguredObject<SystemContextImp } @Override - public String getStorePath() - { - return _storePath; - } - - @Override - public String getStoreType() - { - return _storeType; - } - - @Override protected void onClose() { try @@ -127,6 +118,8 @@ public class SystemContextImpl extends AbstractConfiguredObject<SystemContextImp _logRecorder.closeLogRecorder(); + _configurationStore.closeConfigurationStore(); + } finally { @@ -152,4 +145,61 @@ public class SystemContextImpl extends AbstractConfiguredObject<SystemContextImp } return children.iterator().next(); } + + @Override + protected void onOpen() + { + super.onOpen(); + _configurationStore = createStoreObject(); + + if (_brokerOptions.isManagementMode()) + { + _configurationStore = new ManagementModeStoreHandler(_configurationStore, _brokerOptions); + } + + try + { + _configurationStore.openConfigurationStore(this, + false, + convertToConfigurationRecords(_brokerOptions.getInitialConfigurationLocation(), + this)); + _configurationStore.upgradeStoreStructure(); + } + catch (IOException e) + { + throw new IllegalArgumentException(e); + } + + } + + abstract protected DurableConfigurationStore createStoreObject(); + + @Override + public DurableConfigurationStore getConfigurationStore() + { + return _configurationStore; + } + + private ConfiguredObjectRecord[] convertToConfigurationRecords(final String initialConfigurationLocation, + final SystemConfig systemConfig) throws IOException + { + ConfiguredObjectRecordConverter converter = new ConfiguredObjectRecordConverter(BrokerModel.getInstance()); + + Reader reader; + try + { + URL url = new URL(initialConfigurationLocation); + reader = new InputStreamReader(url.openStream()); + } + catch (MalformedURLException e) + { + reader = new FileReader(initialConfigurationLocation); + } + + Collection<ConfiguredObjectRecord> records = converter.readFromJson(org.apache.qpid.server.model.Broker.class, + systemConfig, reader); + return records.toArray(new ConfiguredObjectRecord[records.size()]); + + } + } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/model/BrokerModel.java b/java/broker-core/src/main/java/org/apache/qpid/server/model/BrokerModel.java index 20adad0afe..39a40781dd 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/model/BrokerModel.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/model/BrokerModel.java @@ -58,9 +58,9 @@ public final class BrokerModel extends Model private BrokerModel() { - setRootCategory(SystemContext.class); + setRootCategory(SystemConfig.class); - addRelationship(SystemContext.class, Broker.class); + addRelationship(SystemConfig.class, Broker.class); addRelationship(Broker.class, VirtualHostNode.class); addRelationship(Broker.class, Port.class); diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryStore.java b/java/broker-core/src/main/java/org/apache/qpid/server/model/JsonSystemConfig.java index d5f7b3a317..f08604bab3 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/configuration/ConfigurationEntryStore.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/model/JsonSystemConfig.java @@ -18,31 +18,12 @@ * under the License. * */ -package org.apache.qpid.server.configuration; +package org.apache.qpid.server.model; -import org.apache.qpid.server.store.DurableConfigurationStore; +import org.apache.qpid.server.store.FileBasedSettings; -public interface ConfigurationEntryStore extends DurableConfigurationStore +public interface JsonSystemConfig<X extends JsonSystemConfig<X>> extends SystemConfig<X>, FileBasedSettings { - - /** - * Return the store location for the opened store or null if store has not been opened. - * - * @return store location for the opened store or null if store has not been opened - */ - String getStoreLocation(); - - /** - * Returns the version of the store - * - * @return store version - */ - int getVersion(); - - /** - * Returns the type of the store - * - * @return store type - */ - String getType(); + @ManagedAttribute( mandatory = true ) + public String getStorePath(); } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/model/JsonSystemConfigImpl.java b/java/broker-core/src/main/java/org/apache/qpid/server/model/JsonSystemConfigImpl.java new file mode 100644 index 0000000000..1763aca524 --- /dev/null +++ b/java/broker-core/src/main/java/org/apache/qpid/server/model/JsonSystemConfigImpl.java @@ -0,0 +1,55 @@ +/* + * + * 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.store.JsonFileConfigStore; + +@ManagedObject(category = false, type = JsonSystemConfigImpl.SYSTEM_CONFIG_TYPE) +public class JsonSystemConfigImpl extends AbstractSystemConfig<JsonSystemConfigImpl> implements JsonSystemConfig<JsonSystemConfigImpl> +{ + public static final String SYSTEM_CONFIG_TYPE = "JSON"; + + @ManagedAttributeField + private String _storePath; + + @SystemConfigFactoryConstructor + public JsonSystemConfigImpl(final TaskExecutor taskExecutor, + final EventLogger eventLogger, + final LogRecorder logRecorder, + final BrokerOptions brokerOptions) + { + super(taskExecutor, eventLogger, logRecorder, brokerOptions); + } + + public String getStorePath() + { + return _storePath; + } + + protected JsonFileConfigStore createStoreObject() + { + return new JsonFileConfigStore(Broker.class); + } +} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemContext.java b/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemConfig.java index 5649eb0d3d..7943c32c42 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemContext.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/model/SystemConfig.java @@ -23,21 +23,18 @@ package org.apache.qpid.server.model; import org.apache.qpid.server.BrokerOptions; import org.apache.qpid.server.logging.EventLogger; import org.apache.qpid.server.logging.LogRecorder; +import org.apache.qpid.server.store.DurableConfigurationStore; @ManagedObject (creatable = false) -public interface SystemContext<X extends SystemContext<X>> extends ConfiguredObject<X> +public interface SystemConfig<X extends SystemConfig<X>> extends ConfiguredObject<X> { EventLogger getEventLogger(); BrokerOptions getBrokerOptions(); - @ManagedAttribute - String getStorePath(); - - @ManagedAttribute - String getStoreType(); - Broker getBroker(); LogRecorder getLogRecorder(); + + DurableConfigurationStore getConfigurationStore(); } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapter.java b/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapter.java index 651a6a909b..2d8a64b920 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapter.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/model/adapter/BrokerAdapter.java @@ -97,7 +97,7 @@ public class BrokerAdapter extends AbstractConfiguredObject<BrokerAdapter> imple @ManagedObjectFactoryConstructor public BrokerAdapter(Map<String, Object> attributes, - SystemContext parent) + SystemConfig parent) { super(parentsMap(parent), attributes); @@ -675,81 +675,16 @@ public class BrokerAdapter extends AbstractConfiguredObject<BrokerAdapter> imple return true; } - /* @StateTransition(currentState = State.STOPPED, desiredState = State.ACTIVE) - private void restart() - { - initialiseStatisticsReporting(); - changeChildState(State.ACTIVE, false); - if (isManagementMode()) - { - _eventLogger.message(BrokerMessages.MANAGEMENT_MODE(BrokerOptions.MANAGEMENT_MODE_USER_NAME, - _brokerOptions.getManagementModePassword())); - } - _state = State.ACTIVE; - } -*/ @Override protected void onClose() { + if (_reportingTimer != null) { _reportingTimer.cancel(); } - - } -/* - - @StateTransition(currentState = State.ACTIVE, desiredState = State.STOPPED) - private void doStop() - { - changeChildState(State.STOPPED, true); - close(); - _state = State.STOPPED; } -*/ - - /* private void changeChildState(final State desiredState, - final boolean swallowException) - { - runTask(new VoidTask() - { - @Override - public void execute() - { - for (Class<? extends ConfiguredObject> clazz : getModel().getChildTypes(getCategoryClass())) - { - for (ConfiguredObject configuredObject : getChildren(clazz)) - { - if (State.ACTIVE.equals(desiredState) && State.QUIESCED.equals(configuredObject.getState())) - { - if (LOGGER.isDebugEnabled()) - { - LOGGER.debug(configuredObject + " cannot be activated as it is " + State.QUIESCED); - } - continue; - } - try - { - configuredObject.setDesiredState(desiredState); - } - catch (RuntimeException e) - { - if (swallowException) - { - LOGGER.error("Failed to stop " + configuredObject, e); - } - else - { - throw e; - } - } - } - } - } - }); - } -*/ @Override public void stateChanged(ConfiguredObject object, State oldState, State newState) { @@ -1078,6 +1013,8 @@ public class BrokerAdapter extends AbstractConfiguredObject<BrokerAdapter> imple } } + + public AuthenticationProvider<?> getManagementModeAuthenticationProvider() { return _managementModeAuthenticationProvider; diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfigurationStoreFactory.java b/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfigurationStoreFactory.java deleted file mode 100644 index eb3884d59e..0000000000 --- a/java/broker-core/src/main/java/org/apache/qpid/server/plugin/ConfigurationStoreFactory.java +++ /dev/null @@ -1,49 +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.plugin; - -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 -{ - /** - * Returns the type of the store this factory can create - */ - public String getType(); - - /** - * Creates and opens the store from a given location using initial store if provided. - * <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 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(SystemContext systemContext, ConfigurationEntryStore initialStore, boolean overwrite, Map<String, String> configProperties); -} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/plugin/SystemConfigFactory.java b/java/broker-core/src/main/java/org/apache/qpid/server/plugin/SystemConfigFactory.java new file mode 100644 index 0000000000..9162f9e095 --- /dev/null +++ b/java/broker-core/src/main/java/org/apache/qpid/server/plugin/SystemConfigFactory.java @@ -0,0 +1,35 @@ +/* + * + * 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.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.model.SystemConfig; + +public interface SystemConfigFactory<X extends SystemConfig<X>> extends Pluggable +{ + public X newInstance(final TaskExecutor taskExecutor, + final EventLogger eventLogger, + final LogRecorder logRecorder, + final BrokerOptions brokerOptions); +} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java b/java/broker-core/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java index 663d06eb39..9711250bd7 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java @@ -32,7 +32,7 @@ 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.model.Broker; -import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.store.BrokerStoreUpgraderAndRecoverer; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.util.SystemUtils; @@ -48,16 +48,16 @@ public class ApplicationRegistry implements IApplicationRegistry { private static final Logger _logger = Logger.getLogger(ApplicationRegistry.class); - private final SystemContext _systemContext; + private final SystemConfig _systemConfig; private Broker _broker; private DurableConfigurationStore _store; - public ApplicationRegistry(DurableConfigurationStore store, SystemContext systemContext) + public ApplicationRegistry(DurableConfigurationStore store, SystemConfig systemConfig) { _store = store; - _systemContext = systemContext; + _systemConfig = systemConfig; } public void initialise(BrokerOptions brokerOptions) throws Exception @@ -65,7 +65,7 @@ public class ApplicationRegistry implements IApplicationRegistry // Create the RootLogger to be used during broker operation boolean statusUpdatesEnabled = Boolean.parseBoolean(System.getProperty(BrokerProperties.PROPERTY_STATUS_UPDATES, "true")); MessageLogger messageLogger = new Log4jMessageLogger(statusUpdatesEnabled); - final EventLogger eventLogger = _systemContext.getEventLogger(); + final EventLogger eventLogger = _systemConfig.getEventLogger(); eventLogger.setMessageLogger(messageLogger); //Create the composite (log4j+SystemOut MessageLogger to be used during startup @@ -76,7 +76,7 @@ public class ApplicationRegistry implements IApplicationRegistry logStartupMessages(startupLogger); - BrokerStoreUpgraderAndRecoverer upgrader = new BrokerStoreUpgraderAndRecoverer(_systemContext); + BrokerStoreUpgraderAndRecoverer upgrader = new BrokerStoreUpgraderAndRecoverer(_systemConfig); _broker = upgrader.perform(_store); _broker.setEventLogger(startupLogger); @@ -96,7 +96,6 @@ public class ApplicationRegistry implements IApplicationRegistry { _logger.info("Shutting down ApplicationRegistry:" + this); } - try { if (_broker != null) @@ -106,7 +105,7 @@ public class ApplicationRegistry implements IApplicationRegistry } finally { - _systemContext.close(); + _systemConfig.close(); } _store = null; _broker = null; diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractJDBCConfigurationStore.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractJDBCConfigurationStore.java index fc43bfb6f7..b3d0428bb3 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractJDBCConfigurationStore.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractJDBCConfigurationStore.java @@ -311,8 +311,7 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv PreparedStatement stmt = connection.prepareStatement(SELECT_FROM_CONFIGURED_OBJECTS); try { - ResultSet rs = stmt.executeQuery(); - try + try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { @@ -322,38 +321,26 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv { continue; } - Map<String,Object> attributes = objectMapper.readValue(getBlobAsString(rs, 3),Map.class); + Map<String, Object> attributes = objectMapper.readValue(getBlobAsString(rs, 3), Map.class); - if(objectType.endsWith("Binding")) + if (objectType.endsWith("Binding")) { - bindingsToUpdate.put(id,attributes); + bindingsToUpdate.put(id, attributes); } else { if (objectType.equals("Exchange")) { - defaultExchanges.remove((String)attributes.get("name")); + defaultExchanges.remove((String) attributes.get("name")); } others.add(id); } } } - catch (JsonMappingException e) - { - throw new StoreException("Error recovering persistent state: " + e.getMessage(), e); - } - catch (JsonParseException e) - { - throw new StoreException("Error recovering persistent state: " + e.getMessage(), e); - } catch (IOException e) { throw new StoreException("Error recovering persistent state: " + e.getMessage(), e); } - finally - { - rs.close(); - } } finally { @@ -395,7 +382,7 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv exchangeAttributes.put("name", defaultExchangeEntry.getKey()); exchangeAttributes.put("type", defaultExchangeEntry.getValue()); exchangeAttributes.put("lifetimePolicy", "PERMANENT"); - Map<String, ConfiguredObjectRecord> parents = Collections.singletonMap("VirtualHost", virtualHostRecord); + Map<String, UUID> parents = Collections.singletonMap("VirtualHost", virtualHostRecord.getId()); ConfiguredObjectRecord exchangeRecord = new org.apache.qpid.server.store.ConfiguredObjectRecordImpl(id, "Exchange", exchangeAttributes, parents); insertConfiguredObject(exchangeRecord, connection); } @@ -414,14 +401,6 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv stmt.execute(); } } - catch (JsonMappingException e) - { - throw new StoreException("Error recovering persistent state: " + e.getMessage(), e); - } - catch (JsonGenerationException e) - { - throw new StoreException("Error recovering persistent state: " + e.getMessage(), e); - } catch (IOException e) { throw new StoreException("Error recovering persistent state: " + e.getMessage(), e); @@ -464,15 +443,15 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv protected abstract String getSqlBigIntType(); - protected void createOrOpenConfigurationStoreDatabase() throws StoreException + protected void createOrOpenConfigurationStoreDatabase(final boolean clear) throws StoreException { Connection conn = null; try { conn = newAutoCommitConnection(); - createConfiguredObjectsTable(conn); - createConfiguredObjectHierarchyTable(conn); + createConfiguredObjectsTable(conn, clear); + createConfiguredObjectHierarchyTable(conn, clear); } catch (SQLException e) { @@ -500,36 +479,43 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv } } - private void createConfiguredObjectsTable(final Connection conn) throws SQLException + private void createConfiguredObjectsTable(final Connection conn, final boolean clear) throws SQLException { if(!tableExists(CONFIGURED_OBJECTS_TABLE_NAME, conn)) { - Statement stmt = conn.createStatement(); - try + try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE " + CONFIGURED_OBJECTS_TABLE_NAME - + " ( id VARCHAR(36) not null, object_type varchar(255), attributes "+getSqlBlobType()+", PRIMARY KEY (id))"); + stmt.execute("CREATE TABLE " + + CONFIGURED_OBJECTS_TABLE_NAME + + " ( id VARCHAR(36) not null, object_type varchar(255), attributes " + + getSqlBlobType() + + ", PRIMARY KEY (id))"); } - finally + } + else if(clear) + { + try (Statement stmt = conn.createStatement()) { - stmt.close(); + stmt.execute("DELETE FROM " + CONFIGURED_OBJECTS_TABLE_NAME); } } } - private void createConfiguredObjectHierarchyTable(final Connection conn) throws SQLException + private void createConfiguredObjectHierarchyTable(final Connection conn, final boolean clear) throws SQLException { if(!tableExists(CONFIGURED_OBJECT_HIERARCHY_TABLE_NAME, conn)) { - Statement stmt = conn.createStatement(); - try + try (Statement stmt = conn.createStatement()) { stmt.execute("CREATE TABLE " + CONFIGURED_OBJECT_HIERARCHY_TABLE_NAME + " ( child_id VARCHAR(36) not null, parent_type varchar(255), parent_id VARCHAR(36), PRIMARY KEY (child_id, parent_type))"); } - finally + } + else if(clear) + { + try (Statement stmt = conn.createStatement()) { - stmt.close(); + stmt.execute("DELETE FROM " + CONFIGURED_OBJECT_HIERARCHY_TABLE_NAME); } } } @@ -643,6 +629,14 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv return connection; } + protected boolean hasNoConfigurationEntries() + { + ConfiguredObjectRecordPresenceDetector recordPresenceDetector = new ConfiguredObjectRecordPresenceDetector(); + visitConfiguredObjectRecords(recordPresenceDetector); + + return !recordPresenceDetector.isRecordsPresent(); + } + protected abstract Connection getConnection() throws SQLException; private void insertConfiguredObject(ConfiguredObjectRecord configuredObject, final Connection conn) throws StoreException @@ -900,11 +894,11 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv PreparedStatement insertStmt = conn.prepareStatement(INSERT_INTO_CONFIGURED_OBJECT_HIERARCHY); try { - for(Map.Entry<String,ConfiguredObjectRecord> parentEntry : configuredObject.getParents().entrySet()) + for(Map.Entry<String,UUID> parentEntry : configuredObject.getParents().entrySet()) { insertStmt.setString(1, configuredObject.getId().toString()); insertStmt.setString(2, parentEntry.getKey()); - insertStmt.setString(3, parentEntry.getValue().getId().toString()); + insertStmt.setString(3, parentEntry.getValue().toString()); insertStmt.execute(); } @@ -963,7 +957,7 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv private final UUID _id; private final String _type; private final Map<String, Object> _attributes; - private final Map<String, ConfiguredObjectRecord> _parents = new HashMap<String, ConfiguredObjectRecord>(); + private final Map<String, UUID> _parents = new HashMap<>(); private ConfiguredObjectRecordImpl(final UUID id, final String type, @@ -988,7 +982,7 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv private void addParent(String parentType, ConfiguredObjectRecord parent) { - _parents.put(parentType, parent); + _parents.put(parentType, parent.getId()); } @Override @@ -998,7 +992,7 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv } @Override - public Map<String, ConfiguredObjectRecord> getParents() + public Map<String, UUID> getParents() { return Collections.unmodifiableMap(_parents); } @@ -1010,4 +1004,33 @@ public abstract class AbstractJDBCConfigurationStore implements MessageStoreProv + _parents + "]"; } } + + private static class ConfiguredObjectRecordPresenceDetector implements ConfiguredObjectRecordHandler + { + private boolean _recordsPresent; + + @Override + public void begin() + { + + } + + @Override + public boolean handle(final ConfiguredObjectRecord record) + { + _recordsPresent = true; + return false; + } + + @Override + public void end() + { + + } + + public boolean isRecordsPresent() + { + return _recordsPresent; + } + } } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractMemoryStore.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractMemoryStore.java index 92184e9b81..4d5cb84d04 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractMemoryStore.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/AbstractMemoryStore.java @@ -28,13 +28,19 @@ import java.util.concurrent.ConcurrentHashMap; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; -abstract class AbstractMemoryStore implements DurableConfigurationStore, MessageStoreProvider +public abstract class AbstractMemoryStore implements DurableConfigurationStore, MessageStoreProvider { private final MessageStore _messageStore = new MemoryMessageStore(); + private final Class<? extends ConfiguredObject> _rootClass; private final ConcurrentHashMap<UUID, ConfiguredObjectRecord> _configuredObjectRecords = new ConcurrentHashMap<UUID, ConfiguredObjectRecord>(); + protected AbstractMemoryStore(final Class<? extends ConfiguredObject> rootClass) + { + _rootClass = rootClass; + } + @Override public void create(ConfiguredObjectRecord record) { @@ -49,10 +55,17 @@ abstract class AbstractMemoryStore implements DurableConfigurationStore, Message { for (ConfiguredObjectRecord record : records) { - ConfiguredObjectRecord previousValue = _configuredObjectRecords.replace(record.getId(), record); - if (previousValue == null && !createIfNecessary) + if(createIfNecessary) { - throw new StoreException("Record with id " + record.getId() + " does not exist"); + _configuredObjectRecords.put(record.getId(), record); + } + else + { + ConfiguredObjectRecord previousValue = _configuredObjectRecords.replace(record.getId(), record); + if (previousValue == null) + { + throw new StoreException("Record with id " + record.getId() + " does not exist"); + } } } } @@ -72,8 +85,14 @@ abstract class AbstractMemoryStore implements DurableConfigurationStore, Message } @Override - public void openConfigurationStore(ConfiguredObject<?> parent) + public void openConfigurationStore(ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) { + for(ConfiguredObjectRecord record : initialRecords) + { + _configuredObjectRecords.put(record.getId(), record); + } } @Override diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/BrokerStoreUpgraderAndRecoverer.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/BrokerStoreUpgraderAndRecoverer.java index 6f53c1601d..15a2a3cbbd 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/BrokerStoreUpgraderAndRecoverer.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/BrokerStoreUpgraderAndRecoverer.java @@ -31,19 +31,19 @@ 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.ConfiguredObject; -import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.util.Action; public class BrokerStoreUpgraderAndRecoverer { - private final SystemContext<?> _systemContext; + private final SystemConfig<?> _systemConfig; private final Map<String, StoreUpgraderPhase> _upgraders = new HashMap<String, StoreUpgraderPhase>(); // 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 - public BrokerStoreUpgraderAndRecoverer(SystemContext<?> systemContext) + public BrokerStoreUpgraderAndRecoverer(SystemConfig<?> systemConfig) { - _systemContext = systemContext; + _systemConfig = systemConfig; register(new Upgrader_1_0_to_1_1()); register(new Upgrader_1_1_to_1_2()); @@ -477,10 +477,10 @@ public class BrokerStoreUpgraderAndRecoverer public Broker<?> perform(final DurableConfigurationStore store) { List<ConfiguredObjectRecord> upgradedRecords = upgrade(store); - new GenericRecoverer(_systemContext, Broker.class.getSimpleName()).recover(upgradedRecords); + new GenericRecoverer(_systemConfig, Broker.class.getSimpleName()).recover(upgradedRecords); final StoreConfigurationChangeListener configChangeListener = new StoreConfigurationChangeListener(store); - applyRecursively(_systemContext.getBroker(), new Action<ConfiguredObject<?>>() + applyRecursively(_systemConfig.getBroker(), new Action<ConfiguredObject<?>>() { @Override public void performAction(final ConfiguredObject<?> object) @@ -489,7 +489,7 @@ public class BrokerStoreUpgraderAndRecoverer } }); - return _systemContext.getBroker(); + return _systemConfig.getBroker(); } List<ConfiguredObjectRecord> upgrade(final DurableConfigurationStore store) diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecord.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecord.java index 99f8f0f04a..ca21a3329c 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecord.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecord.java @@ -31,5 +31,5 @@ public interface ConfiguredObjectRecord Map<String,Object> getAttributes(); - Map<String, ConfiguredObjectRecord> getParents(); + Map<String, UUID> getParents(); } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecordConverter.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecordConverter.java new file mode 100644 index 0000000000..cc284a33f4 --- /dev/null +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecordConverter.java @@ -0,0 +1,123 @@ +/* + * + * 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 java.io.IOException; +import java.io.Reader; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.map.ObjectMapper; + +import org.apache.qpid.server.model.ConfiguredObject; +import org.apache.qpid.server.model.Model; + +public class ConfiguredObjectRecordConverter +{ + private final Model _model; + + public ConfiguredObjectRecordConverter(final Model model) + { + _model = model; + } + + public Collection<ConfiguredObjectRecord> readFromJson(final Class<? extends ConfiguredObject> rootClass, + final ConfiguredObject<?> parent, final Reader reader) throws IOException + { + Map<UUID, ConfiguredObjectRecord> objectsById = new HashMap<>(); + + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); + Map data = objectMapper.readValue(reader, Map.class); + if(!data.isEmpty()) + { + loadChild(rootClass, data, parent.getCategoryClass(), parent.getId(), objectsById); + } + return objectsById.values(); + } + + + private void loadChild(final Class<? extends ConfiguredObject> clazz, + final Map<String, Object> data, + final Class<? extends ConfiguredObject> parentClass, + final UUID parentId, final Map<UUID, ConfiguredObjectRecord> records) + { + String idStr = (String) data.remove("id"); + + final UUID id = idStr == null ? UUID.randomUUID() : UUID.fromString(idStr); + final String type = clazz.getSimpleName(); + Map<String,UUID> parentMap = new HashMap<>(); + + Collection<Class<? extends ConfiguredObject>> childClasses = _model.getChildTypes(clazz); + for(Class<? extends ConfiguredObject> childClass : childClasses) + { + final String childType = childClass.getSimpleName(); + String attrName = childType.toLowerCase() + "s"; + Object children = data.remove(attrName); + if(children != null) + { + if(children instanceof Collection) + { + for(Object child : (Collection)children) + { + if(child instanceof Map) + { + loadChild(childClass, (Map)child, clazz, id, records); + } + } + } + } + + } + if(parentId != null) + { + parentMap.put(parentClass.getSimpleName(),parentId); + for(Class<? extends ConfiguredObject> otherParent : _model.getParentTypes(clazz)) + { + if(otherParent != parentClass) + { + final String otherParentAttr = otherParent.getSimpleName().toLowerCase(); + Object otherParentId = data.remove(otherParentAttr); + if(otherParentId instanceof String) + { + try + { + parentMap.put(otherParent.getSimpleName(), UUID.fromString((String) otherParentId)); + } + catch(IllegalArgumentException e) + { + // TODO + } + } + } + + } + } + + records.put(id, new ConfiguredObjectRecordImpl(id, type, data, parentMap)); + + } + + +} diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecordImpl.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecordImpl.java index ed553aa823..2d1b08aa50 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecordImpl.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/ConfiguredObjectRecordImpl.java @@ -30,20 +30,26 @@ public class ConfiguredObjectRecordImpl implements ConfiguredObjectRecord private UUID _id; private String _type; private final Map<String,Object> _attributes; - private final Map<String,ConfiguredObjectRecord> _parents; + private final Map<String,UUID> _parents; + + + public ConfiguredObjectRecordImpl(ConfiguredObjectRecord record) + { + this(record.getId(), record.getType(), record.getAttributes(), record.getParents()); + } public ConfiguredObjectRecordImpl(UUID id, String type, Map<String, Object> attributes) { - this(id,type,attributes,Collections.<String,ConfiguredObjectRecord>emptyMap()); + this(id,type,attributes,Collections.<String,UUID>emptyMap()); } - public ConfiguredObjectRecordImpl(UUID id, String type, Map<String, Object> attributes, Map<String,ConfiguredObjectRecord> parents) + public ConfiguredObjectRecordImpl(UUID id, String type, Map<String, Object> attributes, Map<String,UUID> parents) { super(); _id = id; _type = type; - _attributes = Collections.unmodifiableMap(new LinkedHashMap<String,Object>(attributes)); - _parents = Collections.unmodifiableMap(new LinkedHashMap<String, ConfiguredObjectRecord>(parents)); + _attributes = Collections.unmodifiableMap(new LinkedHashMap<>(attributes)); + _parents = Collections.unmodifiableMap(new LinkedHashMap<>(parents)); } @Override @@ -65,7 +71,7 @@ public class ConfiguredObjectRecordImpl implements ConfiguredObjectRecord } @Override - public Map<String, ConfiguredObjectRecord> getParents() + public Map<String, UUID> getParents() { return _parents; } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java index 1efd415e6a..588edd9cab 100755 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.server.store; -import java.util.Map; import java.util.UUID; import org.apache.qpid.server.model.ConfiguredObject; @@ -30,10 +29,14 @@ public interface DurableConfigurationStore { /** * Initializes and opens the configuration store. - * @param parent + * @param parent + * @param overwrite + * @param initialRecords * */ - void openConfigurationStore(ConfiguredObject<?> parent) throws StoreException; + void openConfigurationStore(ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) throws StoreException; /** * Requests that the store performs any upgrade work on the store's structure. If there is no diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/GenericRecoverer.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/GenericRecoverer.java index 38492310b5..f281c58c79 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/GenericRecoverer.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/GenericRecoverer.java @@ -93,8 +93,7 @@ public class GenericRecoverer records = new ArrayList<ConfiguredObjectRecord>(records); String parentOfRootCategory = _parentOfRoot.getCategoryClass().getSimpleName(); - ConfiguredObjectRecord parentRecord = new ConfiguredObjectRecordImpl(_parentOfRoot.getId(), parentOfRootCategory, Collections.<String, Object>emptyMap()); - Map<String, ConfiguredObjectRecord> rootParents = Collections.<String, ConfiguredObjectRecord>singletonMap(parentOfRootCategory, parentRecord); + Map<String, UUID> rootParents = Collections.singletonMap(parentOfRootCategory, _parentOfRoot.getId()); records.remove(rootRecord); records.add(new ConfiguredObjectRecordImpl(rootRecord.getId(), _rootCategory, rootRecord.getAttributes(), rootParents)); } @@ -124,16 +123,16 @@ public class GenericRecoverer ConfiguredObjectRecord record = iter.next(); Collection<ConfiguredObject<?>> parents = new ArrayList<ConfiguredObject<?>>(); boolean foundParents = true; - for (ConfiguredObjectRecord parent : record.getParents().values()) + for (UUID parentId : record.getParents().values()) { - if (!resolvedObjects.containsKey(parent.getId())) + if (!resolvedObjects.containsKey(parentId)) { foundParents = false; break; } else { - parents.add(resolvedObjects.get(parent.getId())); + parents.add(resolvedObjects.get(parentId)); } } if (foundParents) diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/JsonFileConfigStore.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/JsonFileConfigStore.java index 7a0f57bd33..615ee7485e 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/JsonFileConfigStore.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/JsonFileConfigStore.java @@ -22,11 +22,13 @@ package org.apache.qpid.server.store; import java.io.File; import java.io.FileOutputStream; +import java.io.FileReader; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -36,11 +38,10 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import org.apache.log4j.Logger; import org.codehaus.jackson.JsonGenerator; -import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.Version; -import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.JsonSerializer; import org.codehaus.jackson.map.Module; import org.codehaus.jackson.map.ObjectMapper; @@ -50,11 +51,12 @@ import org.codehaus.jackson.map.module.SimpleModule; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.Model; -import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; public class JsonFileConfigStore implements DurableConfigurationStore { + private static final Logger _logger = Logger.getLogger(JsonFileConfigStore.class); + private final Map<UUID, ConfiguredObjectRecord> _objectsById = new HashMap<UUID, ConfiguredObjectRecord>(); private final Map<String, List<UUID>> _idsByType = new HashMap<String, List<UUID>>(); private final ObjectMapper _objectMapper = new ObjectMapper(); @@ -66,6 +68,7 @@ public class JsonFileConfigStore implements DurableConfigurationStore private FileLock _fileLock; private String _configFileName; private String _backupFileName; + private String _lockFileName; private static final Module _module; static @@ -90,11 +93,6 @@ public class JsonFileConfigStore implements DurableConfigurationStore private ConfiguredObject<?> _parent; - public JsonFileConfigStore() - { - this(VirtualHost.class); - } - public JsonFileConfigStore(Class<? extends ConfiguredObject> rootClass) { _objectMapper.registerModule(_module); @@ -109,14 +107,16 @@ public class JsonFileConfigStore implements DurableConfigurationStore } @Override - public void openConfigurationStore(ConfiguredObject<?> parent) + public void openConfigurationStore(ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) { _parent = parent; _name = parent.getName(); _classNameMapping = generateClassNameMap(_parent.getModel(), _rootClass); FileBasedSettings fileBasedSettings = (FileBasedSettings)_parent; setup(fileBasedSettings); - load(); + load(overwrite, initialRecords); } @Override @@ -142,9 +142,23 @@ public class JsonFileConfigStore implements DurableConfigurationStore { throw new StoreException("Cannot determine path for configuration storage"); } - _directoryName = configurationStoreSettings.getStorePath(); - _configFileName = _name + ".json"; - _backupFileName = _name + ".bak"; + File fileFromSettings = new File(configurationStoreSettings.getStorePath()); + if(fileFromSettings.isFile() || (!fileFromSettings.exists() && (new File(fileFromSettings.getParent())).isDirectory())) + { + _directoryName = fileFromSettings.getParent(); + _configFileName = fileFromSettings.getName(); + _backupFileName = fileFromSettings.getName() + ".bak"; + _lockFileName = fileFromSettings.getName() + ".lck"; + } + else + { + _directoryName = configurationStoreSettings.getStorePath(); + _configFileName = _name + ".json"; + _backupFileName = _name + ".bak"; + _lockFileName = _name + ".lck"; + } + + checkDirectoryIsWritable(_directoryName); getFileLock(); @@ -195,7 +209,7 @@ public class JsonFileConfigStore implements DurableConfigurationStore private void getFileLock() { - File lockFile = new File(_directoryName, _name + ".lck"); + File lockFile = new File(_directoryName, _lockFileName); try { lockFile.createNewFile(); @@ -245,102 +259,47 @@ public class JsonFileConfigStore implements DurableConfigurationStore } } - protected void load() + protected void load(final boolean overwrite, final ConfiguredObjectRecord[] initialRecords) { final File configFile = new File(_directoryName, _configFileName); try { - Map data = _objectMapper.readValue(configFile,Map.class); - loadFromMap(data); - } - catch (JsonMappingException e) - { - throw new StoreException("Cannot parse the configuration file " + configFile, e); - } - catch (JsonParseException e) - { - throw new StoreException("Cannot parse the configuration file " + configFile, e); - } - catch (IOException e) - { - throw new StoreException("Could not load the configuration file " + configFile, e); - } - - } - - protected void loadFromMap(final Map<String,Object> data) - { - if (!data.isEmpty()) - { - loadChild(_rootClass, data, null, null); - } - } - + boolean updated = false; + Collection<ConfiguredObjectRecord> records = Collections.emptyList(); + if(!overwrite) + { + ConfiguredObjectRecordConverter configuredObjectRecordConverter = + new ConfiguredObjectRecordConverter(_parent.getModel()); - private void loadChild(final Class<? extends ConfiguredObject> clazz, - final Map<String,Object> data, - final Class<? extends ConfiguredObject> parentClass, - final UUID parentId) - { - String idStr = (String) data.remove("id"); - final UUID id = UUID.fromString(idStr); - final String type = clazz.getSimpleName(); - Map<String,UUID> parentMap = new HashMap<String, UUID>(); + records = configuredObjectRecordConverter.readFromJson(_rootClass, _parent, new FileReader(configFile)); + } - Collection<Class<? extends ConfiguredObject>> childClasses = _parent.getModel().getChildTypes(clazz); - for(Class<? extends ConfiguredObject> childClass : childClasses) - { - final String childType = childClass.getSimpleName(); - String attrName = childType.toLowerCase() + "s"; - Object children = data.remove(attrName); - if(children != null) + if(records.isEmpty()) { - if(children instanceof Collection) - { - for(Object child : (Collection)children) - { - if(child instanceof Map) - { - loadChild(childClass, (Map)child, clazz, id); - } - } - } + records = Arrays.asList(initialRecords); + updated = true; } - } - if(parentId != null) - { - parentMap.put(parentClass.getSimpleName(),parentId); - for(Class<? extends ConfiguredObject> otherParent : _parent.getModel().getParentTypes(clazz)) + for(ConfiguredObjectRecord record : records) { - if(otherParent != parentClass) + _objectsById.put(record.getId(), record); + List<UUID> idsForType = _idsByType.get(record.getType()); + if (idsForType == null) { - final String otherParentAttr = otherParent.getSimpleName().toLowerCase(); - Object otherParentId = data.remove(otherParentAttr); - if(otherParentId instanceof String) - { - try - { - parentMap.put(otherParent.getSimpleName(), UUID.fromString((String) otherParentId)); - } - catch(IllegalArgumentException e) - { - // - } - } + idsForType = new ArrayList<>(); + _idsByType.put(record.getType(), idsForType); } - + idsForType.add(record.getId()); + } + if(updated) + { + save(); } } - - _objectsById.put(id, new ConfiguredObjectRecordImpl(id, type, data, parentMap)); - List<UUID> idsForType = _idsByType.get(type); - if(idsForType == null) + catch (IOException e) { - idsForType = new ArrayList<UUID>(); - _idsByType.put(type, idsForType); + throw new StoreException("Cannot construct configuration from the configuration file " + configFile, e); } - idsForType.add(id); } @Override @@ -440,7 +399,7 @@ public class JsonFileConfigStore implements DurableConfigurationStore while(iter.hasNext()) { String parentType = iter.next().getSimpleName(); - map.put(parentType.toLowerCase(), record.getParents().get(parentType).getId()); + map.put(parentType.toLowerCase(), record.getParents().get(parentType)); } } @@ -461,8 +420,8 @@ public class JsonFileConfigStore implements DurableConfigurationStore { ConfiguredObjectRecord childRecord = _objectsById.get(childId); - final ConfiguredObjectRecord parent = childRecord.getParents().get(type.getSimpleName()); - String parentId = parent.getId().toString(); + final UUID parent = childRecord.getParents().get(type.getSimpleName()); + String parentId = parent.toString(); if(id.toString().equals(parentId)) { entities.add(build(childClass,childId)); @@ -558,6 +517,7 @@ public class JsonFileConfigStore implements DurableConfigurationStore @Override public void closeConfigurationStore() { + _logger.info("Close Config Store called", new Exception()); try { releaseFileLock(); @@ -616,87 +576,4 @@ public class JsonFileConfigStore implements DurableConfigurationStore return map; } - private class ConfiguredObjectRecordImpl implements ConfiguredObjectRecord - { - - private final UUID _id; - private final String _type; - private final Map<String, Object> _attributes; - private final Map<String, UUID> _parents; - - private ConfiguredObjectRecordImpl(ConfiguredObjectRecord record) - { - this(record.getId(), record.getType(), record.getAttributes(), convertParents(record.getParents())); - } - - private ConfiguredObjectRecordImpl(final UUID id, final String type, final Map<String, Object> attributes, - final Map<String, UUID> parents) - { - _id = id; - _type = type; - _attributes = attributes; - _parents = parents; - } - - @Override - public UUID getId() - { - return _id; - } - - @Override - public String getType() - { - return _type; - } - - @Override - public Map<String, Object> getAttributes() - { - return _attributes; - } - - @Override - public Map<String, ConfiguredObjectRecord> getParents() - { - Map<String,ConfiguredObjectRecord> parents = new HashMap<String, ConfiguredObjectRecord>(); - for(Map.Entry<String,UUID> entry : _parents.entrySet()) - { - ConfiguredObjectRecord value = _objectsById.get(entry.getValue()); - - if(value == null && entry.getKey().equals("Exchange")) - { - // TODO - remove this hack for the defined exchanges - value = new ConfiguredObjectRecordImpl(entry.getValue(),entry.getKey(),Collections.<String,Object>emptyMap(), Collections.<String,UUID>emptyMap()); - } - - parents.put(entry.getKey(), value); - } - return parents; - } - - @Override - public String toString() - { - return "ConfiguredObjectRecordImpl [_id=" + _id + ", _type=" + _type + ", _attributes=" + _attributes + ", _parents=" - + _parents + "]"; - } - - } - - private static Map<String, UUID> convertParents(final Map<String, ConfiguredObjectRecord> parents) - { - if(parents == null || parents.isEmpty()) - { - return Collections.emptyMap(); - } - Map<String,UUID> parentMap = new HashMap<>(); - for(Map.Entry<String,ConfiguredObjectRecord> entry : parents.entrySet()) - { - parentMap.put(entry.getKey(), entry.getValue().getId()); - } - return parentMap; - } - - } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/NullMessageStore.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/NullMessageStore.java index 15bf13bcab..66975e1189 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/NullMessageStore.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/NullMessageStore.java @@ -36,7 +36,9 @@ public abstract class NullMessageStore implements MessageStore, DurableConfigura } @Override - public void openConfigurationStore(ConfiguredObject<?> parent) + public void openConfigurationStore(ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) { } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/store/VirtualHostStoreUpgraderAndRecoverer.java b/java/broker-core/src/main/java/org/apache/qpid/server/store/VirtualHostStoreUpgraderAndRecoverer.java index a88d647ba7..cbd3f0962e 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/store/VirtualHostStoreUpgraderAndRecoverer.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/store/VirtualHostStoreUpgraderAndRecoverer.java @@ -107,12 +107,11 @@ public class VirtualHostStoreUpgraderAndRecoverer private boolean isTopicExchange(ConfiguredObjectRecord entry) { - ConfiguredObjectRecord exchangeRecord = entry.getParents().get("Exchange"); - if (exchangeRecord == null) + UUID exchangeId = entry.getParents().get("Exchange"); + if (exchangeId == null) { return false; } - UUID exchangeId = exchangeRecord.getId(); if(_records.containsKey(exchangeId)) { @@ -201,10 +200,10 @@ public class VirtualHostStoreUpgraderAndRecoverer { Map.Entry<UUID, ConfiguredObjectRecord> entry = iterator.next(); final ConfiguredObjectRecord record = entry.getValue(); - final ConfiguredObjectRecord exchangeParent = record.getParents().get(Exchange.class.getSimpleName()); - final ConfiguredObjectRecord queueParent = record.getParents().get(Queue.class.getSimpleName()); - if(isBinding(record.getType()) && (exchangeParent == null || unknownExchange(exchangeParent.getId()) - || queueParent == null || unknownQueue(queueParent.getId()))) + final UUID exchangeParent = record.getParents().get(Exchange.class.getSimpleName()); + final UUID queueParent = record.getParents().get(Queue.class.getSimpleName()); + if(isBinding(record.getType()) && (exchangeParent == null || unknownExchange(exchangeParent) + || queueParent == null || unknownQueue(queueParent))) { getDeleteMap().put(entry.getKey(), entry.getValue()); iterator.remove(); @@ -363,7 +362,7 @@ public class VirtualHostStoreUpgraderAndRecoverer Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(record.getAttributes()); virtualHostAttributes.put("name", _virtualHostNode.getName()); virtualHostAttributes.put("modelVersion", getToVersion()); - record = new ConfiguredObjectRecordImpl(record.getId(), "VirtualHost", virtualHostAttributes, Collections.<String, ConfiguredObjectRecord>emptyMap()); + record = new ConfiguredObjectRecordImpl(record.getId(), "VirtualHost", virtualHostAttributes, Collections.<String, UUID>emptyMap()); _virtualHostRecord = record; } else if("Exchange".equals(record.getType())) @@ -389,7 +388,7 @@ public class VirtualHostStoreUpgraderAndRecoverer attributes.put("type", type); attributes.put("lifetimePolicy", "PERMANENT"); - ConfiguredObjectRecord record = new ConfiguredObjectRecordImpl(id, Exchange.class.getSimpleName(), attributes, Collections.singletonMap(_virtualHostRecord.getType(), _virtualHostRecord)); + ConfiguredObjectRecord record = new ConfiguredObjectRecordImpl(id, Exchange.class.getSimpleName(), attributes, Collections.singletonMap(_virtualHostRecord.getType(), _virtualHostRecord.getId())); getUpdateMap().put(id, record); getNextUpgrader().configuredObject(record); diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AbstractVirtualHost.java b/java/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AbstractVirtualHost.java index 1cd14dc025..80d1dcf15f 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AbstractVirtualHost.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AbstractVirtualHost.java @@ -167,7 +167,7 @@ public abstract class AbstractVirtualHost<X extends AbstractVirtualHost<X>> exte _dtxRegistry = new DtxRegistry(); - _eventLogger = _broker.getParent(SystemContext.class).getEventLogger(); + _eventLogger = _broker.getParent(SystemConfig.class).getEventLogger(); _eventLogger.message(VirtualHostMessages.CREATED(getName())); diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractStandardVirtualHostNode.java b/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractStandardVirtualHostNode.java index b2a124a309..fbe402c4a1 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractStandardVirtualHostNode.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractStandardVirtualHostNode.java @@ -71,7 +71,7 @@ public abstract class AbstractStandardVirtualHostNode<X extends AbstractStandard LOGGER.debug("Activating virtualhost node " + this); } - getConfigurationStore().openConfigurationStore(this); + getConfigurationStore().openConfigurationStore(this, false); getConfigurationStore().upgradeStoreStructure(); getEventLogger().message(getConfigurationStoreLogSubject(), ConfigStoreMessages.CREATED()); diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractVirtualHostNode.java b/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractVirtualHostNode.java index 368ac58bee..38101525cd 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractVirtualHostNode.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/AbstractVirtualHostNode.java @@ -31,7 +31,7 @@ import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.LifetimePolicy; import org.apache.qpid.server.model.State; import org.apache.qpid.server.model.StateTransition; -import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.security.access.Operation; @@ -65,8 +65,8 @@ public abstract class AbstractVirtualHostNode<X extends AbstractVirtualHostNode< super(Collections.<Class<? extends ConfiguredObject>,ConfiguredObject<?>>singletonMap(Broker.class, parent), attributes); _broker = parent; - SystemContext<?> systemContext = _broker.getParent(SystemContext.class); - _eventLogger = systemContext.getEventLogger(); + SystemConfig<?> systemConfig = _broker.getParent(SystemConfig.class); + _eventLogger = systemConfig.getEventLogger(); _virtualHostNodeLogSubject = new VirtualHostNodeLogSubject(getName()); } diff --git a/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/JsonVirtualHostNodeImpl.java b/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/JsonVirtualHostNodeImpl.java index 004ad652f4..d97d29092c 100644 --- a/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/JsonVirtualHostNodeImpl.java +++ b/java/broker-core/src/main/java/org/apache/qpid/server/virtualhostnode/JsonVirtualHostNodeImpl.java @@ -27,6 +27,7 @@ import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ManagedAttributeField; import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.JsonFileConfigStore; @@ -53,7 +54,7 @@ public class JsonVirtualHostNodeImpl extends AbstractStandardVirtualHostNode<Jso @Override protected DurableConfigurationStore createConfigurationStore() { - return new JsonFileConfigStore(); + return new JsonFileConfigStore(VirtualHost.class); } @Override diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java index d7301ddc19..8c115c6e62 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java @@ -38,7 +38,7 @@ public class BrokerOptionsTest extends QpidTestCase public void testDefaultConfigurationStoreType() { - assertEquals("json", _options.getConfigurationStoreType()); + assertEquals("JSON", _options.getConfigurationStoreType()); } public void testOverriddenConfigurationStoreType() @@ -52,7 +52,7 @@ public class BrokerOptionsTest extends QpidTestCase String qpidWork = "/test/value"; setTestSystemProperty("QPID_WORK", qpidWork); - String expectedPath = new File(qpidWork, BrokerOptions.DEFAULT_CONFIG_NAME_PREFIX + "." + BrokerOptions.DEFAULT_STORE_TYPE).getAbsolutePath(); + String expectedPath = new File(qpidWork, BrokerOptions.DEFAULT_CONFIG_NAME_PREFIX + "." + BrokerOptions.DEFAULT_STORE_TYPE.toLowerCase()).getAbsolutePath(); assertEquals (expectedPath, _options.getConfigurationStoreLocation()); } @@ -61,7 +61,7 @@ public class BrokerOptionsTest extends QpidTestCase setTestSystemProperty("QPID_WORK", null); String userDir = System.getProperty("user.dir"); - String expectedPath = new File(userDir, "work/" + BrokerOptions.DEFAULT_CONFIG_NAME_PREFIX + "." + BrokerOptions.DEFAULT_STORE_TYPE).getAbsolutePath(); + String expectedPath = new File(userDir, "work/" + BrokerOptions.DEFAULT_CONFIG_NAME_PREFIX + "." + BrokerOptions.DEFAULT_STORE_TYPE.toLowerCase()).getAbsolutePath(); assertEquals (expectedPath, _options.getConfigurationStoreLocation()); } diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java deleted file mode 100644 index 748a9f6433..0000000000 --- a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/BrokerConfigurationStoreCreatorTest.java +++ /dev/null @@ -1,189 +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; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -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.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.store.JsonConfigurationEntryStore; -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -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.BrokerModel; -import org.apache.qpid.server.model.SystemContext; -import org.apache.qpid.server.model.SystemContextImpl; -import org.apache.qpid.test.utils.QpidTestCase; -import org.apache.qpid.test.utils.TestFileUtils; -import org.apache.qpid.util.FileUtils; - -public class BrokerConfigurationStoreCreatorTest extends QpidTestCase -{ - private File _userStoreLocation; - private BrokerConfigurationStoreCreator _storeCreator; - private SystemContext _systemContext; - private TaskExecutor _taskExecutor; - - public void setUp() throws Exception - { - super.setUp(); - - // check whether QPID_HOME JVM system property is set - if (QPID_HOME == null) - { - // set the properties in order to resolve the defaults store settings - setTestSystemProperty("QPID_HOME", TMP_FOLDER); - setTestSystemProperty("QPID_WORK", TMP_FOLDER + File.separator + "work"); - } - _storeCreator = new BrokerConfigurationStoreCreator(); - _userStoreLocation = new File(TMP_FOLDER, "_store_" + System.currentTimeMillis() + "_" + getTestName()); - final BrokerOptions brokerOptions = mock(BrokerOptions.class); - when(brokerOptions.getConfigurationStoreLocation()).thenReturn(_userStoreLocation.getAbsolutePath()); - _taskExecutor = new CurrentThreadTaskExecutor(); - _taskExecutor.start(); - _systemContext = new SystemContextImpl(_taskExecutor, - mock(EventLogger.class), - mock(LogRecorder.class), - brokerOptions); - } - - public void tearDown() throws Exception - { - try - { - super.tearDown(); - _taskExecutor.stop(); - } - finally - { - if (_userStoreLocation != null) - { - FileUtils.delete(_userStoreLocation, true); - } - } - } - - - public void testCreateJsonStore() - { - 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(_systemContext, null, false, Collections - .<String,String>emptyMap()); - Set<UUID> childrenIds = jsonStore.getRootEntry().getChildrenIds(); - assertFalse("Unexpected children: " + childrenIds, childrenIds.isEmpty()); - } - - public void testCreateJsonStoreFromInitialStore() throws Exception - { - createJsonStoreFromInitialStoreTestImpl(false); - } - - public void testOverwriteExistingJsonStoreWithInitialConfig() throws Exception - { - createJsonStoreFromInitialStoreTestImpl(true); - } - - public void createJsonStoreFromInitialStoreTestImpl(boolean overwrite) throws Exception - { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - - String defaultBrokerName = "${broker.name}"; - String testBrokerName = getTestName(); - - Map<String, Object> brokerObjectMap = new HashMap<String, Object>(); - UUID testBrokerId = UUID.randomUUID(); - brokerObjectMap.put(Broker.ID, testBrokerId); - brokerObjectMap.put(Broker.NAME, testBrokerName); - brokerObjectMap.put(Broker.MODEL_VERSION, BrokerModel.MODEL_VERSION); - brokerObjectMap.put(Broker.STORE_VERSION, 1); - - StringWriter sw = new StringWriter(); - objectMapper.writeValue(sw, brokerObjectMap); - - String brokerJson = sw.toString(); - - File _initialStoreFile = TestFileUtils.createTempFile(this, ".json", brokerJson); - - 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(_systemContext, null, false, Collections.<String,String>emptyMap()); - ConfigurationEntry entry = jsonStore.getRootEntry(); - assertEquals("Unexpected root id", testBrokerId, entry.getId()); - Map<String, Object> attributes = entry.getAttributes(); - assertNotNull("Unexpected attributes: " + attributes, attributes); - assertEquals("Unexpected attributes size: " + attributes.size(), 3, attributes.size()); - assertEquals("Unexpected attribute name: " + attributes.get("name"), testBrokerName, attributes.get(Broker.NAME)); - Set<UUID> childrenIds = entry.getChildrenIds(); - assertTrue("Unexpected children: " + childrenIds, childrenIds.isEmpty()); - - if(overwrite) - { - 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(_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(); - assertNotNull("No attributes found", attributes); - assertFalse("Test name should not equal default broker name", testBrokerName.equals(defaultBrokerName)); - assertEquals("Unexpected broker name value" , defaultBrokerName, attributes.get(Broker.NAME)); - childrenIds = entry.getChildrenIds(); - assertFalse("Expected children were not found" + childrenIds, childrenIds.isEmpty()); - } - } - - public void testCreateStoreWithUnknownType() - { - try - { - _storeCreator.createStore(_systemContext, "other", null, false, Collections.<String,String>emptyMap()); - fail("Store is not yet supported"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - -} diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java index a8f1e5942b..f732a01c1e 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/startup/VirtualHostCreationTest.java @@ -39,7 +39,7 @@ import org.apache.qpid.server.model.BrokerModel; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.ConfiguredObjectFactory; import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; -import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.security.SecurityManager; @@ -58,19 +58,19 @@ public class VirtualHostCreationTest extends TestCase EventLogger eventLogger = mock(EventLogger.class); SecurityManager securityManager = mock(SecurityManager.class); TaskExecutor executor = CurrentThreadTaskExecutor.newStartedInstance(); - SystemContext systemContext = mock(SystemContext.class); + SystemConfig systemConfig = mock(SystemConfig.class); ConfiguredObjectFactory objectFactory = new ConfiguredObjectFactoryImpl(BrokerModel.getInstance()); - when(systemContext.getObjectFactory()).thenReturn(objectFactory); - when(systemContext.getModel()).thenReturn(objectFactory.getModel()); - when(systemContext.getEventLogger()).thenReturn(eventLogger); - when(systemContext.getTaskExecutor()).thenReturn(executor); + when(systemConfig.getObjectFactory()).thenReturn(objectFactory); + when(systemConfig.getModel()).thenReturn(objectFactory.getModel()); + when(systemConfig.getEventLogger()).thenReturn(eventLogger); + when(systemConfig.getTaskExecutor()).thenReturn(executor); Broker broker = mock(Broker.class); when(broker.getObjectFactory()).thenReturn(objectFactory); when(broker.getModel()).thenReturn(objectFactory.getModel()); when(broker.getSecurityManager()).thenReturn(securityManager); when(broker.getCategoryClass()).thenReturn(Broker.class); - when(broker.getParent(eq(SystemContext.class))).thenReturn(systemContext); + when(broker.getParent(eq(SystemConfig.class))).thenReturn(systemConfig); when(broker.getTaskExecutor()).thenReturn(executor); _virtualHostNode = mock(VirtualHostNode.class); diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java deleted file mode 100644 index 6619b76214..0000000000 --- a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ConfigurationEntryStoreTestCase.java +++ /dev/null @@ -1,498 +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.store; - -import static org.mockito.Mockito.mock; - -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.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryImpl; -import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; -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.GroupProvider; -import org.apache.qpid.server.model.KeyStore; -import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.SystemContextImpl; -import org.apache.qpid.server.model.Transport; -import org.apache.qpid.server.model.TrustStore; -import org.apache.qpid.server.model.VirtualHost; -import org.apache.qpid.server.model.VirtualHostNode; -import org.apache.qpid.server.model.adapter.FileSystemPreferencesProvider; -import org.apache.qpid.server.model.port.AmqpPort; -import org.apache.qpid.server.security.FileKeyStore; -import org.apache.qpid.server.security.FileTrustStore; -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 MemoryConfigurationEntryStore _store; - - private UUID _brokerId; - private UUID _virtualHostNodeId; - protected UUID _authenticationProviderId; - - private Map<String, Object> _brokerAttributes; - private Map<String, Object> _virtualHostNodeAttributes; - private Map<String, Object> _authenticationProviderAttributes; - - private TaskExecutor _taskExecutor; - private SystemContextImpl _systemContext; - - public void setUp() throws Exception - { - super.setUp(); - - - _taskExecutor = new CurrentThreadTaskExecutor(); - _taskExecutor.start(); - - _systemContext = new SystemContextImpl(_taskExecutor, - mock(EventLogger.class), mock(LogRecorder.class), - new BrokerOptions()); - - _brokerId = UUID.randomUUID(); - _brokerAttributes = new HashMap<String, Object>(); - _brokerAttributes.put(Broker.DEFAULT_VIRTUAL_HOST, "test"); - _brokerAttributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, 1000); - _brokerAttributes.put(Broker.CONNECTION_HEART_BEAT_DELAY, 2000); - _brokerAttributes.put(Broker.STATISTICS_REPORTING_PERIOD, 4000); - _brokerAttributes.put(Broker.STATISTICS_REPORTING_RESET_ENABLED, true); - - _virtualHostNodeId = UUID.randomUUID(); - _virtualHostNodeAttributes = new HashMap<String, Object>(); - _virtualHostNodeAttributes.put(VirtualHost.NAME, "test"); - _virtualHostNodeAttributes.put(VirtualHost.TYPE, "JSON"); - - _authenticationProviderId = UUID.randomUUID(); - _authenticationProviderAttributes = new HashMap<String, Object>(); - _authenticationProviderAttributes.put(AuthenticationProvider.NAME, "authenticationProvider1"); - _authenticationProviderAttributes.put(AuthenticationProvider.TYPE, AnonymousAuthenticationManager.class.getSimpleName()); - - _store = createStore(_brokerId, _brokerAttributes); - addConfiguration(_virtualHostNodeId, VirtualHostNode.class.getSimpleName(), _virtualHostNodeAttributes); - addConfiguration(_authenticationProviderId, AuthenticationProvider.class.getSimpleName(), _authenticationProviderAttributes); - } - - SystemContextImpl getSystemContext() - { - return _systemContext; - } - - @Override - public void tearDown() throws Exception - { - super.tearDown(); - _taskExecutor.stop(); - } - - protected TaskExecutor getTaskExecutor() - { - return _taskExecutor; - } - - // ??? perhaps it should not be abstract - - 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); - - protected final void addConfiguration(UUID id, String type, Map<String, Object> attributes) - { - addConfiguration(id, type, attributes, _brokerId); - } - - protected MemoryConfigurationEntryStore getStore() - { - return _store; - } - - public void testGetRootEntry() - { - ConfigurationEntry brokerConfigEntry = _store.getRootEntry(); - assertNotNull("Root entry does not exist", brokerConfigEntry); - assertEquals("Unexpected id", _brokerId, brokerConfigEntry.getId()); - assertEquals("Unexpected type ", Broker.class.getSimpleName(), brokerConfigEntry.getType()); - Map<String, Object> attributes = brokerConfigEntry.getAttributes(); - assertNotNull("Attributes cannot be null", attributes); - for (Map.Entry<String, Object> attribute : _brokerAttributes.entrySet()) - { - assertEquals("Unexpected attribute " + attribute.getKey(), attribute.getValue(), attributes.get(attribute.getKey())); - } - } - - public void testGetEntry() - { - ConfigurationEntry authenticationProviderConfigEntry = _store.getEntry(_authenticationProviderId); - assertNotNull("Provider with id " + _authenticationProviderId + " should exist", authenticationProviderConfigEntry); - assertEquals("Unexpected id", _authenticationProviderId, authenticationProviderConfigEntry.getId()); - assertEquals("Unexpected type ", AuthenticationProvider.class.getSimpleName(), authenticationProviderConfigEntry.getType()); - Map<String, Object> attributes = authenticationProviderConfigEntry.getAttributes(); - assertNotNull("Attributes cannot be null", attributes); - assertEquals("Unexpected attributes", _authenticationProviderAttributes, attributes); - } - - public void testRemove() - { - final Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put(VirtualHost.NAME, getName()); - virtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - final UUID virtualHostId = UUID.randomUUID(); - addConfiguration(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes); - - assertNotNull("Virtual host with id " + virtualHostId + " should exist", _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() - { - Map<String, Object> virtualHost1Attributes = new HashMap<String, Object>(); - virtualHost1Attributes.put(VirtualHost.NAME, "test1"); - virtualHost1Attributes.put(VirtualHost.TYPE, "STANDARD"); - UUID virtualHost1Id = UUID.randomUUID(); - addConfiguration(virtualHost1Id, VirtualHost.class.getSimpleName(), virtualHost1Attributes); - - Map<String, Object> virtualHost2Attributes = new HashMap<String, Object>(); - virtualHost2Attributes.put(VirtualHost.NAME, "test1"); - virtualHost2Attributes.put(VirtualHost.TYPE, "STANDARD"); - UUID virtualHost2Id = UUID.randomUUID(); - addConfiguration(virtualHost2Id, VirtualHost.class.getSimpleName(), virtualHost2Attributes); - - 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(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]); - assertNull("First virtual host configuration should be removed", _store.getEntry(virtualHost1Id)); - assertNull("Second virtual host configuration should be removed", _store.getEntry(virtualHost2Id)); - } - - public void testSaveBroker() - { - ConfigurationEntry brokerConfigEntry = _store.getRootEntry(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(Broker.DEFAULT_VIRTUAL_HOST, "test"); - attributes.put(Broker.CONNECTION_SESSION_COUNT_LIMIT, 11000); - 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 ConfigurationEntryImpl(_brokerId, Broker.class.getSimpleName(), attributes, - brokerConfigEntry.getChildrenIds(), _store); - - _store.save(updatedBrokerEntry); - - ConfigurationEntry newBrokerConfigEntry = _store.getRootEntry(); - assertNotNull("Root entry does not exist", newBrokerConfigEntry); - assertEquals("Unexpected id", _brokerId, newBrokerConfigEntry.getId()); - assertEquals("Unexpected type ", Broker.class.getSimpleName(), newBrokerConfigEntry.getType()); - Map<String, Object> newBrokerAttributes = newBrokerConfigEntry.getAttributes(); - assertNotNull("Attributes cannot be null", newBrokerAttributes); - assertEquals("Unexpected attributes", attributes, newBrokerAttributes); - } - - public void testSaveNewVirtualHost() - { - Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put(VirtualHost.NAME, "test1"); - virtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - UUID virtualHostId = UUID.randomUUID(); - ConfigurationEntry hostEntry = new ConfigurationEntryImpl(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, - Collections.<UUID> emptySet(), _store); - - _store.save(hostEntry); - - ConfigurationEntry configurationEntry = _store.getEntry(virtualHostId); - assertEquals("Unexpected virtual host configuration", hostEntry, configurationEntry); - assertEquals("Unexpected type", VirtualHost.class.getSimpleName(), configurationEntry.getType()); - assertEquals("Unexpected virtual host attributes", hostEntry.getAttributes(), configurationEntry.getAttributes()); - assertTrue("Unexpected virtual host children found", hostEntry.getChildrenIds().isEmpty()); - } - - public void testSaveExistingVirtualHost() - { - ConfigurationEntry hostEntry = _store.getEntry(_virtualHostNodeId); - assertNotNull("Host configuration is not found", hostEntry); - - Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put(VirtualHost.NAME, "test"); - virtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - - ConfigurationEntry updatedEntry = new ConfigurationEntryImpl(_virtualHostNodeId, VirtualHost.class.getSimpleName(), virtualHostAttributes, - hostEntry.getChildrenIds(), _store); - _store.save(updatedEntry); - - ConfigurationEntry newHostEntry = _store.getEntry(_virtualHostNodeId); - assertEquals("Unexpected virtual host configuration", updatedEntry, newHostEntry); - assertEquals("Unexpected type", VirtualHost.class.getSimpleName(), newHostEntry.getType()); - assertEquals("Unexpected virtual host attributes", updatedEntry.getAttributes(), newHostEntry.getAttributes()); - assertEquals("Unexpected virtual host children found", updatedEntry.getChildrenIds(), newHostEntry.getChildrenIds()); - } - - public void testSaveNewAuthenticationProvider() - { - UUID authenticationProviderId = UUID.randomUUID(); - Map<String, Object> authenticationProviderAttributes = new HashMap<String, Object>(); - authenticationProviderAttributes.put(AuthenticationProvider.NAME, "authenticationProvider1"); - authenticationProviderAttributes.put(AuthenticationProvider.TYPE, ExternalAuthenticationManager.class.getSimpleName()); - ConfigurationEntry providerEntry = new ConfigurationEntryImpl(authenticationProviderId, AuthenticationProvider.class.getSimpleName(), - authenticationProviderAttributes, Collections.<UUID> emptySet(), _store); - - _store.save(providerEntry); - - ConfigurationEntry storeEntry = _store.getEntry(authenticationProviderId); - assertEquals("Unexpected provider configuration", providerEntry, storeEntry); - assertEquals("Unexpected type", AuthenticationProvider.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected provider attributes", providerEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSaveExistingAuthenticationProvider() - { - ConfigurationEntry providerEntry = _store.getEntry(_authenticationProviderId); - assertNotNull("provider configuration is not found", providerEntry); - - Map<String, Object> authenticationProviderAttributes = new HashMap<String, Object>(); - authenticationProviderAttributes.put(AuthenticationProvider.NAME, "authenticationProvider1"); - authenticationProviderAttributes.put(AuthenticationProvider.TYPE, ExternalAuthenticationManager.class.getSimpleName()); - ConfigurationEntry updatedEntry = new ConfigurationEntryImpl(_authenticationProviderId, AuthenticationProvider.class.getSimpleName(), - authenticationProviderAttributes, Collections.<UUID> emptySet(), _store); - _store.save(updatedEntry); - - ConfigurationEntry storeEntry = _store.getEntry(_authenticationProviderId); - assertEquals("Unexpected provider configuration", updatedEntry, storeEntry); - assertEquals("Unexpected type", AuthenticationProvider.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected provider attributes", updatedEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSaveTrustStore() - { - UUID trustStoreId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(TrustStore.NAME, getName()); - attributes.put(FileTrustStore.PATH, "/path/to/truststore"); - attributes.put(FileTrustStore.PASSWORD, "my-secret-password"); - attributes.put(FileTrustStore.TRUST_STORE_TYPE, "NON-JKS"); - attributes.put(FileTrustStore.TRUST_MANAGER_FACTORY_ALGORITHM, "NON-STANDARD"); - attributes.put(TrustStore.DESCRIPTION, "Description"); - - ConfigurationEntry - trustStoreEntry = new ConfigurationEntryImpl(trustStoreId, TrustStore.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), _store); - - _store.save(trustStoreEntry); - - ConfigurationEntry storeEntry = _store.getEntry(trustStoreId); - assertEquals("Unexpected trust store configuration", trustStoreEntry, storeEntry); - assertEquals("Unexpected type", TrustStore.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected provider attributes", trustStoreEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSaveKeyStore() - { - UUID keyStoreId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(KeyStore.NAME, getName()); - attributes.put(FileKeyStore.PATH, "/path/to/truststore"); - attributes.put(FileKeyStore.PASSWORD, "my-secret-password"); - attributes.put(FileKeyStore.KEY_STORE_TYPE, "NON-JKS"); - attributes.put(FileKeyStore.KEY_MANAGER_FACTORY_ALGORITHM, "NON-STANDARD"); - attributes.put(KeyStore.DESCRIPTION, "Description"); - attributes.put(FileKeyStore.CERTIFICATE_ALIAS, "Alias"); - - ConfigurationEntry keyStoreEntry = new ConfigurationEntryImpl(keyStoreId, KeyStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), - _store); - - _store.save(keyStoreEntry); - - ConfigurationEntry storeEntry = _store.getEntry(keyStoreId); - assertEquals("Unexpected key store configuration", keyStoreEntry, storeEntry); - assertEquals("Unexpected type", KeyStore.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected provider attributes", keyStoreEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSaveGroupProvider() - { - UUID groupProviderId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(GroupProvider.NAME, getName()); - - ConfigurationEntry groupProviderEntry = new ConfigurationEntryImpl(groupProviderId, GroupProvider.class.getSimpleName(), attributes, - Collections.<UUID> emptySet(), _store); - - _store.save(groupProviderEntry); - - ConfigurationEntry storeEntry = _store.getEntry(groupProviderId); - assertEquals("Unexpected group provider configuration", groupProviderEntry, storeEntry); - assertEquals("Unexpected type", GroupProvider.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected group provider attributes", groupProviderEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected provider children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testSavePort() - { - UUID portId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - Set<String> tcpTransportSet = Collections.singleton(Transport.TCP.name()); - attributes.put(Port.PORT, 9999); - attributes.put(Port.TRANSPORTS, tcpTransportSet); - attributes.put(Port.TCP_NO_DELAY, true); - attributes.put(AmqpPort.RECEIVE_BUFFER_SIZE, 1); - attributes.put(AmqpPort.SEND_BUFFER_SIZE, 2); - attributes.put(Port.NEED_CLIENT_AUTH, true); - attributes.put(Port.WANT_CLIENT_AUTH, true); - - ConfigurationEntry portEntry = new ConfigurationEntryImpl(portId, Port.class.getSimpleName(), attributes, Collections - .<UUID> emptySet(), _store); - - _store.save(portEntry); - - ConfigurationEntry storeEntry = _store.getEntry(portId); - assertEquals("Unexpected port configuration", portEntry, storeEntry); - assertEquals("Unexpected type", Port.class.getSimpleName(), storeEntry.getType()); - assertEquals("Unexpected port attributes", portEntry.getAttributes(), storeEntry.getAttributes()); - assertTrue("Unexpected port children found", storeEntry.getChildrenIds().isEmpty()); - } - - public void testMultipleSave() - { - UUID virtualHostId = UUID.randomUUID(); - Map<String, Object> virtualHostAttributes = new HashMap<String, Object>(); - virtualHostAttributes.put(VirtualHost.NAME, "test1"); - virtualHostAttributes.put(VirtualHost.TYPE, "STANDARD"); - ConfigurationEntry hostEntry = new ConfigurationEntryImpl(virtualHostId, VirtualHost.class.getSimpleName(), virtualHostAttributes, - Collections.<UUID> emptySet(), _store); - - UUID keyStoreId = UUID.randomUUID(); - Map<String, Object> attributes = new HashMap<String, Object>(); - attributes.put(KeyStore.NAME, getName()); - attributes.put(FileKeyStore.PATH, "/path/to/truststore"); - attributes.put(FileKeyStore.PASSWORD, "my-secret-password"); - attributes.put(FileKeyStore.KEY_STORE_TYPE, "NON-JKS"); - attributes.put(FileKeyStore.KEY_MANAGER_FACTORY_ALGORITHM, "NON-STANDARD"); - attributes.put(KeyStore.DESCRIPTION, "Description"); - attributes.put(FileKeyStore.CERTIFICATE_ALIAS, "Alias"); - - ConfigurationEntry keyStoreEntry = new ConfigurationEntryImpl(keyStoreId, KeyStore.class.getSimpleName(), attributes, Collections.<UUID> emptySet(), - _store); - - _store.save(hostEntry, keyStoreEntry); - - assertNotNull("Virtual host is not found", _store.getEntry(virtualHostId)); - assertNotNull("Key store is not found", _store.getEntry(keyStoreId)); - } - - public void testAddPreferencesProvider() - { - UUID preferencesProviderId = UUID.randomUUID(); - String path = TMP_FOLDER; - String name = getTestName(); - - addPreferencesProvider(preferencesProviderId, name, path); - - assertEquals("Unexpected preference provider ID in authentication provider children set", preferencesProviderId, _store - .getEntry(_authenticationProviderId).getChildrenIds().iterator().next()); - ConfigurationEntry preferencesProviderEntry = _store.getEntry(preferencesProviderId); - assertNotNull("Preferences provider is not found", preferencesProviderEntry); - assertEquals("Unexpected preferences provider id", preferencesProviderId, preferencesProviderEntry.getId()); - Map<String, Object> attributes = preferencesProviderEntry.getAttributes(); - assertEquals("Unexpected preferences provider name", name, attributes.get(PreferencesProvider.NAME)); - assertEquals("Unexpected preferences provider path", path, attributes.get(FileSystemPreferencesProvider.PATH)); - assertEquals("Unexpected preferences provider type", FileSystemPreferencesProvider.PROVIDER_TYPE, - attributes.get(PreferencesProvider.TYPE)); - } - - protected void addPreferencesProvider(UUID preferencesProviderId, String name, String path) - { - ConfigurationEntry authenticationProviderEntry = _store.getEntry(_authenticationProviderId); - ConfigurationEntry newAuthenticationProviderConfigEntry = new ConfigurationEntryImpl(authenticationProviderEntry.getId(), - authenticationProviderEntry.getType(), authenticationProviderEntry.getAttributes(), - Collections.<UUID>singleton(preferencesProviderId), _store); - - Map<String, Object> preferencesProviderAttributes = new HashMap<String, Object>(); - preferencesProviderAttributes.put(PreferencesProvider.TYPE, FileSystemPreferencesProvider.PROVIDER_TYPE); - preferencesProviderAttributes.put(FileSystemPreferencesProvider.PATH, path); - preferencesProviderAttributes.put(PreferencesProvider.NAME, name); - - ConfigurationEntry preferencesProviderEntry = new ConfigurationEntryImpl(preferencesProviderId, PreferencesProvider.class.getSimpleName(), - preferencesProviderAttributes, Collections.<UUID> emptySet(), _store); - - _store.save(newAuthenticationProviderConfigEntry, preferencesProviderEntry); - } - -} diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java deleted file mode 100644 index 3563444f63..0000000000 --- a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/JsonConfigurationEntryStoreTest.java +++ /dev/null @@ -1,314 +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.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; -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.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.ConfigurationEntryImpl; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -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.PreferencesProvider; -import org.apache.qpid.server.model.SystemContext; -import org.apache.qpid.server.model.SystemContextImpl; -import org.apache.qpid.server.model.adapter.FileSystemPreferencesProvider; -import org.apache.qpid.server.store.DurableConfigurationStore; -import org.apache.qpid.test.utils.TestFileUtils; - - -public class JsonConfigurationEntryStoreTest extends ConfigurationEntryStoreTestCase -{ - private File _storeFile; - private ObjectMapper _objectMapper; - - - @Override - public void setUp() throws Exception - { - _objectMapper = new ObjectMapper(); - _objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); - super.setUp(); - } - - @Override - public void tearDown() throws Exception - { - _storeFile.delete(); - super.tearDown(); - } - - @Override - protected JsonConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception - { - _storeFile = createStoreFile(brokerId, brokerAttributes); - 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 SystemContextImpl(getTaskExecutor(), - 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 - { - return createStoreFile(brokerId, brokerAttributes, true); - } - - private File createStoreFile(UUID brokerId, Map<String, Object> brokerAttributes, boolean setVersion) throws IOException, - JsonGenerationException, JsonMappingException - { - Map<String, Object> brokerObjectMap = new HashMap<String, Object>(); - brokerObjectMap.put(Broker.ID, brokerId); - if (setVersion) - { - brokerObjectMap.put(Broker.STORE_VERSION, MemoryConfigurationEntryStore.STORE_VERSION); - } - brokerObjectMap.put(Broker.NAME, getTestName()); - brokerObjectMap.putAll(brokerAttributes); - - StringWriter sw = new StringWriter(); - _objectMapper.writeValue(sw, brokerObjectMap); - - String brokerJson = sw.toString(); - - return TestFileUtils.createTempFile(this, ".json", brokerJson); - } - - @Override - protected void addConfiguration(UUID id, String type, Map<String, Object> attributes, UUID parentId) - { - MemoryConfigurationEntryStore store = getStore(); - ConfigurationEntry parentEntry = getStore().getEntry(parentId); - Set<UUID> children = new HashSet<UUID>(parentEntry.getChildrenIds()); - children.add(id); - ConfigurationEntry newParentEntry = new ConfigurationEntryImpl(parentEntry.getId(), parentEntry.getType(), parentEntry.getAttributes(), children, store); - store.save(newParentEntry, new ConfigurationEntryImpl(id, type, attributes, Collections.<UUID> emptySet(), store)); - } - - /* ** - * TODO - RG : This functionality has been moved to the generic configured object. The JsonConfigurationEntryStore - * needs to be removed and replaced with the Json configuration store written for the virtual host, however testing - * resolution functionality needs to occur in a configured object resolution test - * ** - - - public void testAttributeIsResolvedFromSystemProperties() - { - String defaultVhost = getTestName(); - setTestSystemProperty("my.test.property", defaultVhost); - - 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 ConfigurationEntryImpl(brokerConfigEntry.getId(), Broker.class.getSimpleName(), - attributes, brokerConfigEntry.getChildrenIds(), store); - store.save(updatedBrokerEntry); - - JsonConfigurationEntryStore store2 = createStore(); - - assertEquals("Unresolved default virtualhost value", defaultVhost, store2.getRootEntry().getAttributes().get(Broker.DEFAULT_VIRTUAL_HOST)); - } - */ - - public void testCreateEmptyStore() - { - File file = TestFileUtils.createTempFile(this, ".json"); - try - { - createStore(file.getAbsolutePath()); - fail("Cannot create a new store without initial store"); - } - catch(IllegalConfigurationException e) - { - // pass - } - } - - public void testCreateFromExistingLocation() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - brokerAttributes.put(Broker.NAME, getTestName()); - File file = createStoreFile(brokerId, brokerAttributes); - - JsonConfigurationEntryStore store = createStore(file.getAbsolutePath()); - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - assertEquals("Unexpected root entry", brokerId, root.getId()); - Map<String, Object> attributes = root.getAttributes(); - assertNotNull("Attributes not found", attributes); - assertEquals("Unexpected number of attributes", 2, attributes.size()); - assertEquals("Unexpected name attribute", getTestName(), attributes.get(Broker.NAME)); - assertEquals("Unexpected version attribute", 1, attributes.get(Broker.STORE_VERSION)); - } - - public void testCreateFromInitialStore() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - File initialStoreFile = createStoreFile(brokerId, brokerAttributes); - - JsonConfigurationEntryStore initialStore = createStore(initialStoreFile.getAbsolutePath()); - - File storeFile = TestFileUtils.createTempFile(this, ".json"); - JsonConfigurationEntryStore store = createStore(storeFile.getAbsolutePath(), initialStore); - - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - assertEquals("Unexpected root entry", brokerId, root.getId()); - Map<String, Object> attributes = root.getAttributes(); - assertNotNull("Attributes not found", attributes); - assertEquals("Unexpected number of attributes", 2, attributes.size()); - assertEquals("Unexpected name attribute", getTestName(), attributes.get(Broker.NAME)); - assertEquals("Unexpected version attribute", 1, attributes.get(Broker.STORE_VERSION)); - } - - public void testGetVersion() - { - assertEquals("Unexpected version", 1, getStore().getVersion()); - } - - public void testGetType() - { - assertEquals("Unexpected type", "json", getStore().getType()); - } - - public void testUnsupportedStoreVersion() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - int[] storeVersions = {Integer.MAX_VALUE, 0}; - for (int storeVersion : storeVersions) - { - brokerAttributes.put(Broker.STORE_VERSION, storeVersion); - File storeFile = null; - try - { - storeFile = createStoreFile(brokerId, brokerAttributes); - createStore(storeFile.getAbsolutePath()); - fail("The store creation should fail due to unsupported store version"); - } - catch (IllegalConfigurationException e) - { - assertEquals("The data of version " + storeVersion - + " can not be loaded by store of version " + MemoryConfigurationEntryStore.STORE_VERSION, e.getMessage()); - } - finally - { - if (storeFile != null) - { - storeFile.delete(); - } - } - } - } - - public void testStoreVersionNotSpecified() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - File storeFile = null; - try - { - storeFile = createStoreFile(brokerId, brokerAttributes, false); - createStore(storeFile.getAbsolutePath()); - fail("The store creation should fail due to unspecified store version"); - } - catch (IllegalConfigurationException e) - { - assertEquals("Broker " + Broker.STORE_VERSION + " attribute must be specified", e.getMessage()); - } - finally - { - if (storeFile != null) - { - storeFile.delete(); - } - } - } - - public void testGetPreferencesProvider() throws Exception - { - UUID preferencesProviderId = UUID.randomUUID(); - String path = TMP_FOLDER; - String name = getTestName(); - - addPreferencesProvider(preferencesProviderId, name, path); - - // verify that store can deserialise child of a child - JsonConfigurationEntryStore newStore = createStore(); - - ConfigurationEntry authenticationProviderEntry = newStore.getEntry(_authenticationProviderId); - assertEquals("Unexpected preference provider ID in authentication provider children set", preferencesProviderId, authenticationProviderEntry.getChildrenIds().iterator().next()); - ConfigurationEntry preferencesProviderEntry = newStore.getEntry(preferencesProviderId); - assertNotNull("Preferences provider is not found", preferencesProviderEntry); - assertEquals("Unexpected preferences provider id", preferencesProviderId, preferencesProviderEntry.getId()); - Map<String, Object> attributes = preferencesProviderEntry.getAttributes(); - assertEquals("Unexpected preferences provider name", name, attributes.get(PreferencesProvider.NAME)); - assertEquals("Unexpected preferences provider path", path, attributes.get(FileSystemPreferencesProvider.PATH)); - assertEquals("Unexpected preferences provider type", FileSystemPreferencesProvider.PROVIDER_TYPE, - attributes.get(PreferencesProvider.TYPE)); - } - -} diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java index c648011116..36353f0dba 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/ManagementModeStoreHandlerTest.java @@ -45,11 +45,11 @@ 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.JsonSystemConfigImpl; 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.SystemContextImpl; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.store.ConfiguredObjectRecord; import org.apache.qpid.server.store.ConfiguredObjectRecordImpl; @@ -65,7 +65,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase private ConfiguredObjectRecord _root; private ConfiguredObjectRecord _portEntry; private UUID _rootId, _portEntryId; - private SystemContext _systemContext; + private SystemConfig _systemConfig; private TaskExecutor _taskExecutor; protected void setUp() throws Exception @@ -77,19 +77,19 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase _taskExecutor = new CurrentThreadTaskExecutor(); _taskExecutor.start(); - _systemContext = new SystemContextImpl(_taskExecutor, mock(EventLogger.class), + _systemConfig = new JsonSystemConfigImpl(_taskExecutor, mock(EventLogger.class), mock(LogRecorder.class), new BrokerOptions()); - ConfiguredObjectRecord systemContextRecord = _systemContext.asObjectRecord(); + ConfiguredObjectRecord systemContextRecord = _systemConfig.asObjectRecord(); - _root = new ConfiguredObjectRecordImpl(_rootId, Broker.class.getSimpleName(), Collections.<String,Object>emptyMap(), Collections.singletonMap(SystemContext.class.getSimpleName(), systemContextRecord)); + _root = new ConfiguredObjectRecordImpl(_rootId, Broker.class.getSimpleName(), Collections.<String,Object>emptyMap(), Collections.singletonMap(SystemConfig.class.getSimpleName(), systemContextRecord.getId())); _portEntry = mock(ConfiguredObjectRecord.class); when(_portEntry.getId()).thenReturn(_portEntryId); - when(_portEntry.getParents()).thenReturn(Collections.singletonMap(Broker.class.getSimpleName(), _root)); + when(_portEntry.getParents()).thenReturn(Collections.singletonMap(Broker.class.getSimpleName(), _root.getId())); when(_portEntry.getType()).thenReturn(Port.class.getSimpleName()); final ArgumentCaptor<ConfiguredObjectRecordHandler> recovererArgumentCaptor = ArgumentCaptor.forClass(ConfiguredObjectRecordHandler.class); @@ -111,7 +111,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase _options = new BrokerOptions(); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); } @Override @@ -153,7 +153,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeHttpPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); Collection<UUID> childrenIds = getChildrenIds(root); @@ -165,7 +165,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeRmiPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); @@ -178,7 +178,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeJmxPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); @@ -193,7 +193,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase _options.setManagementModeRmiPortOverride(2000); _options.setManagementModeJmxPortOverride(3000); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord root = getRootEntry(); assertEquals("Unexpected root id", _rootId, root.getId()); @@ -221,7 +221,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeJmxPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); UUID optionsPort = getOptionsPortId(); @@ -233,7 +233,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeHttpPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); UUID optionsPort = getOptionsPortId(); @@ -248,7 +248,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase when(_portEntry.getAttributes()).thenReturn(attributes); _options.setManagementModeHttpPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord portEntry = getEntry(_portEntryId); @@ -262,7 +262,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase when(_portEntry.getAttributes()).thenReturn(attributes); _options.setManagementModeRmiPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord portEntry = getEntry(_portEntryId); @@ -276,7 +276,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase when(_portEntry.getAttributes()).thenReturn(attributes); _options.setManagementModeRmiPortOverride(9090); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord portEntry = getEntry(_portEntryId); @@ -299,7 +299,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(VirtualHost.TYPE, "STANDARD"); - final ConfiguredObjectRecord virtualHost = new ConfiguredObjectRecordImpl(virtualHostId, VirtualHost.class.getSimpleName(), attributes, Collections.singletonMap(Broker.class.getSimpleName(), _root)); + final ConfiguredObjectRecord virtualHost = new ConfiguredObjectRecordImpl(virtualHostId, VirtualHost.class.getSimpleName(), attributes, Collections.singletonMap(Broker.class.getSimpleName(), _root.getId())); final ArgumentCaptor<ConfiguredObjectRecordHandler> recovererArgumentCaptor = ArgumentCaptor.forClass(ConfiguredObjectRecordHandler.class); doAnswer( new Answer() @@ -327,7 +327,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase } _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord hostEntry = getEntry(virtualHostId); Map<String, Object> hostAttributes = new HashMap<String, Object>(hostEntry.getAttributes()); @@ -353,13 +353,13 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase _options.setManagementModeRmiPortOverride(2000); _options.setManagementModeJmxPortOverride(3000); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put(Port.NAME, "TEST"); ConfiguredObjectRecord configurationEntry = new ConfiguredObjectRecordImpl(_portEntryId, Port.class.getSimpleName(), attributes, - Collections.singletonMap(Broker.class.getSimpleName(), getRootEntry())); + Collections.singletonMap(Broker.class.getSimpleName(), getRootEntry().getId())); _handler.create(configurationEntry); verify(_store).create(any(ConfiguredObjectRecord.class)); } @@ -370,7 +370,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase _options.setManagementModeRmiPortOverride(2000); _options.setManagementModeJmxPortOverride(3000); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord root = getRootEntry(); Map<String, Object> attributes = new HashMap<String, Object>(); @@ -385,7 +385,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeHttpPortOverride(1000); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); UUID portId = getOptionsPortId(); Map<String, Object> attributes = new HashMap<String, Object>(); @@ -393,7 +393,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase ConfiguredObjectRecord configurationEntry = new ConfiguredObjectRecordImpl(portId, Port.class.getSimpleName(), attributes, Collections.singletonMap(Broker.class.getSimpleName(), - getRootEntry())); + getRootEntry().getId())); try { _handler.update(false, configurationEntry); @@ -409,7 +409,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeHttpPortOverride(1000); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); ConfiguredObjectRecord record = new ConfiguredObjectRecord() { @@ -432,7 +432,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase } @Override - public Map<String, ConfiguredObjectRecord> getParents() + public Map<String, UUID> getParents() { return null; } @@ -445,7 +445,7 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase { _options.setManagementModeHttpPortOverride(1000); _handler = new ManagementModeStoreHandler(_store, _options); - _handler.openConfigurationStore(_systemContext); + _handler.openConfigurationStore(_systemConfig, false); UUID portId = getOptionsPortId(); ConfiguredObjectRecord record = mock(ConfiguredObjectRecord.class); @@ -563,9 +563,9 @@ public class ManagementModeStoreHandlerTest extends QpidTestCase if(object.getParents() != null) { - for(ConfiguredObjectRecord parent : object.getParents().values()) + for(UUID parent : object.getParents().values()) { - if(parent.getId().equals(_parent.getId())) + if(parent.equals(_parent.getId())) { _childIds.add(object.getId()); } diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java deleted file mode 100644 index 40090efb17..0000000000 --- a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStoreTest.java +++ /dev/null @@ -1,142 +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.store; - -import java.io.File; -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.codehaus.jackson.map.ObjectMapper; - -import org.apache.qpid.server.BrokerOptions; -import org.apache.qpid.server.configuration.ConfigurationEntry; -import org.apache.qpid.server.configuration.ConfigurationEntryImpl; -import org.apache.qpid.server.configuration.IllegalConfigurationException; -import org.apache.qpid.server.model.Broker; - -public class MemoryConfigurationEntryStoreTest extends ConfigurationEntryStoreTestCase -{ - - @Override - public void setUp() throws Exception - { - super.setUp(); - - } - - @Override - protected MemoryConfigurationEntryStore createStore(UUID brokerId, Map<String, Object> brokerAttributes) throws Exception - { - Map<String, Object> broker = new HashMap<String, Object>(); - broker.put(Broker.ID, brokerId); - broker.putAll(brokerAttributes); - ObjectMapper mapper = new ObjectMapper(); - - return new MemoryConfigurationEntryStore(getSystemContext(),mapper.writeValueAsString(broker), Collections.<String,String>emptyMap()); - } - - @Override - protected void addConfiguration(UUID id, String type, Map<String, Object> attributes, UUID parentId) - { - MemoryConfigurationEntryStore store = getStore(); - ConfigurationEntry parentEntry = getStore().getEntry(parentId); - Set<UUID> children = new HashSet<UUID>(parentEntry.getChildrenIds()); - children.add(id); - 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(getSystemContext(), 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) - { - // pass - } - } - - public void testCreateWithNullJson() - { - MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(getSystemContext(),null, Collections.<String,String>emptyMap()); - - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - } - - public void testOpenInMemoryWithInitialStore() throws Exception - { - UUID brokerId = UUID.randomUUID(); - Map<String, Object> brokerAttributes = new HashMap<String, Object>(); - brokerAttributes.put(Broker.NAME, getTestName()); - MemoryConfigurationEntryStore initialStoreFile = createStore(brokerId, brokerAttributes); - MemoryConfigurationEntryStore store = new MemoryConfigurationEntryStore(getSystemContext(), null, initialStoreFile, Collections.<String,String>emptyMap()); - - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - assertEquals("Unexpected root entry", brokerId, root.getId()); - Map<String, Object> attributes = root.getAttributes(); - assertNotNull("Attributes not found", attributes); - assertEquals("Unexpected number of attributes", 1, attributes.size()); - assertEquals("Unexpected name attribute", getTestName(), attributes.get(Broker.NAME)); - } - - - public void testOpenWithDefaultInitialStore() throws Exception - { - // check whether QPID_HOME JVM system property is set - if (QPID_HOME == null) - { - // set the properties in order to resolve the defaults store settings - setTestSystemProperty("QPID_HOME", TMP_FOLDER); - setTestSystemProperty("QPID_WORK", TMP_FOLDER + File.separator + "work"); - } - MemoryConfigurationEntryStore initialStore = new MemoryConfigurationEntryStore(getSystemContext(),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(getSystemContext(), null, initialStore, Collections.<String,String>emptyMap()); - - ConfigurationEntry root = store.getRootEntry(); - assertNotNull("Root entry is not found", root); - - assertEquals("Unexpected broker attributes", initialStoreRoot.getAttributes(), root.getAttributes()); - assertEquals("Unexpected broker children", initialStoreRoot.getChildrenIds(), root.getChildrenIds()); - } - - public void testGetVersion() - { - assertEquals("Unexpected version", 1, getStore().getVersion()); - } - - public void testGetType() - { - assertEquals("Unexpected type", "memory", getStore().getType()); - } - -} diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java index 4d92610875..6cfcf430b2 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/configuration/store/StoreConfigurationChangeListenerTest.java @@ -21,32 +21,32 @@ package org.apache.qpid.server.configuration.store; import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.any; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.util.UUID; -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.State; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.test.utils.QpidTestCase; public class StoreConfigurationChangeListenerTest extends QpidTestCase { - private ConfigurationEntryStore _store; + private DurableConfigurationStore _store; private StoreConfigurationChangeListener _listener; protected void setUp() throws Exception { super.setUp(); - _store = mock(ConfigurationEntryStore.class); + _store = mock(DurableConfigurationStore.class); _listener = new StoreConfigurationChangeListener(_store); } diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java deleted file mode 100644 index e72880e19a..0000000000 --- a/java/broker-core/src/test/java/org/apache/qpid/server/model/configuration/ConfigurationEntryTest.java +++ /dev/null @@ -1,130 +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.configuration; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -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.Set; -import java.util.UUID; - -import junit.framework.TestCase; - -import org.apache.qpid.server.configuration.ConfigurationEntry; -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; - -public class ConfigurationEntryTest extends TestCase -{ - public void testGetChildren() - { - MemoryConfigurationEntryStore store = mock(MemoryConfigurationEntryStore.class); - - ConfigurationEntry virtualHostEntry1 = new ConfigurationEntryImpl(UUID.randomUUID(), VirtualHost.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); - ConfigurationEntry virtualHostEntry2 = new ConfigurationEntryImpl(UUID.randomUUID(), VirtualHost.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); - ConfigurationEntry portEntry = new ConfigurationEntryImpl(UUID.randomUUID(), Port.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), store); - - when(store.getEntry(virtualHostEntry1.getId())).thenReturn(virtualHostEntry1); - when(store.getEntry(virtualHostEntry2.getId())).thenReturn(virtualHostEntry2); - when(store.getEntry(portEntry.getId())).thenReturn(portEntry); - - Set<UUID> childrenIds = new HashSet<UUID>(); - childrenIds.add(virtualHostEntry1.getId()); - childrenIds.add(virtualHostEntry2.getId()); - childrenIds.add(portEntry.getId()); - ConfigurationEntry parentEntry = new ConfigurationEntryImpl(UUID.randomUUID(), Broker.class.getSimpleName(), - Collections.<String, Object> emptyMap(), childrenIds, store); - - Map<String, Collection<ConfigurationEntry>> children = parentEntry.getChildren(); - assertNotNull("Null is returned for children", children); - assertEquals("Unexpected size", 2, children.size()); - Collection<ConfigurationEntry> virtualHosts = children.get(VirtualHost.class.getSimpleName()); - Collection<ConfigurationEntry> ports = children.get(Port.class.getSimpleName()); - assertEquals("Unexpected virtual hosts", - new HashSet<ConfigurationEntry>(Arrays.asList(virtualHostEntry1, virtualHostEntry2)), - new HashSet<ConfigurationEntry>(virtualHosts)); - assertEquals("Unexpected ports", new HashSet<ConfigurationEntry>(Arrays.asList(portEntry)), - new HashSet<ConfigurationEntry>(ports)); - } - - public void testHashCode() - { - MemoryConfigurationEntryStore store = mock(MemoryConfigurationEntryStore.class); - - UUID id = UUID.randomUUID(); - ConfigurationEntry entry1 = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); - ConfigurationEntry entry2 = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), - Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); - ConfigurationEntry entryWithDifferentId = new ConfigurationEntryImpl(UUID.randomUUID(), - VirtualHost.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.singleton(UUID.randomUUID()), store); - - assertTrue(entry1.hashCode() == entry2.hashCode()); - assertFalse(entry1.hashCode() == entryWithDifferentId.hashCode()); - } - - public void testEqualsObject() - { - 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 ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), attributes1, - childrenIds, store); - - Map<String, Object> attributes2 = new HashMap<String, Object>(); - attributes2.put(VirtualHost.NAME, "name2"); - - ConfigurationEntry entry2 = new ConfigurationEntryImpl(id, VirtualHost.class.getSimpleName(), attributes1, - childrenIds, store); - 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 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 ConfigurationEntryImpl(id, - VirtualHost.class.getSimpleName(), attributes2, childrenIds, store); - assertFalse("Entries should be different because of different attributes", entry1.equals(entryWithDifferentName)); - - 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/java/broker-core/src/test/java/org/apache/qpid/server/store/AbstractDurableConfigurationStoreTestCase.java b/java/broker-core/src/test/java/org/apache/qpid/server/store/AbstractDurableConfigurationStoreTestCase.java index 4ddf421901..6d84c7b602 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/store/AbstractDurableConfigurationStoreTestCase.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/store/AbstractDurableConfigurationStoreTestCase.java @@ -114,7 +114,7 @@ public abstract class AbstractDurableConfigurationStoreTestCase extends QpidTest _parent = createVirtualHostNode(_storePath, _factory); _configStore = createConfigStore(); - _configStore.openConfigurationStore(_parent); + _configStore.openConfigurationStore(_parent, false); _rootRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), VirtualHost.class.getSimpleName(), Collections.<String, Object>emptyMap()); _configStore.create(_rootRecord); } @@ -263,14 +263,14 @@ public abstract class AbstractDurableConfigurationStoreTestCase extends QpidTest private boolean matchesParents(ConfiguredObjectRecord binding) { - Map<String, ConfiguredObjectRecord> bindingParents = binding.getParents(); + Map<String, UUID> bindingParents = binding.getParents(); if(bindingParents.size() != _parents.size()) { return false; } for(Map.Entry<String,UUID> entry : _parents.entrySet()) { - if(!bindingParents.get(entry.getKey()).getId().equals(entry.getValue())) + if(!bindingParents.get(entry.getKey()).equals(entry.getValue())) { return false; } @@ -490,7 +490,7 @@ public abstract class AbstractDurableConfigurationStoreTestCase extends QpidTest when(objectRecord.getId()).thenReturn(_queueId); when(objectRecord.getType()).thenReturn(Queue.class.getSimpleName()); when(objectRecord.getAttributes()).thenReturn(attributes); - when(objectRecord.getParents()).thenReturn(Collections.singletonMap(_rootRecord.getType(), _rootRecord)); + when(objectRecord.getParents()).thenReturn(Collections.singletonMap(_rootRecord.getType(), _rootRecord.getId())); when(queue.asObjectRecord()).thenReturn(objectRecord); return queue; } @@ -516,7 +516,7 @@ public abstract class AbstractDurableConfigurationStoreTestCase extends QpidTest when(exchangeRecord.getId()).thenReturn(_exchangeId); when(exchangeRecord.getType()).thenReturn(Exchange.class.getSimpleName()); when(exchangeRecord.getAttributes()).thenReturn(actualAttributes); - when(exchangeRecord.getParents()).thenReturn(Collections.singletonMap(_rootRecord.getType(), _rootRecord)); + when(exchangeRecord.getParents()).thenReturn(Collections.singletonMap(_rootRecord.getType(), _rootRecord.getId())); when(exchange.asObjectRecord()).thenReturn(exchangeRecord); when(exchange.getEventLogger()).thenReturn(new EventLogger()); return exchange; @@ -526,7 +526,7 @@ public abstract class AbstractDurableConfigurationStoreTestCase extends QpidTest { closeConfigStore(); _configStore = createConfigStore(); - _configStore.openConfigurationStore(_parent); + _configStore.openConfigurationStore(_parent, false); } protected abstract DurableConfigurationStore createConfigStore() throws Exception; diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/store/BrokerRecovererTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/store/BrokerRecovererTest.java index 36c5eec108..638f21d82c 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/store/BrokerRecovererTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/store/BrokerRecovererTest.java @@ -42,9 +42,9 @@ import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.BrokerModel; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.GroupProvider; +import org.apache.qpid.server.model.JsonSystemConfigImpl; import org.apache.qpid.server.model.Port; -import org.apache.qpid.server.model.SystemContext; -import org.apache.qpid.server.model.SystemContextImpl; +import org.apache.qpid.server.model.SystemConfig; public class BrokerRecovererTest extends TestCase { @@ -53,7 +53,7 @@ public class BrokerRecovererTest extends TestCase private UUID _brokerId = UUID.randomUUID(); private AuthenticationProvider<?> _authenticationProvider1; private UUID _authenticationProvider1Id = UUID.randomUUID(); - private SystemContext<?> _systemContext; + private SystemConfig<?> _systemConfig; private TaskExecutor _taskExecutor; @Override @@ -63,8 +63,8 @@ public class BrokerRecovererTest extends TestCase _taskExecutor = new CurrentThreadTaskExecutor(); _taskExecutor.start(); - _systemContext = new SystemContextImpl(_taskExecutor, - mock(EventLogger.class), mock(LogRecorder.class), mock(BrokerOptions.class)); + _systemConfig = new JsonSystemConfigImpl(_taskExecutor, + mock(EventLogger.class), mock(LogRecorder.class), new BrokerOptions()); when(_brokerEntry.getId()).thenReturn(_brokerId); when(_brokerEntry.getType()).thenReturn(Broker.class.getSimpleName()); @@ -73,7 +73,8 @@ public class BrokerRecovererTest extends TestCase attributesMap.put(Broker.NAME, getName()); when(_brokerEntry.getAttributes()).thenReturn(attributesMap); - when(_brokerEntry.getParents()).thenReturn(Collections.singletonMap(SystemContext.class.getSimpleName(), _systemContext.asObjectRecord())); + when(_brokerEntry.getParents()).thenReturn(Collections.singletonMap(SystemConfig.class.getSimpleName(), _systemConfig + .getId())); //Add a base AuthenticationProvider for all tests _authenticationProvider1 = mock(AuthenticationProvider.class); @@ -115,7 +116,7 @@ public class BrokerRecovererTest extends TestCase when(_brokerEntry.getAttributes()).thenReturn(entryAttributes); resolveObjects(_brokerEntry); - Broker<?> broker = _systemContext.getBroker(); + Broker<?> broker = _systemConfig.getBroker(); assertNotNull(broker); @@ -137,7 +138,7 @@ public class BrokerRecovererTest extends TestCase authProviderAttrs.put(AuthenticationProvider.TYPE, "Anonymous"); return new ConfiguredObjectRecordImpl(id, AuthenticationProvider.class.getSimpleName(), authProviderAttrs, Collections - .singletonMap(Broker.class.getSimpleName(), _brokerEntry)); + .singletonMap(Broker.class.getSimpleName(), _brokerEntry.getId())); } @@ -149,7 +150,7 @@ public class BrokerRecovererTest extends TestCase groupProviderAttrs.put("path", "/no-such-path"); return new ConfiguredObjectRecordImpl(id, GroupProvider.class.getSimpleName(), groupProviderAttrs, Collections - .singletonMap(Broker.class.getSimpleName(), _brokerEntry)); + .singletonMap(Broker.class.getSimpleName(), _brokerEntry.getId())); } public ConfiguredObjectRecord createPortRecord(UUID id, int port, Object authProviderRef) @@ -161,7 +162,7 @@ public class BrokerRecovererTest extends TestCase portAttrs.put(Port.AUTHENTICATION_PROVIDER, authProviderRef); return new ConfiguredObjectRecordImpl(id, Port.class.getSimpleName(), portAttrs, Collections - .singletonMap(Broker.class.getSimpleName(), _brokerEntry)); + .singletonMap(Broker.class.getSimpleName(), _brokerEntry.getId())); } @@ -174,7 +175,7 @@ public class BrokerRecovererTest extends TestCase portId, 5672, "authProvider")); - Broker<?> broker = _systemContext.getBroker(); + Broker<?> broker = _systemConfig.getBroker(); assertNotNull(broker); @@ -188,7 +189,7 @@ public class BrokerRecovererTest extends TestCase UUID authProviderId = UUID.randomUUID(); resolveObjects(_brokerEntry, createAuthProviderRecord(authProviderId, "authProvider")); - Broker<?> broker = _systemContext.getBroker(); + Broker<?> broker = _systemConfig.getBroker(); assertNotNull(broker); @@ -210,7 +211,7 @@ public class BrokerRecovererTest extends TestCase createPortRecord(portId, 5672, "authProvider"), createAuthProviderRecord(authProvider2Id, "authProvider2"), createPortRecord(port2Id, 5673, "authProvider2")); - Broker<?> broker = _systemContext.getBroker(); + Broker<?> broker = _systemConfig.getBroker(); assertNotNull(broker); @@ -228,7 +229,7 @@ public class BrokerRecovererTest extends TestCase UUID authProviderId = UUID.randomUUID(); resolveObjects(_brokerEntry, createGroupProviderRecord(authProviderId, "groupProvider")); - Broker<?> broker = _systemContext.getBroker(); + Broker<?> broker = _systemConfig.getBroker(); assertNotNull(broker); @@ -253,7 +254,7 @@ public class BrokerRecovererTest extends TestCase try { resolveObjects(_brokerEntry); - Broker<?> broker = _systemContext.getBroker(); + Broker<?> broker = _systemConfig.getBroker(); broker.open(); fail("The broker creation should fail due to unsupported model version"); } @@ -278,7 +279,7 @@ public class BrokerRecovererTest extends TestCase try { UnresolvedConfiguredObject<? extends ConfiguredObject> recover = - _systemContext.getObjectFactory().recover(_brokerEntry, _systemContext); + _systemConfig.getObjectFactory().recover(_brokerEntry, _systemConfig); Broker<?> broker = (Broker<?>) recover.resolve(); broker.open(); @@ -305,7 +306,7 @@ public class BrokerRecovererTest extends TestCase try { UnresolvedConfiguredObject<? extends ConfiguredObject> recover = - _systemContext.getObjectFactory().recover(_brokerEntry, _systemContext); + _systemConfig.getObjectFactory().recover(_brokerEntry, _systemConfig); Broker<?> broker = (Broker<?>) recover.resolve(); broker.open(); fail("The broker creation should fail due to unsupported model version"); @@ -324,7 +325,7 @@ public class BrokerRecovererTest extends TestCase private void resolveObjects(ConfiguredObjectRecord... records) { - GenericRecoverer recoverer = new GenericRecoverer(_systemContext, Broker.class.getSimpleName()); + GenericRecoverer recoverer = new GenericRecoverer(_systemConfig, Broker.class.getSimpleName()); recoverer.recover(Arrays.asList(records)); } diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/store/BrokerStoreUpgraderAndRecovererTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/store/BrokerStoreUpgraderAndRecovererTest.java index 479c117e19..aba7e460bf 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/store/BrokerStoreUpgraderAndRecovererTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/store/BrokerStoreUpgraderAndRecovererTest.java @@ -33,8 +33,8 @@ import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor; import org.apache.qpid.server.logging.EventLogger; import org.apache.qpid.server.logging.LogRecorder; import org.apache.qpid.server.model.ConfiguredObject; -import org.apache.qpid.server.model.SystemContext; -import org.apache.qpid.server.model.SystemContextImpl; +import org.apache.qpid.server.model.JsonSystemConfigImpl; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; import org.apache.qpid.test.utils.QpidTestCase; @@ -43,7 +43,7 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase { private ConfiguredObjectRecord _brokerRecord; private CurrentThreadTaskExecutor _taskExecutor; - private SystemContext<?> _systemContext; + private SystemConfig<?> _systemConfig; public void setUp() throws Exception { @@ -57,10 +57,10 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase _brokerRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "Broker", brokerAttributes); _taskExecutor = new CurrentThreadTaskExecutor(); _taskExecutor.start(); - _systemContext = new SystemContextImpl(_taskExecutor, + _systemConfig = new JsonSystemConfigImpl(_taskExecutor, mock(EventLogger.class), mock(LogRecorder.class), - mock(BrokerOptions.class)); + new BrokerOptions()); } public void testUpgradeVirtualHostWithJDBCStoreAndBoneCPPool() @@ -84,10 +84,10 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", - hostAttributes, Collections.<String,ConfiguredObjectRecord>singletonMap("Broker", _brokerRecord)); + hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); - BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemContext); + BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = recoverer.upgrade(dcs); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); @@ -132,10 +132,10 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", - hostAttributes, Collections.<String,ConfiguredObjectRecord>singletonMap("Broker", _brokerRecord)); + hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); - BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemContext); + BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = recoverer.upgrade(dcs); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); @@ -171,10 +171,10 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase hostAttributes.put("type", "STANDARD"); ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", - hostAttributes, Collections.<String,ConfiguredObjectRecord>singletonMap("Broker", _brokerRecord)); + hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); - BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemContext); + BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = recoverer.upgrade(dcs); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); @@ -202,10 +202,10 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", - hostAttributes, Collections.<String,ConfiguredObjectRecord>singletonMap("Broker", _brokerRecord)); + hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); - BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemContext); + BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = recoverer.upgrade(dcs); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); @@ -240,10 +240,10 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", - hostAttributes, Collections.<String,ConfiguredObjectRecord>singletonMap("Broker", _brokerRecord)); + hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); - BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemContext); + BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = recoverer.upgrade(dcs); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); @@ -278,10 +278,10 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase hostAttributes.put("type", "STANDARD"); ConfiguredObjectRecord virtualHostRecord = new ConfiguredObjectRecordImpl(UUID.randomUUID(), "VirtualHost", - hostAttributes, Collections.<String,ConfiguredObjectRecord>singletonMap("Broker", _brokerRecord)); + hostAttributes, Collections.singletonMap("Broker", _brokerRecord.getId())); DurableConfigurationStore dcs = new DurableConfigurationStoreStub(_brokerRecord, virtualHostRecord); - BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemContext); + BrokerStoreUpgraderAndRecoverer recoverer = new BrokerStoreUpgraderAndRecoverer(_systemConfig); List<ConfiguredObjectRecord> records = recoverer.upgrade(dcs); ConfiguredObjectRecord upgradedVirtualHostNodeRecord = findRecordById(virtualHostRecord.getId(), records); @@ -317,7 +317,9 @@ public class BrokerStoreUpgraderAndRecovererTest extends QpidTestCase } @Override - public void openConfigurationStore(ConfiguredObject<?> parent) throws StoreException + public void openConfigurationStore(ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) throws StoreException { } diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreConfigurationTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreConfigurationTest.java index 62cbe409a9..14d2cb15d9 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreConfigurationTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreConfigurationTest.java @@ -20,13 +20,14 @@ */ package org.apache.qpid.server.store; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.qpid.server.model.ConfiguredObjectFactory; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class JsonFileConfigStoreConfigurationTest extends AbstractDurableConfigurationStoreTestCase { @Override @@ -44,6 +45,6 @@ public class JsonFileConfigStoreConfigurationTest extends AbstractDurableConfigu @Override protected DurableConfigurationStore createConfigStore() throws Exception { - return new JsonFileConfigStore(); + return new JsonFileConfigStore(VirtualHost.class); } } diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreTest.java index e9f3ba3d21..ee8f6497bc 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/store/JsonFileConfigStoreTest.java @@ -34,18 +34,20 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; +import org.mockito.ArgumentMatcher; +import org.mockito.InOrder; + import org.apache.qpid.server.model.BrokerModel; import org.apache.qpid.server.model.ConfiguredObjectFactory; import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; import org.apache.qpid.server.model.Queue; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler; import org.apache.qpid.server.util.ServerScopedRuntimeException; import org.apache.qpid.server.virtualhostnode.JsonVirtualHostNode; import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.test.utils.TestFileUtils; import org.apache.qpid.util.FileUtils; -import org.mockito.ArgumentMatcher; -import org.mockito.InOrder; public class JsonFileConfigStoreTest extends QpidTestCase { @@ -74,7 +76,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase _storeLocation = TestFileUtils.createTestDirectory("json", true); when(_parent.getStorePath()).thenReturn(_storeLocation.getAbsolutePath()); - _store = new JsonFileConfigStore(); + _store = new JsonFileConfigStore(VirtualHost.class); _handler = mock(ConfiguredObjectRecordHandler.class); when(_handler.handle(any(ConfiguredObjectRecord.class))).thenReturn(true); @@ -99,7 +101,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase try { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); fail("Store should not successfully configure if there is no path set"); } catch (ServerScopedRuntimeException e) @@ -114,7 +116,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase when(_parent.getStorePath()).thenReturn(System.getProperty("file.separator")); try { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); fail("Store should not successfully configure if there is an invalid path set"); } catch (ServerScopedRuntimeException e) @@ -125,7 +127,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testVisitEmptyStore() { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); _store.visitConfiguredObjectRecords(_handler); InOrder inorder = inOrder(_handler); @@ -138,17 +140,17 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testInsertAndUpdateTopLevelObject() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); createRootRecord(); _store.closeConfigurationStore(); - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); Map<String, Object> newAttributes = new HashMap<String, Object>(_rootRecord.getAttributes()); newAttributes.put("attributeName", "attributeValue"); _store.update(false, new ConfiguredObjectRecordImpl(_rootRecord.getId(), _rootRecord.getType(), newAttributes)); _store.closeConfigurationStore(); - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); _store.visitConfiguredObjectRecords(_handler); @@ -159,7 +161,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testCreateObject() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); createRootRecord(); final UUID queueId = new UUID(0, 1); @@ -169,7 +171,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase _store.create(new ConfiguredObjectRecordImpl(queueId, queueType, queueAttr, getRootAsParentMap())); _store.closeConfigurationStore(); - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); _store.visitConfiguredObjectRecords(_handler); verify(_handler).handle(matchesRecord(queueId, queueType, queueAttr)); @@ -179,7 +181,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testCreateAndUpdateObject() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); createRootRecord(); final UUID queueId = new UUID(0, 1); @@ -194,7 +196,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase _store.closeConfigurationStore(); - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); _store.visitConfiguredObjectRecords(_handler); verify(_handler, times(1)).handle(matchesRecord(queueId, queueType, queueAttr)); _store.closeConfigurationStore(); @@ -203,7 +205,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testCreateAndRemoveObject() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); createRootRecord(); final UUID queueId = new UUID(0, 1); @@ -218,7 +220,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase _store.closeConfigurationStore(); - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); _store.visitConfiguredObjectRecords(_handler); verify(_handler, times(1)).handle(matchesRecord(ANY_UUID, VIRTUAL_HOST_TYPE, ANY_MAP)); _store.closeConfigurationStore(); @@ -226,7 +228,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testCreateUnknownObjectType() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); createRootRecord(); try @@ -242,7 +244,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testTwoObjectsWithSameId() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); createRootRecord(); final UUID id = UUID.randomUUID(); @@ -261,13 +263,13 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testChangeTypeOfObject() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); createRootRecord(); final UUID id = UUID.randomUUID(); _store.create(new ConfiguredObjectRecordImpl(id, "Queue", Collections.<String, Object>emptyMap(), getRootAsParentMap())); _store.closeConfigurationStore(); - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); try { @@ -282,13 +284,13 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testLockFileGuaranteesExclusiveAccess() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); - JsonFileConfigStore secondStore = new JsonFileConfigStore(); + JsonFileConfigStore secondStore = new JsonFileConfigStore(VirtualHost.class); try { - secondStore.openConfigurationStore(_parent); + secondStore.openConfigurationStore(_parent, false); fail("Should not be able to open a second store with the same path"); } catch(ServerScopedRuntimeException e) @@ -296,7 +298,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase // pass } _store.closeConfigurationStore(); - secondStore.openConfigurationStore(_parent); + secondStore.openConfigurationStore(_parent, false); } public void testStoreFileLifecycle() @@ -307,7 +309,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase assertFalse("JSON store should not exist", expectedJsonFile.exists()); assertFalse("JSON backup should not exist", expectedJsonFileBak.exists()); - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); assertTrue("JSON store should exist after open", expectedJsonFile.exists()); assertFalse("JSON backup should not exist after open", expectedJsonFileBak.exists()); @@ -321,7 +323,7 @@ public class JsonFileConfigStoreTest extends QpidTestCase public void testCreatedNestedObjects() throws Exception { - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); createRootRecord(); final UUID queueId = new UUID(0, 1); @@ -333,28 +335,28 @@ public class JsonFileConfigStoreTest extends QpidTestCase final UUID bindingId = new UUID(0, 3); final UUID binding2Id = new UUID(1, 3); - Map<String, ConfiguredObjectRecord> parents = getRootAsParentMap(); + Map<String, UUID> parents = getRootAsParentMap(); final ConfiguredObjectRecordImpl queueRecord = new ConfiguredObjectRecordImpl(queueId, "Queue", EMPTY_ATTR, parents); _store.create(queueRecord); final ConfiguredObjectRecordImpl queue2Record = new ConfiguredObjectRecordImpl(queue2Id, "Queue", EMPTY_ATTR, parents); _store.create(queue2Record); final ConfiguredObjectRecordImpl exchangeRecord = new ConfiguredObjectRecordImpl(exchangeId, "Exchange", EMPTY_ATTR, parents); _store.create(exchangeRecord); - Map<String,ConfiguredObjectRecord> bindingParents = new HashMap<String, ConfiguredObjectRecord>(); - bindingParents.put("Exchange", exchangeRecord); - bindingParents.put("Queue", queueRecord); + Map<String,UUID> bindingParents = new HashMap(); + bindingParents.put("Exchange", exchangeRecord.getId()); + bindingParents.put("Queue", queueRecord.getId()); final ConfiguredObjectRecordImpl bindingRecord = new ConfiguredObjectRecordImpl(bindingId, "Binding", EMPTY_ATTR, bindingParents); - Map<String,ConfiguredObjectRecord> binding2Parents = new HashMap<String, ConfiguredObjectRecord>(); - binding2Parents.put("Exchange", exchangeRecord); - binding2Parents.put("Queue", queue2Record); + Map<String,UUID> binding2Parents = new HashMap(); + binding2Parents.put("Exchange", exchangeRecord.getId()); + binding2Parents.put("Queue", queue2Record.getId()); final ConfiguredObjectRecordImpl binding2Record = new ConfiguredObjectRecordImpl(binding2Id, "Binding", EMPTY_ATTR, binding2Parents); _store.update(true, bindingRecord, binding2Record); _store.closeConfigurationStore(); - _store.openConfigurationStore(_parent); + _store.openConfigurationStore(_parent, false); _store.visitConfiguredObjectRecords(_handler); verify(_handler).handle(matchesRecord(queueId, "Queue", EMPTY_ATTR)); verify(_handler).handle(matchesRecord(queue2Id, "Queue", EMPTY_ATTR)); @@ -373,9 +375,9 @@ public class JsonFileConfigStoreTest extends QpidTestCase _store.create(_rootRecord); } - private Map<String, ConfiguredObjectRecord> getRootAsParentMap() + private Map<String, UUID> getRootAsParentMap() { - return Collections.<String, ConfiguredObjectRecord>singletonMap(VIRTUAL_HOST_TYPE, _rootRecord); + return Collections.singletonMap(VIRTUAL_HOST_TYPE, _rootRecord.getId()); } private ConfiguredObjectRecord matchesRecord(UUID id, String type, Map<String, Object> attributes) diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java b/java/broker-core/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java index 4272b89abb..9c8f4ed3ae 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/util/BrokerTestHelper.java @@ -44,7 +44,7 @@ import org.apache.qpid.server.model.ConfiguredObjectFactory; import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; import org.apache.qpid.server.model.Exchange; import org.apache.qpid.server.model.Queue; -import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; @@ -73,11 +73,11 @@ public class BrokerTestHelper ConfiguredObjectFactory objectFactory = new ConfiguredObjectFactoryImpl(BrokerModel.getInstance()); EventLogger eventLogger = new EventLogger(); - SystemContext systemContext = mock(SystemContext.class); - when(systemContext.getEventLogger()).thenReturn(eventLogger); - when(systemContext.getObjectFactory()).thenReturn(objectFactory); - when(systemContext.getModel()).thenReturn(objectFactory.getModel()); - when(systemContext.getCategoryClass()).thenReturn(SystemContext.class); + SystemConfig systemConfig = mock(SystemConfig.class); + when(systemConfig.getEventLogger()).thenReturn(eventLogger); + when(systemConfig.getObjectFactory()).thenReturn(objectFactory); + when(systemConfig.getModel()).thenReturn(objectFactory.getModel()); + when(systemConfig.getCategoryClass()).thenReturn(SystemConfig.class); SubjectCreator subjectCreator = mock(SubjectCreator.class); when(subjectCreator.getMechanisms()).thenReturn(Collections.<String>emptyList()); @@ -92,10 +92,10 @@ public class BrokerTestHelper when(broker.getModel()).thenReturn(objectFactory.getModel()); when(broker.getEventLogger()).thenReturn(eventLogger); when(broker.getCategoryClass()).thenReturn(Broker.class); - when(broker.getParent(SystemContext.class)).thenReturn(systemContext); + when(broker.getParent(SystemConfig.class)).thenReturn(systemConfig); when(broker.getTaskExecutor()).thenReturn(TASK_EXECUTOR); - when(systemContext.getTaskExecutor()).thenReturn(TASK_EXECUTOR); + when(systemConfig.getTaskExecutor()).thenReturn(TASK_EXECUTOR); return broker; } diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostQueueCreationTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostQueueCreationTest.java index a360ba3571..78793726a8 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostQueueCreationTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostQueueCreationTest.java @@ -42,7 +42,7 @@ import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; 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.SystemContext; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.queue.AMQQueue; @@ -74,13 +74,13 @@ public class VirtualHostQueueCreationTest extends QpidTestCase _taskExecutor = new CurrentThreadTaskExecutor(); _taskExecutor.start(); - SystemContext<?> context = mock(SystemContext.class); + SystemConfig<?> context = mock(SystemConfig.class); when(context.getEventLogger()).thenReturn(eventLogger); Broker broker = mock(Broker.class); when(broker.getObjectFactory()).thenReturn(objectFactory); when(broker.getCategoryClass()).thenReturn(Broker.class); - when(broker.getParent(SystemContext.class)).thenReturn(context); + when(broker.getParent(SystemConfig.class)).thenReturn(context); when(broker.getSecurityManager()).thenReturn(securityManager); when(broker.getModel()).thenReturn(objectFactory.getModel()); when(broker.getTaskExecutor()).thenReturn(_taskExecutor); diff --git a/java/broker-core/src/test/java/org/apache/qpid/server/virtualhostnode/AbstractStandardVirtualHostNodeTest.java b/java/broker-core/src/test/java/org/apache/qpid/server/virtualhostnode/AbstractStandardVirtualHostNodeTest.java index 884e729c52..19436627ce 100644 --- a/java/broker-core/src/test/java/org/apache/qpid/server/virtualhostnode/AbstractStandardVirtualHostNodeTest.java +++ b/java/broker-core/src/test/java/org/apache/qpid/server/virtualhostnode/AbstractStandardVirtualHostNodeTest.java @@ -37,7 +37,7 @@ import org.apache.qpid.server.model.BrokerModel; import org.apache.qpid.server.model.ConfiguredObjectFactoryImpl; import org.apache.qpid.server.model.Model; import org.apache.qpid.server.model.State; -import org.apache.qpid.server.model.SystemContext; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.security.SecurityManager; @@ -67,8 +67,8 @@ public class AbstractStandardVirtualHostNodeTest extends QpidTestCase super.setUp(); _broker = BrokerTestHelper.createBrokerMock(); - SystemContext<?> systemContext = _broker.getParent(SystemContext.class); - when(systemContext.getObjectFactory()).thenReturn(new ConfiguredObjectFactoryImpl(mock(Model.class))); + SystemConfig<?> systemConfig = _broker.getParent(SystemConfig.class); + when(systemConfig.getObjectFactory()).thenReturn(new ConfiguredObjectFactoryImpl(mock(Model.class))); _taskExecutor = new CurrentThreadTaskExecutor(); _taskExecutor.start(); diff --git a/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java b/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java index fdf08a9940..5866319985 100644 --- a/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java +++ b/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyConfigurationStore.java @@ -48,9 +48,17 @@ public class DerbyConfigurationStore extends AbstractJDBCConfigurationStore private String _storeLocation; private ConfiguredObject<?> _parent; + private final Class<? extends ConfiguredObject> _rootClass; + + public DerbyConfigurationStore(final Class<? extends ConfiguredObject> rootClass) + { + _rootClass = rootClass; + } @Override - public void openConfigurationStore(ConfiguredObject<?> parent) + public void openConfigurationStore(ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) throws StoreException { if (_configurationStoreOpen.compareAndSet(false, true)) @@ -62,7 +70,12 @@ public class DerbyConfigurationStore extends AbstractJDBCConfigurationStore _storeLocation = settings.getStorePath(); _connectionURL = DerbyUtils.createConnectionUrl(parent.getName(), _storeLocation); - createOrOpenConfigurationStoreDatabase(); + createOrOpenConfigurationStoreDatabase(overwrite); + + if(hasNoConfigurationEntries()) + { + update(true, initialRecords); + } } } diff --git a/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java b/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java new file mode 100644 index 0000000000..d3a1fa2bbc --- /dev/null +++ b/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfig.java @@ -0,0 +1,39 @@ +/* + * + * 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.derby; + +import org.apache.qpid.server.model.ManagedAttribute; +import org.apache.qpid.server.model.SystemConfig; +import org.apache.qpid.server.store.FileBasedSettings; +import org.apache.qpid.server.store.SizeMonitoringSettings; + +public interface DerbySystemConfig<X extends DerbySystemConfig<X>> extends SystemConfig<X>, FileBasedSettings, + SizeMonitoringSettings +{ + @ManagedAttribute(mandatory = true) + String getStorePath(); + + @ManagedAttribute(mandatory = true, defaultValue = "0") + Long getStoreUnderfullSize(); + + @ManagedAttribute(mandatory = true, defaultValue = "0") + Long getStoreOverfullSize(); +} diff --git a/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java b/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java new file mode 100644 index 0000000000..32c5bcd541 --- /dev/null +++ b/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbySystemConfigImpl.java @@ -0,0 +1,78 @@ +/* + * + * 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.derby; + +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.model.AbstractSystemConfig; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedAttributeField; +import org.apache.qpid.server.model.ManagedObject; +import org.apache.qpid.server.model.SystemConfigFactoryConstructor; +import org.apache.qpid.server.store.DurableConfigurationStore; + +@ManagedObject(category = false, type = DerbySystemConfigImpl.SYSTEM_CONFIG_TYPE) +public class DerbySystemConfigImpl extends AbstractSystemConfig<DerbySystemConfigImpl> implements DerbySystemConfig<DerbySystemConfigImpl> +{ + public static final String SYSTEM_CONFIG_TYPE = "DERBY"; + + @ManagedAttributeField + private String _storePath; + @ManagedAttributeField + private Long _storeUnderfullSize; + @ManagedAttributeField + private Long _storeOverfullSize; + + @SystemConfigFactoryConstructor + public DerbySystemConfigImpl(final TaskExecutor taskExecutor, + final EventLogger eventLogger, + final LogRecorder logRecorder, + final BrokerOptions brokerOptions) + { + super(taskExecutor, eventLogger, logRecorder, brokerOptions); + } + + @Override + protected DurableConfigurationStore createStoreObject() + { + return new DerbyConfigurationStore(Broker.class); + } + + @Override + public String getStorePath() + { + return _storePath; + } + + @Override + public Long getStoreUnderfullSize() + { + return _storeUnderfullSize; + } + + @Override + public Long getStoreOverfullSize() + { + return _storeOverfullSize; + } +} diff --git a/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java b/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java index ae440014c7..4bb3cc5376 100644 --- a/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java +++ b/java/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/virtualhostnode/derby/DerbyVirtualHostNodeImpl.java @@ -28,6 +28,7 @@ import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ManagedAttributeField; import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.derby.DerbyConfigurationStore; import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; @@ -55,7 +56,7 @@ public class DerbyVirtualHostNodeImpl extends AbstractStandardVirtualHostNode<De @Override protected DurableConfigurationStore createConfigurationStore() { - return new DerbyConfigurationStore(); + return new DerbyConfigurationStore(VirtualHost.class); } @Override diff --git a/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java b/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java index 849bd066c7..4a71fe2faf 100644 --- a/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java +++ b/java/broker-plugins/derby-store/src/test/java/org/apache/qpid/server/store/derby/DerbyMessageStoreConfigurationTest.java @@ -20,14 +20,15 @@ */ package org.apache.qpid.server.store.derby; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.qpid.server.model.ConfiguredObjectFactory; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.model.VirtualHostNode; import org.apache.qpid.server.store.AbstractDurableConfigurationStoreTestCase; import org.apache.qpid.server.virtualhostnode.derby.DerbyVirtualHostNode; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class DerbyMessageStoreConfigurationTest extends AbstractDurableConfigurationStoreTestCase { @@ -42,7 +43,7 @@ public class DerbyMessageStoreConfigurationTest extends AbstractDurableConfigura @Override protected DerbyConfigurationStore createConfigStore() throws Exception { - return new DerbyConfigurationStore(); + return new DerbyConfigurationStore(VirtualHost.class); } } diff --git a/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java b/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java index 6764b7b715..4f88e011fb 100644 --- a/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java +++ b/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java @@ -29,14 +29,18 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; +import javax.security.auth.Subject; + import org.apache.log4j.Logger; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.plugin.JDBCConnectionProviderFactory; import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.store.*; - -import javax.security.auth.Subject; +import org.apache.qpid.server.store.AbstractJDBCConfigurationStore; +import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.store.MessageStoreProvider; +import org.apache.qpid.server.store.StoreException; /** * Implementation of a DurableConfigurationStore backed by Generic JDBC Database @@ -60,9 +64,17 @@ public class GenericJDBCConfigurationStore extends AbstractJDBCConfigurationStor private boolean _useBytesMethodsForBlob; private ConfiguredObject<?> _parent; + private final Class<? extends ConfiguredObject> _rootClass; + + public GenericJDBCConfigurationStore(final Class<? extends ConfiguredObject> rootClass) + { + _rootClass = rootClass; + } @Override - public void openConfigurationStore(ConfiguredObject<?> parent) + public void openConfigurationStore(ConfiguredObject<?> parent, + final boolean overwrite, + final ConfiguredObjectRecord... initialRecords) throws StoreException { if (_configurationStoreOpen.compareAndSet(false, true)) @@ -117,7 +129,11 @@ public class GenericJDBCConfigurationStore extends AbstractJDBCConfigurationStor _useBytesMethodsForBlob = details.isUseBytesMethodsForBlob(); _bigIntType = details.getBigintType(); - createOrOpenConfigurationStoreDatabase(); + createOrOpenConfigurationStoreDatabase(overwrite); + if(hasNoConfigurationEntries()) + { + update(true, initialRecords); + } } } diff --git a/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java b/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java new file mode 100644 index 0000000000..9fe64577bb --- /dev/null +++ b/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfig.java @@ -0,0 +1,39 @@ +/* + * + * 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.jdbc; + +import org.apache.qpid.server.model.ManagedAttribute; +import org.apache.qpid.server.model.SystemConfig; + +public interface JDBCSystemConfig<X extends JDBCSystemConfig<X>> extends SystemConfig<X>, JDBCSettings +{ + @ManagedAttribute(mandatory=true, defaultValue = "${systemConfig.connectionUrl}") + String getConnectionUrl(); + + @ManagedAttribute(defaultValue=DefaultConnectionProviderFactory.TYPE) + String getConnectionPoolType(); + + @ManagedAttribute(defaultValue = "${systemConfig.username}") + String getUsername(); + + @ManagedAttribute(secure=true, defaultValue = "${systemConfig.password}") + String getPassword(); +} diff --git a/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java b/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java new file mode 100644 index 0000000000..fd1cad7de4 --- /dev/null +++ b/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/JDBCSystemConfigImpl.java @@ -0,0 +1,86 @@ +/* + * + * 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.jdbc; + +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.model.AbstractSystemConfig; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedAttributeField; +import org.apache.qpid.server.model.ManagedObject; +import org.apache.qpid.server.model.SystemConfigFactoryConstructor; +import org.apache.qpid.server.store.DurableConfigurationStore; + +@ManagedObject( category = false, type = JDBCSystemConfigImpl.SYSTEM_CONFIG_TYPE) +public class JDBCSystemConfigImpl extends AbstractSystemConfig<JDBCSystemConfigImpl> implements JDBCSystemConfig<JDBCSystemConfigImpl> +{ + public static final String SYSTEM_CONFIG_TYPE = "JDBC"; + + @ManagedAttributeField + private String _connectionUrl; + @ManagedAttributeField + private String _connectionPoolType; + @ManagedAttributeField + private String _username; + @ManagedAttributeField + private String _password; + + @SystemConfigFactoryConstructor + public JDBCSystemConfigImpl(final TaskExecutor taskExecutor, + final EventLogger eventLogger, + final LogRecorder logRecorder, + final BrokerOptions brokerOptions) + { + super(taskExecutor, eventLogger, logRecorder, brokerOptions); + } + + @Override + protected DurableConfigurationStore createStoreObject() + { + return new GenericJDBCConfigurationStore(Broker.class); + } + + @Override + public String getConnectionUrl() + { + return _connectionUrl; + } + + @Override + public String getConnectionPoolType() + { + return _connectionPoolType; + } + + @Override + public String getUsername() + { + return _username; + } + + @Override + public String getPassword() + { + return _password; + } +} diff --git a/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java b/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java index 01acb9e0b5..eab53e6744 100644 --- a/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java +++ b/java/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/virtualhostnode/jdbc/JDBCVirtualHostNodeImpl.java @@ -26,6 +26,7 @@ import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ManagedAttributeField; import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.jdbc.GenericJDBCConfigurationStore; import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; @@ -61,7 +62,7 @@ public class JDBCVirtualHostNodeImpl extends AbstractStandardVirtualHostNode<JDB @Override protected DurableConfigurationStore createConfigurationStore() { - return new GenericJDBCConfigurationStore(); + return new GenericJDBCConfigurationStore(VirtualHost.class); } @Override diff --git a/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryConfigurationStore.java b/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryConfigurationStore.java index 0b0e6705d5..81344c880f 100644 --- a/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryConfigurationStore.java +++ b/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryConfigurationStore.java @@ -21,9 +21,15 @@ package org.apache.qpid.server.store; +import org.apache.qpid.server.model.ConfiguredObject; + /** A simple message store that stores the messages in a thread-safe structure in memory. */ public class MemoryConfigurationStore extends AbstractMemoryStore { public static final String TYPE = "Memory"; + public MemoryConfigurationStore(final Class<? extends ConfiguredObject> rootClass) + { + super(rootClass); + } } diff --git a/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java b/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java deleted file mode 100644 index e69de29bb2..0000000000 --- a/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java +++ /dev/null diff --git a/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemorySystemConfigImpl.java b/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemorySystemConfigImpl.java new file mode 100644 index 0000000000..f644b8f46b --- /dev/null +++ b/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/store/MemorySystemConfigImpl.java @@ -0,0 +1,52 @@ +/* + * + * 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.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.model.AbstractSystemConfig; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.ManagedObject; +import org.apache.qpid.server.model.SystemConfigFactoryConstructor; + + +@ManagedObject( category = false, type = MemorySystemConfigImpl.SYSTEM_CONFIG_TYPE ) +public class MemorySystemConfigImpl extends AbstractSystemConfig<MemorySystemConfigImpl> +{ + public static final String SYSTEM_CONFIG_TYPE = "Memory"; + + @SystemConfigFactoryConstructor + public MemorySystemConfigImpl(final TaskExecutor taskExecutor, + final EventLogger eventLogger, + final LogRecorder logRecorder, + final BrokerOptions brokerOptions) + { + super(taskExecutor, eventLogger, logRecorder, brokerOptions); + } + + @Override + protected DurableConfigurationStore createStoreObject() + { + return new MemoryConfigurationStore(Broker.class); + } +} diff --git a/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhostnode/memory/MemoryVirtualHostNode.java b/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhostnode/memory/MemoryVirtualHostNode.java index d9b564305c..f57c0df4c0 100644 --- a/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhostnode/memory/MemoryVirtualHostNode.java +++ b/java/broker-plugins/memory-store/src/main/java/org/apache/qpid/server/virtualhostnode/memory/MemoryVirtualHostNode.java @@ -25,6 +25,7 @@ import java.util.Map; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ManagedObject; import org.apache.qpid.server.model.ManagedObjectFactoryConstructor; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.MemoryConfigurationStore; import org.apache.qpid.server.virtualhostnode.AbstractStandardVirtualHostNode; @@ -48,6 +49,6 @@ public class MemoryVirtualHostNode extends AbstractStandardVirtualHostNode<Memor @Override protected DurableConfigurationStore createConfigurationStore() { - return new MemoryConfigurationStore(); + return new MemoryConfigurationStore(VirtualHost.class); } } diff --git a/java/broker/src/main/java/org/apache/qpid/server/Main.java b/java/broker/src/main/java/org/apache/qpid/server/Main.java index 20b73e965c..72550128b7 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/Main.java +++ b/java/broker/src/main/java/org/apache/qpid/server/Main.java @@ -21,6 +21,10 @@ package org.apache.qpid.server; import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; @@ -30,9 +34,11 @@ import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.log4j.Logger; + import org.apache.qpid.common.QpidProperties; import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.server.configuration.store.ConfigurationEntryStoreUtil; +import org.apache.qpid.server.configuration.IllegalConfigurationException; +import org.apache.qpid.util.FileUtils; /** * Main entry point for AMQPD. @@ -189,8 +195,7 @@ public class Main destinationFile = new File(System.getProperty("user.dir"), BrokerOptions.DEFAULT_INITIAL_CONFIG_NAME); } - ConfigurationEntryStoreUtil util = new ConfigurationEntryStoreUtil(); - util.copyInitialConfigFile(options.getInitialConfigurationLocation(), destinationFile); + copyInitialConfigFile(options, destinationFile); System.out.println("Initial config written to: " + destinationFile.getAbsolutePath()); } @@ -299,6 +304,53 @@ public class Main } } + private void copyInitialConfigFile(final BrokerOptions options, final File destinationFile) + { + String initialConfigLocation = options.getInitialConfigurationLocation(); + URL url = null; + try + { + url = new URL(initialConfigLocation); + } + catch (MalformedURLException e) + { + File locationFile = new File(initialConfigLocation); + try + { + url = locationFile.toURI().toURL(); + } + catch (MalformedURLException e1) + { + throw new IllegalConfigurationException("Cannot create URL for file " + locationFile, e1); + } + } + InputStream in = null; + try + { + in = url.openStream(); + FileUtils.copy(in, destinationFile); + } + catch (IOException e) + { + throw new IllegalConfigurationException("Cannot create file " + destinationFile + + " by copying initial config from " + initialConfigLocation, e); + } + finally + { + if (in != null) + { + try + { + in.close(); + } + catch (IOException e) + { + throw new IllegalConfigurationException("Cannot close initial config input stream: " + initialConfigLocation, e); + } + } + } + } + protected void setExceptionHandler() { Thread.UncaughtExceptionHandler handler = null; diff --git a/java/broker/src/test/java/org/apache/qpid/server/MainTest.java b/java/broker/src/test/java/org/apache/qpid/server/MainTest.java index c6d68843b7..850fa993f5 100644 --- a/java/broker/src/test/java/org/apache/qpid/server/MainTest.java +++ b/java/broker/src/test/java/org/apache/qpid/server/MainTest.java @@ -48,7 +48,7 @@ public class MainTest extends QpidTestCase BrokerOptions options = startDummyMain(""); - assertEquals("json", options.getConfigurationStoreType()); + assertEquals("JSON", options.getConfigurationStoreType()); assertEquals(expectedStorePath, options.getConfigurationStoreLocation()); assertEquals(expectedLogConfigPath, options.getLogConfigFileLocation()); assertEquals(0, options.getLogWatchFrequency()); diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java b/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java index 2ccf85c5a5..82fcadfcf9 100755 --- a/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java +++ b/java/systests/src/main/java/org/apache/qpid/test/utils/QpidBrokerTestCase.java @@ -95,7 +95,7 @@ public class QpidBrokerTestCase extends QpidTestCase protected final static String QpidHome = System.getProperty("QPID_HOME"); private final File _configFile = new File(System.getProperty("broker.config")); private File _logConfigFile; - protected final String _brokerStoreType = System.getProperty("broker.config-store-type", "json"); + protected final String _brokerStoreType = System.getProperty("broker.config-store-type", "JSON"); protected static final Logger _logger = Logger.getLogger(QpidBrokerTestCase.class); protected static final int LOGMONITOR_TIMEOUT = 5000; @@ -238,7 +238,7 @@ public class QpidBrokerTestCase extends QpidTestCase _taskExecutor = new TaskExecutorImpl(); _taskExecutor.start(); } - TestBrokerConfiguration configuration = new TestBrokerConfiguration(System.getProperty(_brokerStoreType), _configFile.getAbsolutePath(), _taskExecutor); + TestBrokerConfiguration configuration = new TestBrokerConfiguration(_brokerStoreType, _configFile.getAbsolutePath(), _taskExecutor); synchronized (_brokerConfigurations) { _brokerConfigurations.put(actualPort, configuration); diff --git a/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java b/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java index cb4150a575..fce47f9986 100644 --- a/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java +++ b/java/systests/src/main/java/org/apache/qpid/test/utils/TestBrokerConfiguration.java @@ -23,35 +23,55 @@ package org.apache.qpid.test.utils; import static org.mockito.Mockito.mock; import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.net.MalformedURLException; +import java.net.URL; +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.BrokerOptions; -import org.apache.qpid.server.configuration.store.MemoryConfigurationEntryStore; 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.AbstractSystemConfig; 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.BrokerModel; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.GroupProvider; +import org.apache.qpid.server.model.JsonSystemConfigImpl; import org.apache.qpid.server.model.Plugin; import org.apache.qpid.server.model.PreferencesProvider; -import org.apache.qpid.server.model.SystemContextImpl; +import org.apache.qpid.server.model.SystemConfig; import org.apache.qpid.server.model.UUIDGenerator; import org.apache.qpid.server.model.adapter.FileBasedGroupProvider; import org.apache.qpid.server.model.adapter.FileBasedGroupProviderImpl; +import org.apache.qpid.server.plugin.PluggableFactoryLoader; +import org.apache.qpid.server.plugin.SystemConfigFactory; import org.apache.qpid.server.security.access.FileAccessControlProviderConstants; +import org.apache.qpid.server.store.AbstractMemoryStore; import org.apache.qpid.server.store.ConfiguredObjectRecord; +import org.apache.qpid.server.store.ConfiguredObjectRecordConverter; 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.util.Strings; public class TestBrokerConfiguration { + private static final Logger LOGGER = Logger.getLogger(TestBrokerConfiguration.class); + public static final String ENTRY_NAME_HTTP_PORT = "http"; public static final String ENTRY_NAME_AMQP_PORT = "amqp"; public static final String ENTRY_NAME_RMI_PORT = "rmi"; @@ -69,20 +89,49 @@ public class TestBrokerConfiguration public static final String ENTRY_NAME_SSL_TRUSTSTORE = "systestsTrustStore"; public static final String ENTRY_NAME_GROUP_FILE = "groupFile"; public static final String ENTRY_NAME_ACL_FILE = "aclFile"; + private final TaskExecutor _taskExecutor; + private final String _storeType; - private MemoryConfigurationEntryStore _store; + private DurableConfigurationStore _store; private boolean _saved; public TestBrokerConfiguration(String storeType, String initialStoreLocation, final TaskExecutor taskExecutor) { - _store = new MemoryConfigurationEntryStore( - new SystemContextImpl(taskExecutor, - mock(EventLogger.class), - mock(LogRecorder.class), - mock(BrokerOptions.class)), - initialStoreLocation, - null, - Collections.<String,String>emptyMap()); + BrokerOptions brokerOptions = new BrokerOptions(); + _taskExecutor = taskExecutor; + _storeType = storeType; + brokerOptions.setInitialConfigurationLocation(initialStoreLocation); + final AbstractSystemConfig parentObject = new JsonSystemConfigImpl(taskExecutor, + mock(EventLogger.class), + mock(LogRecorder.class), + brokerOptions); + + ConfiguredObjectRecordConverter converter = new ConfiguredObjectRecordConverter(BrokerModel.getInstance()); + + Reader reader; + try + { + try + { + URL url = new URL(initialStoreLocation); + reader = new InputStreamReader(url.openStream()); + } + catch (MalformedURLException e) + { + reader = new FileReader(initialStoreLocation); + } + + Collection<ConfiguredObjectRecord> records = converter.readFromJson(org.apache.qpid.server.model.Broker.class, parentObject, reader); + _store = new AbstractMemoryStore(Broker.class){}; + + ConfiguredObjectRecord[] initialRecords = records.toArray(new ConfiguredObjectRecord[records.size()]); + _store.openConfigurationStore(parentObject,false, initialRecords); + } + catch (IOException e) + { + throw new RuntimeException("Unable to load initial store", e); + } + _store.visitConfiguredObjectRecords(new ConfiguredObjectRecordHandler() { @Override @@ -151,7 +200,47 @@ public class TestBrokerConfiguration public boolean save(File configFile) { - _store.copyTo(configFile.getAbsolutePath()); + BrokerOptions brokerOptions = new BrokerOptions(); + brokerOptions.setConfigurationStoreLocation(configFile.getAbsolutePath()); + + SystemConfigFactory configFactory = + (new PluggableFactoryLoader<>(SystemConfigFactory.class)).get(_storeType); + + final SystemConfig parentObject = configFactory.newInstance(_taskExecutor, + mock(EventLogger.class), + mock(LogRecorder.class), + brokerOptions); + + parentObject.open(); + DurableConfigurationStore configurationStore = parentObject.getConfigurationStore(); + configurationStore.closeConfigurationStore(); + + final List<ConfiguredObjectRecord> initialRecords = new ArrayList<>(); + _store.visitConfiguredObjectRecords(new ConfiguredObjectRecordHandler() + { + @Override + public void begin() + { + + } + + @Override + public boolean handle(final ConfiguredObjectRecord record) + { + initialRecords.add(record); + return true; + } + + @Override + public void end() + { + + } + }); + + + configurationStore.openConfigurationStore(parentObject,true,initialRecords.toArray(new ConfiguredObjectRecord[initialRecords.size()])); + configurationStore.closeConfigurationStore(); return true; } @@ -228,7 +317,7 @@ public class TestBrokerConfiguration private void addObjectConfiguration(UUID id, String type, Map<String, Object> attributes) { - ConfiguredObjectRecord entry = new ConfiguredObjectRecordImpl(id, type, attributes, Collections.singletonMap(Broker.class.getSimpleName(), findObject(Broker.class,null))); + ConfiguredObjectRecord entry = new ConfiguredObjectRecordImpl(id, type, attributes, Collections.singletonMap(Broker.class.getSimpleName(), findObject(Broker.class,null).getId())); _store.update(true, entry); } @@ -256,7 +345,7 @@ public class TestBrokerConfiguration { ConfiguredObjectRecord authProviderRecord = findObject(AuthenticationProvider.class, authenticationProvider); ConfiguredObjectRecord pp = new ConfiguredObjectRecordImpl(UUIDGenerator.generateRandomUUID(), - PreferencesProvider.class.getSimpleName(), attributes, Collections.<String, ConfiguredObjectRecord>singletonMap(AuthenticationProvider.class.getSimpleName(),authProviderRecord)); + PreferencesProvider.class.getSimpleName(), attributes, Collections.singletonMap(AuthenticationProvider.class.getSimpleName(),authProviderRecord.getId())); _store.create(pp); } |