DNA SVN: r522 - in trunk/dna-jcr/src: test/java/org/jboss/dna/jcr and 1 other directory.
by dna-commits@lists.jboss.org
Author: jverhaeg(a)redhat.com
Date: 2008-09-16 16:26:44 -0400 (Tue, 16 Sep 2008)
New Revision: 522
Modified:
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java
Log:
Fixed problem in repository that assumed a login context was available from the execution context. This allows for skipping authentication if JAAS hasn't been configured.
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java 2008-09-16 19:03:58 UTC (rev 521)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java 2008-09-16 20:26:44 UTC (rev 522)
@@ -245,13 +245,15 @@
throw new RepositoryException(error);
}
}
- // Authenticate
- try {
- assert execContext != null;
- assert execContext.getLoginContext() != null;
- execContext.getLoginContext().login();
- } catch (javax.security.auth.login.LoginException error) {
- throw new LoginException(error);
+ // Authenticate if possible
+ assert execContext != null;
+ LoginContext loginContext = execContext.getLoginContext();
+ if (loginContext != null) {
+ try {
+ loginContext.login();
+ } catch (javax.security.auth.login.LoginException error) {
+ throw new LoginException(error);
+ }
}
// Ensure valid workspace name
if (workspaceName == null) workspaceName = JcrI18n.defaultWorkspaceName.text();
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2008-09-16 19:03:58 UTC (rev 521)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2008-09-16 20:26:44 UTC (rev 522)
@@ -45,6 +45,7 @@
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import net.jcip.annotations.NotThreadSafe;
import org.jboss.dna.common.util.ArgCheck;
@@ -487,17 +488,20 @@
if (!isLive()) {
return;
}
- try {
- if (connection != null) {
- connection.close();
- connection = null;
+ if (connection != null) {
+ connection.close();
+ connection = null;
+ }
+ LoginContext loginContext = executionContext.getLoginContext();
+ if (loginContext != null) {
+ try {
+ loginContext.logout();
+ } catch (LoginException error) {
+ // TODO: Change to DnaException once DNA-180 is addressed
+ throw new RuntimeException(error);
}
- assert executionContext.getLoginContext() != null;
- executionContext.getLoginContext().logout();
- isLive = false;
- } catch (LoginException error) {
- // TODO; Log error
}
+ isLive = false;
}
/**
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java 2008-09-16 19:03:58 UTC (rev 521)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java 2008-09-16 20:26:44 UTC (rev 522)
@@ -77,7 +77,6 @@
@Before
public void before() throws Exception {
MockitoAnnotations.initMocks(this);
- stub(executionContext.getLoginContext()).toReturn(loginContext);
stub(executionContextFactory.create()).toReturn(executionContext);
stub(executionContextFactory.create(accessControlContext)).toReturn(executionContext);
stub(connectionFactory.createConnection(JcrI18n.defaultWorkspaceName.text())).toReturn(connection);
15 years, 7 months
DNA SVN: r521 - in trunk: dna-repository/src/test/java/org/jboss/dna/repository and 13 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-16 15:03:58 -0400 (Tue, 16 Sep 2008)
New Revision: 521
Added:
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryLibrary.java
trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryContext.java
trunk/docs/examples/gettingstarted/repositories/src/test/resources/log4j.properties
Removed:
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java
Modified:
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java
trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositorySource.java
trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/SimpleRepositorySource.java
trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/TimeDelayingRepositorySource.java
trunk/docs/examples/gettingstarted/repositories/pom.xml
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java
trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml
trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml
trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties
trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositoryConnection.java
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositorySource.java
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederationI18n.java
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/executor/FederatingCommandExecutor.java
trunk/extensions/dna-connector-federation/src/main/resources/org/jboss/dna/connector/federation/FederationI18n.properties
trunk/extensions/dna-connector-federation/src/test/java/org/jboss/dna/connector/federation/FederatedRepositorySourceIntegrationTest.java
trunk/extensions/dna-connector-federation/src/test/java/org/jboss/dna/connector/federation/FederatedRepositorySourceTest.java
trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryConnection.java
trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositorySource.java
trunk/extensions/dna-connector-jbosscache/src/main/java/org/jboss/dna/connector/jbosscache/JBossCacheSource.java
Log:
DNA-222 - Create Getting Started example application for repositories
http://jira.jboss.com/jira/browse/DNA-222
Changed how the RepositorySource instances are initialized, removing the need to use JNDI for the FederatedRepositorySource (since the ExecutionContextFactory and RepositoryConnectionFactory are not serializable and could not be placed inside JNDI); instead, RepositoryLibrary (formerly RepositorySourceManager) now initializes each RepositorySource with a RepositoryContext when the RepositorySource is added to the library. This completely removes the need to use JNDI to look up DNA components, since they are all injected into the correct locations as needed.
Completed more unit testing. Still lacking tests that use JCR implementation, but that will follow shortly.
Copied: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryLibrary.java (from rev 516, trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java)
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryLibrary.java (rev 0)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryLibrary.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -0,0 +1,453 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.repository;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import net.jcip.annotations.ThreadSafe;
+import org.jboss.dna.common.util.ArgCheck;
+import org.jboss.dna.repository.services.AbstractServiceAdministrator;
+import org.jboss.dna.repository.services.ServiceAdministrator;
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.ExecutionContextFactory;
+import org.jboss.dna.spi.connector.BasicExecutionContextFactory;
+import org.jboss.dna.spi.connector.RepositoryConnection;
+import org.jboss.dna.spi.connector.RepositoryConnectionFactory;
+import org.jboss.dna.spi.connector.RepositoryConnectionPool;
+import org.jboss.dna.spi.connector.RepositoryContext;
+import org.jboss.dna.spi.connector.RepositorySource;
+
+/**
+ * A library of {@link RepositorySource} instances and the {@link RepositoryConnectionPool} used to manage the connections for
+ * each.
+ *
+ * @author Randall Hauch
+ */
+@ThreadSafe
+public class RepositoryLibrary implements RepositoryConnectionFactory {
+
+ /**
+ * The administrative component for this service.
+ *
+ * @author Randall Hauch
+ */
+ protected class Administrator extends AbstractServiceAdministrator {
+
+ protected Administrator() {
+ super(RepositoryI18n.federationServiceName, State.STARTED);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void doStart( State fromState ) {
+ super.doStart(fromState);
+ RepositoryLibrary.this.start();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected void doShutdown( State fromState ) {
+ super.doShutdown(fromState);
+ RepositoryLibrary.this.shutdown();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean awaitTermination( long timeout,
+ TimeUnit unit ) throws InterruptedException {
+ return RepositoryLibrary.this.awaitTermination(timeout, unit);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected boolean doCheckIsTerminated() {
+ return RepositoryLibrary.this.isTerminated();
+ }
+
+ }
+
+ private final ServiceAdministrator administrator = new Administrator();
+ private final ReadWriteLock sourcesLock = new ReentrantReadWriteLock();
+ private final CopyOnWriteArrayList<RepositoryConnectionPool> pools = new CopyOnWriteArrayList<RepositoryConnectionPool>();
+ private RepositoryConnectionFactory delegate;
+ private final ExecutionContextFactory executionContextFactory;
+ private final RepositoryContext repositoryContext;
+
+ /**
+ * Create a new manager instance.
+ */
+ public RepositoryLibrary() {
+ this(new BasicExecutionContextFactory(), null);
+ }
+
+ /**
+ * Create a new manager instance.
+ *
+ * @param delegate the connection factory to which this instance should delegate in the event that a source is not found in
+ * this manager; may be null if there is no delegate
+ */
+ public RepositoryLibrary( RepositoryConnectionFactory delegate ) {
+ this(new BasicExecutionContextFactory(), delegate);
+ }
+
+ /**
+ * Create a new manager instance.
+ *
+ * @param executionContextFactory the execution context factory, used by sources to create {@link ExecutionContext} instances
+ * @throws IllegalArgumentException if the <code>executionContextFactory</code> reference is null
+ */
+ public RepositoryLibrary( ExecutionContextFactory executionContextFactory ) {
+ this(executionContextFactory, null);
+ }
+
+ /**
+ * Create a new manager instance.
+ *
+ * @param executionContextFactory the execution context factory, used by sources to create {@link ExecutionContext} instances
+ * @param delegate the connection factory to which this instance should delegate in the event that a source is not found in
+ * this manager; may be null if there is no delegate
+ * @throws IllegalArgumentException if the <code>executionContextFactory</code> reference is null
+ */
+ public RepositoryLibrary( ExecutionContextFactory executionContextFactory,
+ RepositoryConnectionFactory delegate ) {
+ ArgCheck.isNotNull(executionContextFactory, "executionContextFactory");
+ this.delegate = delegate;
+ this.executionContextFactory = executionContextFactory;
+ this.repositoryContext = new RepositoryContext() {
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.connector.RepositoryContext#getExecutionContextFactory()
+ */
+ public ExecutionContextFactory getExecutionContextFactory() {
+ return RepositoryLibrary.this.getExecutionContextFactory();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.connector.RepositoryContext#getRepositoryConnectionFactory()
+ */
+ public RepositoryConnectionFactory getRepositoryConnectionFactory() {
+ return RepositoryLibrary.this;
+ }
+ };
+ }
+
+ /**
+ * @return executionContextFactory
+ */
+ public ExecutionContextFactory getExecutionContextFactory() {
+ return executionContextFactory;
+ }
+
+ /**
+ * Get the delegate connection factory.
+ *
+ * @return the connection factory to which this instance should delegate in the event that a source is not found in this
+ * manager, or null if there is no delegate
+ */
+ public RepositoryConnectionFactory getDelegate() {
+ return delegate;
+ }
+
+ /**
+ * Set the delegate connection factory.
+ *
+ * @param delegate the connection factory to which this instance should delegate in the event that a source is not found in
+ * this manager; may be null if there is no delegate
+ */
+ public void setDelegate( RepositoryConnectionFactory delegate ) {
+ this.delegate = delegate;
+ }
+
+ /**
+ * @return administrator
+ */
+ public ServiceAdministrator getAdministrator() {
+ return this.administrator;
+ }
+
+ /**
+ * Utility method called by the administrator.
+ */
+ protected void start() {
+ // Do not establish connections to the pools; these will be established as needed
+
+ }
+
+ /**
+ * Utility method called by the administrator.
+ */
+ protected void shutdown() {
+ // Close all connections to the pools. This is done inside the pools write lock.
+ try {
+ this.sourcesLock.readLock().lock();
+ for (RepositoryConnectionPool pool : this.pools) {
+ pool.shutdown();
+ }
+ } finally {
+ this.sourcesLock.readLock().unlock();
+ }
+ }
+
+ /**
+ * Utility method called by the administrator.
+ *
+ * @param timeout
+ * @param unit
+ * @return true if all pools were terminated in the supplied time (or were already terminated), or false if the timeout
+ * occurred before all the connections were closed
+ * @throws InterruptedException
+ */
+ protected boolean awaitTermination( long timeout,
+ TimeUnit unit ) throws InterruptedException {
+ // Check whether all source pools are shut down. This is done inside the pools write lock.
+ try {
+ this.sourcesLock.readLock().lock();
+ for (RepositoryConnectionPool pool : this.pools) {
+ if (!pool.awaitTermination(timeout, unit)) return false;
+ }
+ return true;
+ } finally {
+ this.sourcesLock.readLock().unlock();
+ }
+ }
+
+ /**
+ * Returns true if this federated repository is in the process of terminating after {@link ServiceAdministrator#shutdown()}
+ * has been called on the {@link #getAdministrator() administrator}, but the federated repository has connections that have
+ * not yet normally been {@link RepositoryConnection#close() closed}. This method may be useful for debugging. A return of
+ * <tt>true</tt> reported a sufficient period after shutdown may indicate that connection users have ignored or suppressed
+ * interruption, causing this repository not to properly terminate.
+ *
+ * @return true if terminating but not yet terminated, or false otherwise
+ * @see #isTerminated()
+ */
+ public boolean isTerminating() {
+ try {
+ this.sourcesLock.readLock().lock();
+ for (RepositoryConnectionPool pool : this.pools) {
+ if (pool.isTerminating()) return true;
+ }
+ return false;
+ } finally {
+ this.sourcesLock.readLock().unlock();
+ }
+ }
+
+ /**
+ * Return true if this federated repository has completed its termination and no longer has any open connections.
+ *
+ * @return true if terminated, or false otherwise
+ * @see #isTerminating()
+ */
+ public boolean isTerminated() {
+ try {
+ this.sourcesLock.readLock().lock();
+ for (RepositoryConnectionPool pool : this.pools) {
+ if (!pool.isTerminated()) return false;
+ }
+ return true;
+ } finally {
+ this.sourcesLock.readLock().unlock();
+ }
+ }
+
+ /**
+ * Get an unmodifiable collection of {@link RepositorySource} names.
+ *
+ * @return the pools
+ */
+ public Collection<String> getSourceNames() {
+ Set<String> sourceNames = new HashSet<String>();
+ for (RepositoryConnectionPool pool : this.pools) {
+ sourceNames.add(pool.getRepositorySource().getName());
+ }
+ return Collections.unmodifiableCollection(sourceNames);
+ }
+
+ /**
+ * Get an unmodifiable collection of {@link RepositorySource} instances managed by this instance.
+ *
+ * @return the pools
+ */
+ public Collection<RepositorySource> getSources() {
+ List<RepositorySource> sources = new LinkedList<RepositorySource>();
+ for (RepositoryConnectionPool pool : this.pools) {
+ sources.add(pool.getRepositorySource());
+ }
+ return Collections.unmodifiableCollection(sources);
+ }
+
+ /**
+ * Get the RepositorySource with the specified name managed by this instance.
+ *
+ * @param sourceName the name of the source
+ * @return the source, or null if no such source exists in this instance
+ */
+ public RepositorySource getSource( String sourceName ) {
+ try {
+ this.sourcesLock.readLock().lock();
+ for (RepositoryConnectionPool existingPool : this.pools) {
+ RepositorySource source = existingPool.getRepositorySource();
+ if (source.getName().equals(sourceName)) return source;
+ }
+ } finally {
+ this.sourcesLock.readLock().unlock();
+ }
+ return null;
+ }
+
+ /**
+ * Get the connection pool managing the {@link RepositorySource} with the specified name managed by this instance.
+ *
+ * @param sourceName the name of the source
+ * @return the pool, or null if no such pool exists in this instance
+ */
+ public RepositoryConnectionPool getConnectionPool( String sourceName ) {
+ try {
+ this.sourcesLock.readLock().lock();
+ for (RepositoryConnectionPool existingPool : this.pools) {
+ RepositorySource source = existingPool.getRepositorySource();
+ if (source.getName().equals(sourceName)) return existingPool;
+ }
+ } finally {
+ this.sourcesLock.readLock().unlock();
+ }
+ return null;
+ }
+
+ /**
+ * Add the supplied federated source. This method returns false if the source is null.
+ *
+ * @param source the source to add
+ * @return true if the source is added, or false if the reference is null or if there is already an existing source with the
+ * supplied name.
+ */
+ public boolean addSource( RepositorySource source ) {
+ if (source == null) return false;
+ try {
+ this.sourcesLock.writeLock().lock();
+ for (RepositoryConnectionPool existingPool : this.pools) {
+ if (existingPool.getRepositorySource().getName().equals(source.getName())) return false;
+ }
+ source.initialize(repositoryContext);
+ RepositoryConnectionPool pool = new RepositoryConnectionPool(source);
+ this.pools.add(pool);
+ return true;
+ } finally {
+ this.sourcesLock.writeLock().unlock();
+ }
+ }
+
+ /**
+ * Remove from this federated repository the supplied source (or a source with the same name as that supplied). This call
+ * shuts down the connections in the source in an orderly fashion, allowing those connection currently in use to be used and
+ * closed normally, but preventing further connections from being used.
+ * <p>
+ * This method can safely be called while the federation repository is in use.
+ * </p>
+ *
+ * @param source the source to be removed
+ * @param timeToAwait the amount of time to wait while all of the source's connections are closed, or non-positive if the call
+ * should not wait at all
+ * @param unit the time unit to be used for <code>timeToAwait</code>
+ * @return true if the source was removed, or false if the source was not a source for this repository.
+ * @throws InterruptedException if the thread is interrupted while awaiting closing of the connections
+ */
+ public boolean removeSource( RepositorySource source,
+ long timeToAwait,
+ TimeUnit unit ) throws InterruptedException {
+ // Use the name; don't use the object equality ...
+ return removeSource(source.getName(), timeToAwait, unit) != null;
+ }
+
+ /**
+ * Remove from this federated repository the source with the supplied name. This call shuts down the connections in the source
+ * in an orderly fashion, allowing those connection currently in use to be used and closed normally, but preventing further
+ * connections from being used.
+ *
+ * @param name the name of the source to be removed
+ * @param timeToAwait the amount of time to wait while all of the source's connections are closed, or non-positive if the call
+ * should not wait at all
+ * @param unit the time unit to be used for <code>timeToAwait</code>
+ * @return the source with the supplied name that was removed, or null if no existing source matching the supplied name could
+ * be found
+ * @throws InterruptedException if the thread is interrupted while awaiting closing of the connections
+ */
+ public RepositorySource removeSource( String name,
+ long timeToAwait,
+ TimeUnit unit ) throws InterruptedException {
+ try {
+ this.sourcesLock.writeLock().lock();
+ for (RepositoryConnectionPool existingPool : this.pools) {
+ if (existingPool.getRepositorySource().getName().equals(name)) {
+ // Shut down the source ...
+ existingPool.shutdown();
+ if (timeToAwait > 0L) existingPool.awaitTermination(timeToAwait, unit);
+ }
+ return existingPool.getRepositorySource();
+ }
+ } finally {
+ this.sourcesLock.writeLock().unlock();
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.connector.RepositoryConnectionFactory#createConnection(java.lang.String)
+ */
+ public RepositoryConnection createConnection( String sourceName ) {
+ try {
+ this.sourcesLock.readLock().lock();
+ for (RepositoryConnectionPool existingPool : this.pools) {
+ RepositorySource source = existingPool.getRepositorySource();
+ if (source.getName().equals(sourceName)) return existingPool.getConnection();
+ }
+ RepositoryConnectionFactory delegate = this.delegate;
+ if (delegate != null) {
+ return delegate.createConnection(sourceName);
+ }
+ } finally {
+ this.sourcesLock.readLock().unlock();
+ }
+ return null;
+ }
+}
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -101,7 +101,7 @@
private final ClassLoaderFactory classLoaderFactory;
private final ExecutionContext context;
- private final RepositorySourceManager sources;
+ private final RepositoryLibrary sources;
private final String configurationSourceName;
private final Path pathToConfigurationRoot;
private final Administrator administrator = new Administrator();
@@ -120,7 +120,7 @@
* loaded this class.
* @throws IllegalArgumentException if the bootstrap source is null or the execution context is null
*/
- public RepositoryService( RepositorySourceManager sources,
+ public RepositoryService( RepositoryLibrary sources,
String configurationSourceName,
ExecutionContext context,
ClassLoaderFactory classLoaderFactory ) {
@@ -142,7 +142,7 @@
* loaded this class.
* @throws IllegalArgumentException if the bootstrap source is null or the execution context is null
*/
- public RepositoryService( RepositorySourceManager sources,
+ public RepositoryService( RepositoryLibrary sources,
String configurationSourceName,
Path pathToConfigurationRoot,
ExecutionContext context,
@@ -175,7 +175,7 @@
/**
* @return sources
*/
- public RepositorySourceManager getRepositorySourceManager() {
+ public RepositoryLibrary getRepositorySourceManager() {
return sources;
}
Deleted: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -1,394 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.dna.repository;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import net.jcip.annotations.ThreadSafe;
-import org.jboss.dna.repository.services.AbstractServiceAdministrator;
-import org.jboss.dna.repository.services.ServiceAdministrator;
-import org.jboss.dna.spi.connector.RepositoryConnection;
-import org.jboss.dna.spi.connector.RepositoryConnectionFactory;
-import org.jboss.dna.spi.connector.RepositoryConnectionPool;
-import org.jboss.dna.spi.connector.RepositorySource;
-
-/**
- * A manager of {@link RepositorySource} instances and the {@link RepositoryConnectionPool} used to manage the connections for
- * each.
- *
- * @author Randall Hauch
- */
-@ThreadSafe
-public class RepositorySourceManager implements RepositoryConnectionFactory {
-
- /**
- * The administrative component for this service.
- *
- * @author Randall Hauch
- */
- protected class Administrator extends AbstractServiceAdministrator {
-
- protected Administrator() {
- super(RepositoryI18n.federationServiceName, State.STARTED);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected void doStart( State fromState ) {
- super.doStart(fromState);
- RepositorySourceManager.this.start();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected void doShutdown( State fromState ) {
- super.doShutdown(fromState);
- RepositorySourceManager.this.shutdown();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean awaitTermination( long timeout,
- TimeUnit unit ) throws InterruptedException {
- return RepositorySourceManager.this.awaitTermination(timeout, unit);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected boolean doCheckIsTerminated() {
- return RepositorySourceManager.this.isTerminated();
- }
-
- }
-
- private final ServiceAdministrator administrator = new Administrator();
- private final ReadWriteLock sourcesLock = new ReentrantReadWriteLock();
- private final CopyOnWriteArrayList<RepositoryConnectionPool> pools = new CopyOnWriteArrayList<RepositoryConnectionPool>();
- private RepositoryConnectionFactory delegate;
-
- /**
- * Create a new manager instance.
- */
- public RepositorySourceManager() {
- this(null);
- }
-
- /**
- * Create a new manager instance.
- *
- * @param delegate the connection factory to which this instance should delegate in the event that a source is not found in
- * this manager; may be null if there is no delegate
- */
- public RepositorySourceManager( RepositoryConnectionFactory delegate ) {
- this.delegate = delegate;
- }
-
- /**
- * Get the delegate connection factory.
- *
- * @return the connection factory to which this instance should delegate in the event that a source is not found in this
- * manager, or null if there is no delegate
- */
- public RepositoryConnectionFactory getDelegate() {
- return delegate;
- }
-
- /**
- * Set the delegate connection factory.
- *
- * @param delegate the connection factory to which this instance should delegate in the event that a source is not found in
- * this manager; may be null if there is no delegate
- */
- public void setDelegate( RepositoryConnectionFactory delegate ) {
- this.delegate = delegate;
- }
-
- /**
- * @return administrator
- */
- public ServiceAdministrator getAdministrator() {
- return this.administrator;
- }
-
- /**
- * Utility method called by the administrator.
- */
- protected void start() {
- // Do not establish connections to the pools; these will be established as needed
-
- }
-
- /**
- * Utility method called by the administrator.
- */
- protected void shutdown() {
- // Close all connections to the pools. This is done inside the pools write lock.
- try {
- this.sourcesLock.readLock().lock();
- for (RepositoryConnectionPool pool : this.pools) {
- pool.shutdown();
- }
- } finally {
- this.sourcesLock.readLock().unlock();
- }
- }
-
- /**
- * Utility method called by the administrator.
- *
- * @param timeout
- * @param unit
- * @return true if all pools were terminated in the supplied time (or were already terminated), or false if the timeout
- * occurred before all the connections were closed
- * @throws InterruptedException
- */
- protected boolean awaitTermination( long timeout,
- TimeUnit unit ) throws InterruptedException {
- // Check whether all source pools are shut down. This is done inside the pools write lock.
- try {
- this.sourcesLock.readLock().lock();
- for (RepositoryConnectionPool pool : this.pools) {
- if (!pool.awaitTermination(timeout, unit)) return false;
- }
- return true;
- } finally {
- this.sourcesLock.readLock().unlock();
- }
- }
-
- /**
- * Returns true if this federated repository is in the process of terminating after {@link ServiceAdministrator#shutdown()}
- * has been called on the {@link #getAdministrator() administrator}, but the federated repository has connections that have
- * not yet normally been {@link RepositoryConnection#close() closed}. This method may be useful for debugging. A return of
- * <tt>true</tt> reported a sufficient period after shutdown may indicate that connection users have ignored or suppressed
- * interruption, causing this repository not to properly terminate.
- *
- * @return true if terminating but not yet terminated, or false otherwise
- * @see #isTerminated()
- */
- public boolean isTerminating() {
- try {
- this.sourcesLock.readLock().lock();
- for (RepositoryConnectionPool pool : this.pools) {
- if (pool.isTerminating()) return true;
- }
- return false;
- } finally {
- this.sourcesLock.readLock().unlock();
- }
- }
-
- /**
- * Return true if this federated repository has completed its termination and no longer has any open connections.
- *
- * @return true if terminated, or false otherwise
- * @see #isTerminating()
- */
- public boolean isTerminated() {
- try {
- this.sourcesLock.readLock().lock();
- for (RepositoryConnectionPool pool : this.pools) {
- if (!pool.isTerminated()) return false;
- }
- return true;
- } finally {
- this.sourcesLock.readLock().unlock();
- }
- }
-
- /**
- * Get an unmodifiable collection of {@link RepositorySource} names.
- *
- * @return the pools
- */
- public Collection<String> getSourceNames() {
- Set<String> sourceNames = new HashSet<String>();
- for (RepositoryConnectionPool pool : this.pools) {
- sourceNames.add(pool.getRepositorySource().getName());
- }
- return Collections.unmodifiableCollection(sourceNames);
- }
-
- /**
- * Get an unmodifiable collection of {@link RepositorySource} instances managed by this instance.
- *
- * @return the pools
- */
- public Collection<RepositorySource> getSources() {
- List<RepositorySource> sources = new LinkedList<RepositorySource>();
- for (RepositoryConnectionPool pool : this.pools) {
- sources.add(pool.getRepositorySource());
- }
- return Collections.unmodifiableCollection(sources);
- }
-
- /**
- * Get the RepositorySource with the specified name managed by this instance.
- *
- * @param sourceName the name of the source
- * @return the source, or null if no such source exists in this instance
- */
- public RepositorySource getSource( String sourceName ) {
- try {
- this.sourcesLock.readLock().lock();
- for (RepositoryConnectionPool existingPool : this.pools) {
- RepositorySource source = existingPool.getRepositorySource();
- if (source.getName().equals(sourceName)) return source;
- }
- } finally {
- this.sourcesLock.readLock().unlock();
- }
- return null;
- }
-
- /**
- * Get the connection pool managing the {@link RepositorySource} with the specified name managed by this instance.
- *
- * @param sourceName the name of the source
- * @return the pool, or null if no such pool exists in this instance
- */
- public RepositoryConnectionPool getConnectionPool( String sourceName ) {
- try {
- this.sourcesLock.readLock().lock();
- for (RepositoryConnectionPool existingPool : this.pools) {
- RepositorySource source = existingPool.getRepositorySource();
- if (source.getName().equals(sourceName)) return existingPool;
- }
- } finally {
- this.sourcesLock.readLock().unlock();
- }
- return null;
- }
-
- /**
- * Add the supplied federated source. This method returns false if the source is null.
- *
- * @param source the source to add
- * @return true if the source is added, or false if the reference is null or if there is already an existing source with the
- * supplied name.
- */
- public boolean addSource( RepositorySource source ) {
- if (source == null) return false;
- try {
- this.sourcesLock.writeLock().lock();
- for (RepositoryConnectionPool existingPool : this.pools) {
- if (existingPool.getRepositorySource().getName().equals(source.getName())) return false;
- }
- RepositoryConnectionPool pool = new RepositoryConnectionPool(source);
- this.pools.add(pool);
- return true;
- } finally {
- this.sourcesLock.writeLock().unlock();
- }
- }
-
- /**
- * Remove from this federated repository the supplied source (or a source with the same name as that supplied). This call
- * shuts down the connections in the source in an orderly fashion, allowing those connection currently in use to be used and
- * closed normally, but preventing further connections from being used.
- * <p>
- * This method can safely be called while the federation repository is in use.
- * </p>
- *
- * @param source the source to be removed
- * @param timeToAwait the amount of time to wait while all of the source's connections are closed, or non-positive if the call
- * should not wait at all
- * @param unit the time unit to be used for <code>timeToAwait</code>
- * @return true if the source was removed, or false if the source was not a source for this repository.
- * @throws InterruptedException if the thread is interrupted while awaiting closing of the connections
- */
- public boolean removeSource( RepositorySource source,
- long timeToAwait,
- TimeUnit unit ) throws InterruptedException {
- // Use the name; don't use the object equality ...
- return removeSource(source.getName(), timeToAwait, unit) != null;
- }
-
- /**
- * Remove from this federated repository the source with the supplied name. This call shuts down the connections in the source
- * in an orderly fashion, allowing those connection currently in use to be used and closed normally, but preventing further
- * connections from being used.
- *
- * @param name the name of the source to be removed
- * @param timeToAwait the amount of time to wait while all of the source's connections are closed, or non-positive if the call
- * should not wait at all
- * @param unit the time unit to be used for <code>timeToAwait</code>
- * @return the source with the supplied name that was removed, or null if no existing source matching the supplied name could
- * be found
- * @throws InterruptedException if the thread is interrupted while awaiting closing of the connections
- */
- public RepositorySource removeSource( String name,
- long timeToAwait,
- TimeUnit unit ) throws InterruptedException {
- try {
- this.sourcesLock.writeLock().lock();
- for (RepositoryConnectionPool existingPool : this.pools) {
- if (existingPool.getRepositorySource().getName().equals(name)) {
- // Shut down the source ...
- existingPool.shutdown();
- if (timeToAwait > 0L) existingPool.awaitTermination(timeToAwait, unit);
- }
- return existingPool.getRepositorySource();
- }
- } finally {
- this.sourcesLock.writeLock().unlock();
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.jboss.dna.spi.connector.RepositoryConnectionFactory#createConnection(java.lang.String)
- */
- public RepositoryConnection createConnection( String sourceName ) {
- try {
- this.sourcesLock.readLock().lock();
- for (RepositoryConnectionPool existingPool : this.pools) {
- RepositorySource source = existingPool.getRepositorySource();
- if (source.getName().equals(sourceName)) return existingPool.getConnection();
- }
- RepositoryConnectionFactory delegate = this.delegate;
- if (delegate != null) {
- return delegate.createConnection(sourceName);
- }
- } finally {
- this.sourcesLock.readLock().unlock();
- }
- return null;
- }
-}
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -65,7 +65,7 @@
private ExecutionContext context;
private Path root;
@Mock
- private RepositorySourceManager sources;
+ private RepositoryLibrary sources;
@Before
public void beforeEach() throws Exception {
@@ -149,7 +149,7 @@
@Test
public void shouldStartUpUsingConfigurationRepositoryThatContainsSomeSources() throws Exception {
// Use a real source manager for this test ...
- sources = new RepositorySourceManager(sources);
+ sources = new RepositoryLibrary(sources);
sources.addSource(configRepositorySource);
assertThat(sources.getSources(), hasItems((RepositorySource)configRepositorySource));
assertThat(sources.getSources().size(), is(1));
Added: trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryContext.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryContext.java (rev 0)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryContext.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -0,0 +1,48 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.spi.connector;
+
+import org.jboss.dna.spi.ExecutionContextFactory;
+
+/**
+ * The context for a repository. This interface need not be implemented by a {@link RepositorySource}, as it is normally provided
+ * to the source when {@link RepositorySource#initialize(RepositoryContext) initialized}.
+ *
+ * @author Randall Hauch
+ */
+public interface RepositoryContext {
+
+ /**
+ * Get the factory that can be used to create execution contexts.
+ *
+ * @return the execution context factory
+ */
+ ExecutionContextFactory getExecutionContextFactory();
+
+ /**
+ * Get the factory for {@link RepositoryConnection connections} to other sources.
+ *
+ * @return the connection factory
+ */
+ RepositoryConnectionFactory getRepositoryConnectionFactory();
+
+}
Property changes on: trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryContext.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositorySource.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositorySource.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositorySource.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -51,6 +51,16 @@
public interface RepositorySource extends Referenceable, Serializable {
/**
+ * Initialize this source to use the supplied {@link RepositoryContext}, from which this source can obtain
+ * {@link RepositoryContext#getRepositoryConnectionFactory() connections} to other {@link RepositorySource sources} as well as
+ * {@link RepositoryContext#getExecutionContextFactory() execution contexts}.
+ *
+ * @param context
+ * @throws RepositorySourceException
+ */
+ void initialize( RepositoryContext context ) throws RepositorySourceException;
+
+ /**
* Get the name for this repository source.
*
* @return the name; never null or empty
Modified: trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/SimpleRepositorySource.java
===================================================================
--- trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/SimpleRepositorySource.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/SimpleRepositorySource.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -66,6 +66,7 @@
private String name;
private final AtomicInteger retryLimit = new AtomicInteger(DEFAULT_RETRY_LIMIT);
private CachePolicy defaultCachePolicy;
+ private transient RepositoryContext repositoryContext;
public SimpleRepositorySource() {
super();
@@ -74,6 +75,22 @@
/**
* {@inheritDoc}
*
+ * @see org.jboss.dna.spi.connector.RepositorySource#initialize(org.jboss.dna.spi.connector.RepositoryContext)
+ */
+ public void initialize( RepositoryContext context ) throws RepositorySourceException {
+ this.repositoryContext = context;
+ }
+
+ /**
+ * @return repositoryContext
+ */
+ public RepositoryContext getRepositoryContext() {
+ return repositoryContext;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
* @see org.jboss.dna.spi.connector.RepositorySource#getName()
*/
public String getName() {
Modified: trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/TimeDelayingRepositorySource.java
===================================================================
--- trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/TimeDelayingRepositorySource.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/TimeDelayingRepositorySource.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -62,6 +62,7 @@
private final AtomicLong pingDelay = new AtomicLong(0);
private final AtomicInteger retryLimit = new AtomicInteger(DEFAULT_RETRY_LIMIT);
private CachePolicy defaultCachePolicy;
+ private transient RepositoryContext repositoryContext;
public TimeDelayingRepositorySource( String identifier ) {
super();
@@ -70,7 +71,23 @@
/**
* {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.connector.RepositorySource#initialize(org.jboss.dna.spi.connector.RepositoryContext)
*/
+ public void initialize( RepositoryContext context ) throws RepositorySourceException {
+ this.repositoryContext = context;
+ }
+
+ /**
+ * @return repositoryContext
+ */
+ public RepositoryContext getRepositoryContext() {
+ return repositoryContext;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public String getName() {
return this.name;
}
Modified: trunk/docs/examples/gettingstarted/repositories/pom.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/pom.xml 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/docs/examples/gettingstarted/repositories/pom.xml 2008-09-16 19:03:58 UTC (rev 521)
@@ -42,7 +42,7 @@
<groupId>org.jboss.dna</groupId>
<artifactId>dna-connector-inmemory</artifactId>
<version>${dna-version}</version>
- <scope>runtime</scope>
+ <scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jboss.dna</groupId>
Modified: trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -32,14 +32,15 @@
import javax.jcr.PropertyIterator;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
+import javax.naming.NamingException;
import javax.security.auth.callback.PasswordCallback;
import org.jboss.dna.common.component.ClassLoaderFactory;
import org.jboss.dna.common.component.StandardClassLoaderFactory;
import org.jboss.dna.connector.inmemory.InMemoryRepositorySource;
import org.jboss.dna.jcr.JcrRepository;
import org.jboss.dna.repository.RepositoryImporter;
+import org.jboss.dna.repository.RepositoryLibrary;
import org.jboss.dna.repository.RepositoryService;
-import org.jboss.dna.repository.RepositorySourceManager;
import org.jboss.dna.spi.ExecutionContext;
import org.jboss.dna.spi.ExecutionContextFactory;
import org.jboss.dna.spi.connector.BasicExecutionContextFactory;
@@ -78,7 +79,7 @@
}
private ClassLoaderFactory classLoaderFactory;
- private RepositorySourceManager sources;
+ private RepositoryLibrary sources;
private ExecutionContextFactory contextFactory;
private RepositoryService repositoryService;
private Api api = Api.DNA;
@@ -138,8 +139,9 @@
* repositories.
*
* @throws IOException if there is a problem initializing the repositories from the files.
+ * @throws NamingException if there is a problem registering or looking up objects in JNDI
*/
- public void startRepositories() throws IOException {
+ public void startRepositories() throws IOException, NamingException {
if (repositoryService != null) return; // already started
// Create the class loader factory, which for this example will simply use this class' class loader...
@@ -152,8 +154,8 @@
// by supply LoginContext, AccessControlContext, or even Subject with CallbackHandlers. But no JAAS in this example.
ExecutionContext context = contextFactory.create();
- // Create the manager for the RepositorySource instances ...
- sources = new RepositorySourceManager();
+ // Create the library for the RepositorySource instances ...
+ sources = new RepositoryLibrary(contextFactory);
// Load into the source manager the repository source for the configuration repository ...
InMemoryRepositorySource configSource = new InMemoryRepositorySource();
Modified: trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml 2008-09-16 19:03:58 UTC (rev 521)
@@ -35,7 +35,7 @@
<aircraft jcr:name="Airbus A380" maker="Airbus" model="A380-800" introduced="2007" numberBuilt="18" range="8200nm" maxWeight="1235000lb" cruiseSpeed="647mph" url="http://en.wikipedia.org/wiki/Airbus_a380"/>
<aircraft jcr:name="Airbus A340" maker="Airbus" model="A340-200" introduced="1993" numberBuilt="354" range="8000nm" maxWeight="606300lb" cruiseSpeed="557mph" url="http://en.wikipedia.org/wiki/Airbus_A-340"/>
<aircraft jcr:name="Airbus A310" maker="Airbus" model="A310-200" introduced="1983" numberBuilt="255" cruiseSpeed="850km/h" emptyWeight="176312lb" range="3670nm" url="http://en.wikipedia.org/wiki/Airbus_A-310"/>
- <aircraft jcr:name="Embraer " maker="Embraer" model="ERJ170-200" introduced="2004" range="3334km" cruiseSpeed="481kt" emptyWeight="21810kg" url="http://en.wikipedia.org/wiki/EMBRAER_170"/>
+ <aircraft jcr:name="Embraer RJ-175" maker="Embraer" model="ERJ170-200" introduced="2004" range="3334km" cruiseSpeed="481kt" emptyWeight="21810kg" url="http://en.wikipedia.org/wiki/EMBRAER_170"/>
</Commercial>
<Vintage>
<aircraft jcr:name="Fokker Trimotor" maker="Fokker" model="F.VII" introduced="1925" cruiseSpeed="170km/h" emptyWeight="3050kg" crew="2" url="http://en.wikipedia.org/wiki/Fokker_trimotor"/>
Modified: trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml 2008-09-16 19:03:58 UTC (rev 521)
@@ -25,28 +25,35 @@
<dna:system xmlns:dna="http://www.jboss.org/dna" xmlns:jcr="http://www.jcp.org/jcr/1.0">
<!-- Define the sources from which content is made available -->
<dna:sources>
- <sourceA name="Cars" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" retryLimit="3" />
- <sourceB name="Aircraft" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" />
- <sourceC name="Vehicles" dna:classname="org.jboss.dna.connector.federation.FederatedRepositorySource" configurationSourceName="Configuration" configurationSourcePath="/dna:system/dna:federatedRepositories/Vehicles" />
- <sourceD name="Cache" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" />
+ <dna:source jcr:name="SourceA" dna:name="Cars" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" dna:retryLimit="3" />
+ <dna:source jcr:name="SourceB" dna:name="Aircraft" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" />
+ <dna:source jcr:name="SourceC" dna:name="Vehicles" dna:classname="org.jboss.dna.connector.federation.FederatedRepositorySource"
+ dna:repositoryName="Configuration Repository"
+ dna:configurationSourceName="Configuration"
+ dna:configurationSourcePath="/dna:system/dna:federatedRepositories/Vehicles"
+ dna:repositoryConnectionFactoryJndiName="/dna/connectionFactory"
+ dna:executionContextFactoryJndiName="/dna/contextFactory"/>
+ <dna:source jcr:name="SourceD" dna:name="Cache" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" />
</dna:sources>
<dna:federatedRepositories>
- <Vehicles>
- <!-- This section defines from where the content of the 'Vehicles' federated repository is obtained -->
+ <!-- This section defines from where the content of the 'Vehicles' federated repository is obtained.
+ The name of this node must match the 'name' of the source listed above. -->
+ <dna:federatedRepository jcr:name="Vehicles">
+ <!-- Define the federation configuration. -->
<dna:federation dna:timeToCache="100000">
+ <!-- Define how the content in the 'Cache' source is to map to the federated cache -->
<dna:cache>
- <!-- Define how the content in the 'Cache' source is to map to the federated cache -->
- <Cache dna:projectionRules="/ => /" />
+ <dna:projection jcr:name="Cache" dna:projectionRules="/ => /" />
</dna:cache>
+ <!-- Define how the content in the difference sources maps to the federated/unified repository.
+ This example puts the 'Cars' and 'Aircraft' content underneath '/vehicles', but the
+ 'Configuration' content (which is defined by this file) will appear under '/'. -->
<dna:projections>
- <!-- Define how the content in the difference sources maps to the federated/unified repository.
- This example puts the 'Cars' and 'Aircraft' content underneath '/vehicles', but the
- 'Configuration' content (which is defined by this file) will appear under '/'. -->
- <Cars dna:projectionRules="/vehicles => /" />
- <Aircraft dna:projectionRules="/vehicles => /" />
- <Configuration dna:projectionRules="/ => /" />
+ <dna:projection jcr:name="Cars" dna:projectionRules="/Vehicles => /" />
+ <dna:projection jcr:name="Aircraft" dna:projectionRules="/Vehicles => /" />
+ <dna:projection jcr:name="Configuration" dna:projectionRules="/ => /" />
</dna:projections>
</dna:federation>
- </Vehicles>
+ </dna:federatedRepository>
</dna:federatedRepositories>
</dna:system>
\ No newline at end of file
Modified: trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties 2008-09-16 19:03:58 UTC (rev 521)
@@ -9,9 +9,5 @@
# Set up the default logging to be INFO level, then override specific units
log4j.logger.org.jboss.dna=INFO
-#log4j.logger.org.jboss.dna.repository.sequencers=TRACE
-#log4j.logger.org.jboss.dna.sequencer=DEBUG
-#log4j.logger.org.jboss.dna.connector=TRACE
-#log4j.logger.org.jboss.dna.spi.connector.RepositoryConnectionPool=TRACE
-#log4j.logger.org.jboss.dna.spi=DEBUG
+log4j.logger.org.jboss.example.dna=INFO
Modified: trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -30,10 +30,8 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.jboss.dna.common.util.StringUtil;
import org.junit.After;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.mockito.MockitoAnnotations.Mock;
@@ -56,6 +54,7 @@
children = new ArrayList<String>();
client = new RepositoryClient();
client.setUserInterface(userInterface);
+ client.setApi(getApi());
stub(userInterface.getLocationOfRepositoryFiles()).toReturn(new File("src/main/resources").getAbsolutePath());
}
@@ -64,6 +63,10 @@
client.shutdown();
}
+ protected RepositoryClient.Api getApi() {
+ return RepositoryClient.Api.DNA;
+ }
+
protected void assertProperty( String propertyName,
Object... values ) {
Object[] actualValues = properties.get(propertyName);
@@ -82,7 +85,6 @@
assertThat(client.getNamesOfRepositories(), hasItems("Aircraft", "Cars", "Configuration", "Vehicles", "Cache"));
}
- @Ignore
@Test
public void shouldHaveContentFromConfigurationRepository() throws Throwable {
client.startRepositories();
@@ -95,22 +97,21 @@
properties.clear();
children.clear();
assertThat(client.getNodeInfo("Configuration", "/dna:system/dna:sources", properties, children), is(true));
- assertThat(children, hasItems("sourceA", "sourceB", "sourceC", "sourceD"));
+ assertThat(children, hasItems("SourceA", "SourceB", "SourceC", "SourceD"));
assertThat(properties.containsKey("jcr:primaryType"), is(true));
assertThat(properties.containsKey("dna:uuid"), is(true));
assertThat(properties.size(), is(2));
properties.clear();
children.clear();
- assertThat(client.getNodeInfo("Configuration", "/dna:system/dna:sources/sourceA", properties, children), is(true));
+ assertThat(client.getNodeInfo("Configuration", "/dna:system/dna:sources/SourceA", properties, children), is(true));
assertThat(children.size(), is(0));
- System.out.println(StringUtil.readableString(properties));
assertThat(properties.containsKey("jcr:primaryType"), is(true));
assertThat(properties.containsKey("dna:uuid"), is(true));
assertProperty("dna:classname", "org.jboss.dna.connector.inmemory.InMemoryRepositorySource");
- assertProperty("name", "Cars");
- assertProperty("retryLimit", "3");
- assertThat(properties.size(), is(4));
+ assertProperty("dna:name", "Cars");
+ assertProperty("dna:retryLimit", "3");
+ assertThat(properties.size(), is(5));
}
@Test
@@ -151,6 +152,96 @@
}
@Test
+ public void shouldLoadAircraftRepository() throws Throwable {
+ client.startRepositories();
+ assertThat(client.getNodeInfo("Aircraft", "/Aircraft", properties, children), is(true));
+ assertThat(children, hasItems("Business", "Commercial", "Vintage", "Homebuilt"));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertThat(properties.size(), is(2));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Aircraft", "/Aircraft/Commercial", properties, children), is(true));
+ assertThat(children, hasItems("Boeing 777",
+ "Boeing 767",
+ "Boeing 787",
+ "Boeing 757",
+ "Airbus A380",
+ "Airbus A340",
+ "Airbus A310",
+ "Embraer RJ-175"));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertThat(properties.size(), is(2));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Aircraft", "/Aircraft/Vintage/Wright Flyer", properties, children), is(true));
+ assertThat(children.size(), is(0));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertProperty("maker", "Wright Brothers");
+ assertProperty("introduced", "1903");
+ assertProperty("range", "852ft");
+ assertProperty("maxSpeed", "30mph");
+ assertProperty("emptyWeight", "605lb");
+ assertProperty("crew", "1");
+ assertThat(properties.size(), is(8));
+ }
+
+ @Test
+ public void shouldLoadVehiclesRepository() throws Throwable {
+ client.startRepositories();
+ assertThat(client.getNodeInfo("Vehicles", "/Vehicles", properties, children), is(true));
+ assertThat(children, hasItems("Cars", "Aircraft"));
+ assertThat(properties.containsKey("jcr:primaryType"), is(false));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertThat(properties.size(), is(1));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Vehicles", "/Vehicles/Cars/Hybrid", properties, children), is(true));
+ assertThat(children, hasItems("Toyota Prius", "Toyota Highlander", "Nissan Altima"));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertThat(properties.size(), is(2));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Vehicles", "/Vehicles/Cars/Sports/Aston Martin DB9", properties, children), is(true));
+ assertThat(children.size(), is(0));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertProperty("maker", "Aston Martin");
+ assertProperty("maker", "Aston Martin");
+ assertProperty("model", "DB9");
+ assertProperty("year", "2008");
+ assertProperty("msrp", "$171,600");
+ assertProperty("userRating", "5");
+ assertProperty("mpgCity", "12");
+ assertProperty("mpgHighway", "19");
+ assertProperty("lengthInInches", "185.5");
+ assertProperty("wheelbaseInInches", "108.0");
+ assertProperty("engine", "5,935 cc 5.9 liters V 12");
+ assertThat(properties.size(), is(12));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Vehicles", "/Vehicles/Aircraft/Vintage/Wright Flyer", properties, children), is(true));
+ assertThat(children.size(), is(0));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertProperty("maker", "Wright Brothers");
+ assertProperty("introduced", "1903");
+ assertProperty("range", "852ft");
+ assertProperty("maxSpeed", "30mph");
+ assertProperty("emptyWeight", "605lb");
+ assertProperty("crew", "1");
+ assertThat(properties.size(), is(8));
+ }
+
+ @Test
public void shouldReturnNullForNonExistantNode() throws Throwable {
client.startRepositories();
assertThat(client.getNodeInfo("Cars", "/Cars/Sports/Non Existant Car", properties, children), is(false));
Added: trunk/docs/examples/gettingstarted/repositories/src/test/resources/log4j.properties
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/test/resources/log4j.properties (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/test/resources/log4j.properties 2008-09-16 19:03:58 UTC (rev 521)
@@ -0,0 +1,18 @@
+# Direct log messages to stdout
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %m%n
+
+# Root logger option
+log4j.rootLogger=INFO, stdout
+
+# Set up the default logging to be INFO level, then override specific units
+log4j.logger.org.jboss.dna=INFO
+#log4j.logger.org.jboss.dna.repository.sequencers=TRACE
+#log4j.logger.org.jboss.dna.sequencer=DEBUG
+#log4j.logger.org.jboss.dna.connector=TRACE
+#log4j.logger.org.jboss.dna.spi.connector.RepositoryConnectionPool=TRACE
+#log4j.logger.org.jboss.dna.spi=DEBUG
+#log4j.logger.org.jboss.example.dna=TRACE
+
Property changes on: trunk/docs/examples/gettingstarted/repositories/src/test/resources/log4j.properties
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositoryConnection.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositoryConnection.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositoryConnection.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -119,9 +119,13 @@
if (commands == null || commands.length == 0) return;
CommandExecutor executor = this.repository.getExecutor(context, sourceName);
- assert executor != null;
- for (GraphCommand command : commands) {
- executor.execute(command);
+ try {
+ assert executor != null;
+ for (GraphCommand command : commands) {
+ executor.execute(command);
+ }
+ } finally {
+ executor.close();
}
}
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositorySource.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositorySource.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositorySource.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -31,7 +31,6 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.naming.Context;
-import javax.naming.InitialContext;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
@@ -55,6 +54,7 @@
import org.jboss.dna.spi.cache.CachePolicy;
import org.jboss.dna.spi.connector.RepositoryConnection;
import org.jboss.dna.spi.connector.RepositoryConnectionFactory;
+import org.jboss.dna.spi.connector.RepositoryContext;
import org.jboss.dna.spi.connector.RepositorySource;
import org.jboss.dna.spi.connector.RepositorySourceCapabilities;
import org.jboss.dna.spi.connector.RepositorySourceException;
@@ -97,9 +97,6 @@
protected static final String PASSWORD = "password";
protected static final String CONFIGURATION_SOURCE_NAME = "configurationSourceName";
protected static final String CONFIGURATION_SOURCE_PATH = "configurationSourcePath";
- protected static final String REPOSITORY_CONNECTION_FACTORY_JNDI_NAME = "repositoryConnectionFactoryJndiName";
- protected static final String EXECUTION_CONTEXT_FACTORY_JNDI_NAME = "executionContextFactoryJndiName";
- protected static final String REPOSITORY_JNDI_NAME = "repositoryJndiName";
protected static final String SECURITY_DOMAIN = "securityDomain";
protected static final String RETRY_LIMIT = "retryLimit";
@@ -115,13 +112,10 @@
private String password;
private String configurationSourceName;
private String configurationSourcePath = DEFAULT_CONFIGURATION_SOURCE_PATH;
- private String repositoryConnectionFactoryJndiName;
- private String executionContextFactoryJndiName;
private String securityDomain;
- private String repositoryJndiName;
private final AtomicInteger retryLimit = new AtomicInteger(DEFAULT_RETRY_LIMIT);
private transient FederatedRepository repository;
- private transient Context jndiContext;
+ private transient RepositoryContext repositoryContext;
/**
* Create a new instance of the source, which must still be properly initialized with a {@link #setRepositoryName(String)
@@ -145,7 +139,23 @@
/**
* {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.connector.RepositorySource#initialize(org.jboss.dna.spi.connector.RepositoryContext)
*/
+ public void initialize( RepositoryContext context ) throws RepositorySourceException {
+ this.repositoryContext = context;
+ }
+
+ /**
+ * @return repositoryContext
+ */
+ public RepositoryContext getRepositoryContext() {
+ return repositoryContext;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public synchronized String getName() {
return sourceName;
}
@@ -158,12 +168,10 @@
*
* @param sourceName the name of this repository source
* @see #setConfigurationSourceName(String)
- * @see #setRepositoryConnectionFactoryJndiName(String)
* @see #setConfigurationSourcePath(String)
* @see #setPassword(String)
* @see #setUsername(String)
* @see #setRepositoryName(String)
- * @see #setExecutionContextFactoryJndiName(String)
* @see #setPassword(String)
* @see #setUsername(String)
* @see #setName(String)
@@ -193,47 +201,10 @@
}
/**
- * Get the name in JNDI of a {@link FederatedRepository} instance that should be used. If this is set (and an instance can be
- * found at that location), few of the remaining properties on this instance may not be used (basically just
- * {@link #getUsername() username}, {@link #getPassword() password}, and {@link #getName() source name}).
- * <p>
- * This is an optional property.
- * </p>
- *
- * @return the location in JNDI of the {@link FederatedRepository} that should be used by this source, or null if the
- * {@link FederatedRepository} instance will be created from the properties of this instance
- * @see #setRepositoryJndiName(String)
- */
- public String getRepositoryJndiName() {
- return repositoryJndiName;
- }
-
- /**
- * Set the name in JNDI of a {@link FederatedRepository} instance that should be used. If this is set (and an instance can be
- * found at that location), few of the remaining properties on this instance may not be used (basically just
- * {@link #getUsername() username}, {@link #getPassword() password}, and {@link #getName() source name}).
- * <p>
- * This is an optional property.
- * </p>
- *
- * @param jndiName the JNDI name where the {@link FederatedRepository} instance can be found, or null if the instance is not
- * to be found in JNDI but one should be instantiated from this instance's properties
- * @see #getRepositoryJndiName()
- * @see #setPassword(String)
- * @see #setUsername(String)
- * @see #setName(String)
- */
- public void setRepositoryJndiName( String jndiName ) {
- if (this.repositoryJndiName == jndiName || this.repositoryJndiName != null && this.repositoryJndiName.equals(jndiName)) return; // unchanged
- this.repositoryJndiName = jndiName;
- changeRepositoryConfig();
- }
-
- /**
* Get the name in JNDI of a {@link RepositorySource} instance that should be used by the {@link FederatedRepository federated
* repository} as the configuration repository.
* <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
+ * This is a required property.
* </p>
*
* @return the JNDI name of the {@link RepositorySource} instance that should be used for the configuration, or null if the
@@ -247,20 +218,19 @@
/**
* Get the name of a {@link RepositorySource} instance that should be used by the {@link FederatedRepository federated
* repository} as the configuration repository. The instance will be retrieved from the {@link RepositoryConnectionFactory}
- * instance {@link #getRepositoryConnectionFactoryJndiName() found in JDNI}.
+ * instance from the {@link RepositoryContext#getRepositoryConnectionFactory() repository context} supplied during
+ * {@link RepositorySource#initialize(RepositoryContext) initialization}.
* <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
+ * This is a required property.
* </p>
*
* @param sourceName the name of the {@link RepositorySource} instance that should be used for the configuration, or null if
* the federated repository instance is to be found in JNDI
* @see #getConfigurationSourceName()
- * @see #setRepositoryConnectionFactoryJndiName(String)
* @see #setConfigurationSourcePath(String)
* @see #setPassword(String)
* @see #setUsername(String)
* @see #setRepositoryName(String)
- * @see #setExecutionContextFactoryJndiName(String)
* @see #setName(String)
*/
public void setConfigurationSourceName( String sourceName ) {
@@ -273,7 +243,7 @@
/**
* Get the path in the source that will be subgraph below the <code>/dna:system</code> branch of the repository.
* <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
+ * This is a required property.
* </p>
*
* @return the string array of projection rules, or null if the projection rules haven't yet been set or if the federated
@@ -287,19 +257,17 @@
/**
* Set the path in the source that will be subgraph below the <code>/dna:system</code> branch of the repository.
* <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
+ * This is a required property.
* </p>
*
* @param pathInSourceToConfigurationRoot the path within the configuration source to the node that should be the root of the
* configuration information, or null if the path hasn't yet been set or if the federated repository instance is to be
* found in JNDI
* @see #setConfigurationSourcePath(String)
- * @see #setRepositoryConnectionFactoryJndiName(String)
* @see #setConfigurationSourceName(String)
* @see #setPassword(String)
* @see #setUsername(String)
* @see #setRepositoryName(String)
- * @see #setExecutionContextFactoryJndiName(String)
* @see #setName(String)
*/
public void setConfigurationSourcePath( String pathInSourceToConfigurationRoot ) {
@@ -310,87 +278,6 @@
}
/**
- * Get the name in JNDI of a {@link ExecutionContextFactory} instance that should be used to obtain the
- * {@link ExecutionContext execution context} used by the {@link FederatedRepository federated repository}.
- * <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
- * </p>
- *
- * @return the JNDI name of the {@link ExecutionContextFactory} instance that should be used, or null if the federated
- * repository instance is to be found in JNDI
- * @see #setExecutionContextFactoryJndiName(String)
- */
- public String getExecutionContextFactoryJndiName() {
- return executionContextFactoryJndiName;
- }
-
- /**
- * Set the name in JNDI of a {@link ExecutionContextFactory} instance that should be used to obtain the
- * {@link ExecutionContext execution context} used by the {@link FederatedRepository federated repository}.
- * <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
- * </p>
- *
- * @param jndiName the JNDI name where the {@link ExecutionContextFactory} instance can be found, or null if the federated
- * repository instance is to be found in JNDI
- * @see #getExecutionContextFactoryJndiName()
- * @see #setConfigurationSourceName(String)
- * @see #setConfigurationSourcePath(String)
- * @see #setRepositoryConnectionFactoryJndiName(String)
- * @see #setPassword(String)
- * @see #setUsername(String)
- * @see #setRepositoryName(String)
- * @see #setName(String)
- */
- public synchronized void setExecutionContextFactoryJndiName( String jndiName ) {
- if (this.repositoryJndiName == jndiName || this.repositoryJndiName != null && this.repositoryJndiName.equals(jndiName)) return;
- this.executionContextFactoryJndiName = jndiName; // unchanged
- changeRepositoryConfig();
- }
-
- /**
- * Get the name in JNDI where the {@link RepositoryConnectionFactory} instance that can be used by the
- * {@link FederatedRepository federated repository} can find any {@link RepositorySource} sources it needs, including those
- * used for {@link Projection sources} and that used for it's {@link #getConfigurationSourceName() configuration}.
- * <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
- * </p>
- *
- * @return the JNDI name where the {@link RepositoryConnectionFactory} instance can be found, or null if the federated
- * repository instance is to be found in JNDI
- * @see #setRepositoryConnectionFactoryJndiName(String)
- */
- public String getRepositoryConnectionFactoryJndiName() {
- return repositoryConnectionFactoryJndiName;
- }
-
- /**
- * Set the name in JNDI where the {@link RepositoryConnectionFactory} instance that can be used by the
- * {@link FederatedRepository federated repository} can find any {@link RepositorySource} sources it needs, including those
- * used for {@link Projection sources} and that used for it's {@link #getConfigurationSourceName() configuration}.
- * <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
- * </p>
- *
- * @param jndiName the JNDI name where the {@link RepositoryConnectionFactory} instance can be found, or null if the federated
- * repository instance is to be found in JNDI
- * @see #getRepositoryConnectionFactoryJndiName()
- * @see #setConfigurationSourceName(String)
- * @see #setConfigurationSourcePath(String)
- * @see #setPassword(String)
- * @see #setUsername(String)
- * @see #setRepositoryName(String)
- * @see #setExecutionContextFactoryJndiName(String)
- * @see #setName(String)
- */
- public synchronized void setRepositoryConnectionFactoryJndiName( String jndiName ) {
- if (this.repositoryConnectionFactoryJndiName == jndiName || this.repositoryConnectionFactoryJndiName != null
- && this.repositoryConnectionFactoryJndiName.equals(jndiName)) return; // unchanged
- this.repositoryConnectionFactoryJndiName = jndiName;
- changeRepositoryConfig();
- }
-
- /**
* Get the name of the security domain that should be used by JAAS to identify the application or security context. This
* should correspond to the JAAS login configuration located within the JAAS login configuration file.
*
@@ -415,7 +302,7 @@
/**
* Get the name of the federated repository.
* <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
+ * This is a required property.
* </p>
*
* @return the name of the repository
@@ -428,7 +315,7 @@
/**
* Get the name of the federated repository.
* <p>
- * This is a required property (unless the {@link #getRepositoryJndiName() federated repository is to be found in JDNI}).
+ * This is a required property.
* </p>
*
* @param repositoryName the new name of the repository
@@ -438,8 +325,6 @@
* @see #setConfigurationSourcePath(String)
* @see #setPassword(String)
* @see #setUsername(String)
- * @see #setRepositoryConnectionFactoryJndiName(String)
- * @see #setExecutionContextFactoryJndiName(String)
* @see #setName(String)
*/
public synchronized void setRepositoryName( String repositoryName ) {
@@ -475,8 +360,6 @@
* @see #setConfigurationSourcePath(String)
* @see #setPassword(String)
* @see #setRepositoryName(String)
- * @see #setRepositoryConnectionFactoryJndiName(String)
- * @see #setExecutionContextFactoryJndiName(String)
* @see #setName(String)
*/
public void setUsername( String username ) {
@@ -510,8 +393,6 @@
* @see #setConfigurationSourcePath(String)
* @see #setUsername(String)
* @see #setRepositoryName(String)
- * @see #setRepositoryConnectionFactoryJndiName(String)
- * @see #setExecutionContextFactoryJndiName(String)
* @see #setName(String)
*/
public void setPassword( String password ) {
@@ -528,12 +409,15 @@
*/
protected synchronized void changeRepositoryConfig() {
if (this.repository != null) {
- // Find in JNDI the repository source registry and the environment ...
- ExecutionContext context = getExecutionContext();
- RepositoryConnectionFactory factory = getConnectionFactory();
- // Compute a new repository config and set it on the repository ...
- FederatedRepositoryConfig newConfig = getRepositoryConfiguration(context, factory);
- this.repository.setConfiguration(newConfig);
+ RepositoryContext repositoryContext = getRepositoryContext();
+ if (repositoryContext != null) {
+ // Find in JNDI the repository source registry and the environment ...
+ ExecutionContext context = getExecutionContext();
+ RepositoryConnectionFactory factory = getRepositoryContext().getRepositoryConnectionFactory();
+ // Compute a new repository config and set it on the repository ...
+ FederatedRepositoryConfig newConfig = getRepositoryConfiguration(context, factory);
+ this.repository.setConfiguration(newConfig);
+ }
}
}
@@ -547,18 +431,14 @@
I18n msg = FederationI18n.propertyIsRequired;
throw new RepositorySourceException(getName(), msg.text("name"));
}
- if (getExecutionContextFactoryJndiName() == null) {
+ if (getRepositoryContext() == null) {
I18n msg = FederationI18n.propertyIsRequired;
- throw new RepositorySourceException(getName(), msg.text("execution context factory JNDI name"));
+ throw new RepositorySourceException(getName(), msg.text("repository context"));
}
- if (getSecurityDomain() == null) {
+ if (getUsername() != null && getSecurityDomain() == null) {
I18n msg = FederationI18n.propertyIsRequired;
throw new RepositorySourceException(getName(), msg.text("security domain"));
}
- if (getRepositoryConnectionFactoryJndiName() == null) {
- I18n msg = FederationI18n.propertyIsRequired;
- throw new RepositorySourceException(getName(), msg.text("repository source registry JNDI name"));
- }
// Find the repository ...
FederatedRepository repository = getRepository();
// Authenticate the user ...
@@ -588,105 +468,30 @@
*/
protected synchronized FederatedRepository getRepository() throws RepositorySourceException {
if (repository == null) {
- String jndiName = this.getRepositoryJndiName();
- Context jndiContext = getContext();
- if (jndiName != null && jndiName.trim().length() != 0) {
- // Look for an existing repository in JNDI ...
- Object object = null;
- try {
- if (jndiContext == null) jndiContext = new InitialContext();
- object = jndiContext.lookup(jndiName);
- if (object != null) repository = (FederatedRepository)object;
- } catch (ClassCastException err) {
- I18n msg = FederationI18n.objectFoundInJndiWasNotOfExpectedType;
- String className = object != null ? object.getClass().getName() : "null";
- throw new RepositorySourceException(getName(), msg.text(jndiName,
- this.getName(),
- FederatedRepository.class.getName(),
- className), err);
- } catch (Throwable err) {
- I18n msg = FederationI18n.unableToFindFederatedRepositoryInJndi;
- throw new RepositorySourceException(getName(), msg.text(this.sourceName, jndiName), err);
- }
- }
-
- if (repository == null) {
- // Find in JNDI the repository source registry and the environment ...
- ExecutionContext context = getExecutionContext();
- RepositoryConnectionFactory connectionFactory = getConnectionFactory();
- // And create the configuration and the repository ...
- FederatedRepositoryConfig config = getRepositoryConfiguration(context, connectionFactory);
- repository = new FederatedRepository(context, connectionFactory, config);
- }
+ ExecutionContext context = getExecutionContext();
+ RepositoryConnectionFactory connectionFactory = getRepositoryContext().getRepositoryConnectionFactory();
+ // And create the configuration and the repository ...
+ FederatedRepositoryConfig config = getRepositoryConfiguration(context, connectionFactory);
+ repository = new FederatedRepository(context, connectionFactory, config);
}
return repository;
}
protected ExecutionContext getExecutionContext() {
- ExecutionContextFactory factory = null;
- Context context = getContext();
- String jndiName = getExecutionContextFactoryJndiName();
- if (jndiName != null && jndiName.trim().length() != 0) {
- Object object = null;
- try {
- if (context == null) context = new InitialContext();
- object = context.lookup(jndiName);
- if (object != null) factory = (ExecutionContextFactory)object;
- } catch (ClassCastException err) {
- I18n msg = FederationI18n.objectFoundInJndiWasNotOfExpectedType;
- String className = object != null ? object.getClass().getName() : "null";
- throw new RepositorySourceException(getName(), msg.text(jndiName,
- this.getName(),
- ExecutionContextFactory.class.getName(),
- className), err);
- } catch (Throwable err) {
- I18n msg = FederationI18n.unableToFindExecutionContextFactoryInJndi;
- throw new RepositorySourceException(getName(), msg.text(this.sourceName, jndiName), err);
- }
- }
- if (factory == null) {
- I18n msg = FederationI18n.unableToFindExecutionContextFactoryInJndi;
- throw new RepositorySourceException(getName(), msg.text(this.sourceName, jndiName));
- }
- String securityDomain = getSecurityDomain();
+ ExecutionContextFactory factory = getRepositoryContext().getExecutionContextFactory();
CallbackHandler handler = createCallbackHandler();
try {
- return factory.create(securityDomain, handler);
+ String securityDomain = getSecurityDomain();
+ if (securityDomain != null || getUsername() != null) {
+ return factory.create(securityDomain, handler);
+ }
+ return factory.create();
} catch (LoginException e) {
I18n msg = FederationI18n.unableToCreateExecutionContext;
- throw new RepositorySourceException(getName(), msg.text(this.sourceName, jndiName, securityDomain), e);
+ throw new RepositorySourceException(getName(), msg.text(this.sourceName, securityDomain), e);
}
}
- protected RepositoryConnectionFactory getConnectionFactory() {
- RepositoryConnectionFactory factories = null;
- Context context = getContext();
- String jndiName = getRepositoryConnectionFactoryJndiName();
- if (jndiName != null && jndiName.trim().length() != 0) {
- Object object = null;
- try {
- if (context == null) context = new InitialContext();
- object = context.lookup(jndiName);
- if (object != null) factories = (RepositoryConnectionFactory)object;
- } catch (ClassCastException err) {
- I18n msg = FederationI18n.objectFoundInJndiWasNotOfExpectedType;
- String className = object != null ? object.getClass().getName() : "null";
- throw new RepositorySourceException(getName(), msg.text(jndiName,
- this.getName(),
- RepositoryConnectionFactory.class.getName(),
- className), err);
- } catch (Throwable err) {
- I18n msg = FederationI18n.unableToFindRepositoryConnectionFactoriesInJndi;
- throw new RepositorySourceException(getName(), msg.text(this.sourceName, jndiName), err);
- }
- }
- if (factories == null) {
- I18n msg = FederationI18n.noRepositoryConnectionFactories;
- throw new RepositorySourceException(getName(), msg.text(this.repositoryName));
- }
- return factories;
- }
-
protected CallbackHandler createCallbackHandler() {
return new CallbackHandler() {
public void handle( Callback[] callbacks ) {
@@ -704,14 +509,6 @@
};
}
- protected Context getContext() {
- return this.jndiContext;
- }
-
- protected synchronized void setContext( Context context ) {
- this.jndiContext = context;
- }
-
/**
* Create a {@link FederatedRepositoryConfig} instance from the current properties of this instance. This method does
* <i>not</i> modify the state of this instance.
@@ -752,7 +549,7 @@
executor = new FederatingCommandExecutor(context, configurationSourceName, projections, connectionFactory);
}
// Wrap the executor with a logging executor ...
- executor = new LoggingCommandExecutor(executor, context.getLogger(getClass()), Logger.Level.INFO);
+ executor = new LoggingCommandExecutor(executor, context.getLogger(getClass()), Logger.Level.DEBUG);
// The configuration projection (via "executor") will convert this path into a path that exists in the configuration
// repository
@@ -824,7 +621,7 @@
if (projection != null) {
Logger logger = context.getLogger(getClass());
if (logger.isTraceEnabled()) {
- logger.trace("Adding projection to federated repository {1}: {2}",
+ logger.trace("Adding projection to federated repository {0}: {1}",
getRepositoryName(),
projection);
}
@@ -845,6 +642,8 @@
} catch (InvalidPathException err) {
I18n msg = FederationI18n.federatedRepositoryCannotBeFound;
throw new FederationException(msg.text(repositoryName));
+ } finally {
+ executor.close();
}
}
@@ -911,18 +710,9 @@
if (getConfigurationSourcePath() != null) {
ref.add(new StringRefAddr(CONFIGURATION_SOURCE_PATH, getConfigurationSourcePath()));
}
- if (getRepositoryConnectionFactoryJndiName() != null) {
- ref.add(new StringRefAddr(REPOSITORY_CONNECTION_FACTORY_JNDI_NAME, getRepositoryConnectionFactoryJndiName()));
- }
- if (getExecutionContextFactoryJndiName() != null) {
- ref.add(new StringRefAddr(EXECUTION_CONTEXT_FACTORY_JNDI_NAME, getExecutionContextFactoryJndiName()));
- }
if (getSecurityDomain() != null) {
ref.add(new StringRefAddr(SECURITY_DOMAIN, getSecurityDomain()));
}
- if (getRepositoryJndiName() != null) {
- ref.add(new StringRefAddr(REPOSITORY_JNDI_NAME, getRepositoryJndiName()));
- }
ref.add(new StringRefAddr(RETRY_LIMIT, Integer.toString(getRetryLimit())));
return ref;
}
@@ -952,9 +742,6 @@
String password = values.get(FederatedRepositorySource.PASSWORD);
String configurationSourceName = values.get(FederatedRepositorySource.CONFIGURATION_SOURCE_NAME);
String configurationSourcePath = values.get(FederatedRepositorySource.CONFIGURATION_SOURCE_PATH);
- String connectionFactoriesJndiName = values.get(FederatedRepositorySource.REPOSITORY_CONNECTION_FACTORY_JNDI_NAME);
- String environmentJndiName = values.get(FederatedRepositorySource.EXECUTION_CONTEXT_FACTORY_JNDI_NAME);
- String repositoryJndiName = values.get(FederatedRepositorySource.REPOSITORY_JNDI_NAME);
String securityDomain = values.get(FederatedRepositorySource.SECURITY_DOMAIN);
String retryLimit = values.get(FederatedRepositorySource.RETRY_LIMIT);
@@ -966,9 +753,6 @@
if (password != null) source.setPassword(password);
if (configurationSourceName != null) source.setConfigurationSourceName(configurationSourceName);
if (configurationSourcePath != null) source.setConfigurationSourcePath(configurationSourcePath);
- if (connectionFactoriesJndiName != null) source.setRepositoryConnectionFactoryJndiName(connectionFactoriesJndiName);
- if (environmentJndiName != null) source.setExecutionContextFactoryJndiName(environmentJndiName);
- if (repositoryJndiName != null) source.setRepositoryJndiName(repositoryJndiName);
if (securityDomain != null) source.setSecurityDomain(securityDomain);
if (retryLimit != null) source.setRetryLimit(Integer.parseInt(retryLimit));
return source;
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederationI18n.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederationI18n.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederationI18n.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -35,12 +35,7 @@
public static I18n nodeDoesNotExistAtPath;
public static I18n errorRemovingNodeFromCache;
- public static I18n unableToFindFederatedRepositoryInJndi;
- public static I18n unableToFindExecutionContextFactoryInJndi;
public static I18n unableToCreateExecutionContext;
- public static I18n unableToFindRepositoryConnectionFactoriesInJndi;
- public static I18n objectFoundInJndiWasNotOfExpectedType;
- public static I18n noRepositoryConnectionFactories;
public static I18n federatedRepositoryCannotBeFound;
public static I18n unableToAuthenticateConnectionToFederatedRepository;
public static I18n repositoryHasBeenShutDown;
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/executor/FederatingCommandExecutor.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/executor/FederatingCommandExecutor.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/executor/FederatingCommandExecutor.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -200,6 +200,11 @@
}
}
connectionsBySourceName.clear();
+ try {
+ if (this.cacheConnection != null) this.cacheConnection.close();
+ } finally {
+ this.cacheConnection = null;
+ }
}
}
@@ -427,92 +432,88 @@
if (sourceNames != null && !sourceNames.contains(source)) continue;
final RepositoryConnection sourceConnection = getConnection(projection);
if (sourceConnection == null) continue; // No source exists by this name
- try {
- // Get the cached information ...
- CachePolicy cachePolicy = sourceConnection.getDefaultCachePolicy();
- if (cachePolicy == null) cachePolicy = this.defaultCachePolicy;
- DateTime expirationTime = null;
- if (cachePolicy != null) {
- expirationTime = getCurrentTimeInUtc().plus(cachePolicy.getTimeToLive(), TimeUnit.MILLISECONDS);
- }
- // Get the paths-in-source where we should fetch node contributions ...
- Set<Path> pathsInSource = projection.getPathsInSource(path, pathFactory);
- if (pathsInSource.isEmpty()) {
- // The source has no contributions, but see whether the project exists BELOW this path.
- // We do this by getting the top-level repository paths of the projection, and then
- // use those to figure out the children of the nodes.
- Contribution contribution = null;
- List<Path> topLevelPaths = projection.getTopLevelPathsInRepository(pathFactory);
- switch (topLevelPaths.size()) {
- case 0:
- break;
- case 1: {
- Path topLevelPath = topLevelPaths.iterator().next();
+ // Get the cached information ...
+ CachePolicy cachePolicy = sourceConnection.getDefaultCachePolicy();
+ if (cachePolicy == null) cachePolicy = this.defaultCachePolicy;
+ DateTime expirationTime = null;
+ if (cachePolicy != null) {
+ expirationTime = getCurrentTimeInUtc().plus(cachePolicy.getTimeToLive(), TimeUnit.MILLISECONDS);
+ }
+ // Get the paths-in-source where we should fetch node contributions ...
+ Set<Path> pathsInSource = projection.getPathsInSource(path, pathFactory);
+ if (pathsInSource.isEmpty()) {
+ // The source has no contributions, but see whether the project exists BELOW this path.
+ // We do this by getting the top-level repository paths of the projection, and then
+ // use those to figure out the children of the nodes.
+ Contribution contribution = null;
+ List<Path> topLevelPaths = projection.getTopLevelPathsInRepository(pathFactory);
+ switch (topLevelPaths.size()) {
+ case 0:
+ break;
+ case 1: {
+ Path topLevelPath = topLevelPaths.iterator().next();
+ if (path.isAncestorOf(topLevelPath)) {
+ assert topLevelPath.size() > path.size();
+ Path.Segment child = topLevelPath.getSegment(path.size());
+ contribution = Contribution.create(source, path, expirationTime, null, child);
+ }
+ break;
+ }
+ default: {
+ // We assume that the top-level paths do not overlap ...
+ List<Path.Segment> children = new ArrayList<Path.Segment>(topLevelPaths.size());
+ for (Path topLevelPath : topLevelPaths) {
if (path.isAncestorOf(topLevelPath)) {
assert topLevelPath.size() > path.size();
Path.Segment child = topLevelPath.getSegment(path.size());
- contribution = Contribution.create(source, path, expirationTime, null, child);
+ children.add(child);
}
- break;
}
- default: {
- // We assume that the top-level paths do not overlap ...
- List<Path.Segment> children = new ArrayList<Path.Segment>(topLevelPaths.size());
- for (Path topLevelPath : topLevelPaths) {
- if (path.isAncestorOf(topLevelPath)) {
- assert topLevelPath.size() > path.size();
- Path.Segment child = topLevelPath.getSegment(path.size());
- children.add(child);
- }
- }
- if (children.size() > 0) {
- contribution = Contribution.create(source, path, expirationTime, null, children);
- }
+ if (children.size() > 0) {
+ contribution = Contribution.create(source, path, expirationTime, null, children);
}
}
- if (contribution == null) contribution = Contribution.create(source, expirationTime);
- contributions.add(contribution);
- } else {
- // There is at least one (real) contribution ...
+ }
+ if (contribution == null) contribution = Contribution.create(source, expirationTime);
+ contributions.add(contribution);
+ } else {
+ // There is at least one (real) contribution ...
- // Get the contributions ...
- final int numPaths = pathsInSource.size();
- if (numPaths == 1) {
- Path pathInSource = pathsInSource.iterator().next();
- BasicGetNodeCommand fromSource = new BasicGetNodeCommand(pathInSource);
- sourceConnection.execute(getExecutionContext(), fromSource);
- if (!fromSource.hasError()) {
- Collection<Property> properties = fromSource.getProperties();
- List<Segment> children = fromSource.getChildren();
- DateTime expTime = fromSource.getCachePolicy() == null ? expirationTime : getCurrentTimeInUtc().plus(fromSource.getCachePolicy().getTimeToLive(),
- TimeUnit.MILLISECONDS);
- Contribution contribution = Contribution.create(source, pathInSource, expTime, properties, children);
- contributions.add(contribution);
- }
- } else {
- BasicGetNodeCommand[] fromSourceCommands = new BasicGetNodeCommand[numPaths];
- int i = 0;
- for (Path pathInSource : pathsInSource) {
- fromSourceCommands[i++] = new BasicGetNodeCommand(pathInSource);
- }
- sourceConnection.execute(context, fromSourceCommands);
- for (BasicGetNodeCommand fromSource : fromSourceCommands) {
- if (fromSource.hasError()) continue;
- Collection<Property> properties = fromSource.getProperties();
- List<Segment> children = fromSource.getChildren();
- DateTime expTime = fromSource.getCachePolicy() == null ? expirationTime : getCurrentTimeInUtc().plus(fromSource.getCachePolicy().getTimeToLive(),
- TimeUnit.MILLISECONDS);
- Contribution contribution = Contribution.create(source,
- fromSource.getPath(),
- expTime,
- properties,
- children);
- contributions.add(contribution);
- }
+ // Get the contributions ...
+ final int numPaths = pathsInSource.size();
+ if (numPaths == 1) {
+ Path pathInSource = pathsInSource.iterator().next();
+ BasicGetNodeCommand fromSource = new BasicGetNodeCommand(pathInSource);
+ sourceConnection.execute(getExecutionContext(), fromSource);
+ if (!fromSource.hasError()) {
+ Collection<Property> properties = fromSource.getProperties();
+ List<Segment> children = fromSource.getChildren();
+ DateTime expTime = fromSource.getCachePolicy() == null ? expirationTime : getCurrentTimeInUtc().plus(fromSource.getCachePolicy().getTimeToLive(),
+ TimeUnit.MILLISECONDS);
+ Contribution contribution = Contribution.create(source, pathInSource, expTime, properties, children);
+ contributions.add(contribution);
}
+ } else {
+ BasicGetNodeCommand[] fromSourceCommands = new BasicGetNodeCommand[numPaths];
+ int i = 0;
+ for (Path pathInSource : pathsInSource) {
+ fromSourceCommands[i++] = new BasicGetNodeCommand(pathInSource);
+ }
+ sourceConnection.execute(context, fromSourceCommands);
+ for (BasicGetNodeCommand fromSource : fromSourceCommands) {
+ if (fromSource.hasError()) continue;
+ Collection<Property> properties = fromSource.getProperties();
+ List<Segment> children = fromSource.getChildren();
+ DateTime expTime = fromSource.getCachePolicy() == null ? expirationTime : getCurrentTimeInUtc().plus(fromSource.getCachePolicy().getTimeToLive(),
+ TimeUnit.MILLISECONDS);
+ Contribution contribution = Contribution.create(source,
+ fromSource.getPath(),
+ expTime,
+ properties,
+ children);
+ contributions.add(contribution);
+ }
}
- } finally {
- sourceConnection.close();
}
}
}
Modified: trunk/extensions/dna-connector-federation/src/main/resources/org/jboss/dna/connector/federation/FederationI18n.properties
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/resources/org/jboss/dna/connector/federation/FederationI18n.properties 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-federation/src/main/resources/org/jboss/dna/connector/federation/FederationI18n.properties 2008-09-16 19:03:58 UTC (rev 521)
@@ -24,12 +24,7 @@
nodeDoesNotExistAtPath = No node exists at {0} (or below {1})
errorRemovingNodeFromCache = Error while removing {0} from cache
-unableToFindFederatedRepositoryInJndi = Unable to find a FederatedRepository instance in JNDI under "{1}" when creating connection to federated source "{0}"
-unableToFindExecutionContextFactoryInJndi = Unable to find an ExecutionContextFactory instance in JNDI under "{1}" when creating connection to federated source "{0}"
-unableToCreateExecutionContext = Unable to create ExecutionContext for connection to federated source "{0}" when using factory in JNDI under "{1}" and security domain "{2}"
-unableToFindRepositoryConnectionFactoriesInJndi = Unable to find an RepositoryConnectionFactories instance in JNDI under "{1}" when creating connection to federated source "{0}"
-objectFoundInJndiWasNotOfExpectedType = Object in JNDI at {0} found by FederatedRepositorySource {1} was expected to be a {2} but instead was a {2}
-noRepositoryConnectionFactories = No RepositoryConnectionFactories instance was specified directly or indirectly found in JNDI when creating connection to federated source "{0}"
+unableToCreateExecutionContext = Unable to create ExecutionContext for connection to federated source "{0}" when using security domain "{1}"
federatedRepositoryCannotBeFound = The federated repository "{0}" cannot be found
unableToAuthenticateConnectionToFederatedRepository = Unable to authenticate "{1}" for repository "{0}"
repositoryHasBeenShutDown = The "{0}" repository has been shut down and may no longer be used.
Modified: trunk/extensions/dna-connector-federation/src/test/java/org/jboss/dna/connector/federation/FederatedRepositorySourceIntegrationTest.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/test/java/org/jboss/dna/connector/federation/FederatedRepositorySourceIntegrationTest.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-federation/src/test/java/org/jboss/dna/connector/federation/FederatedRepositorySourceIntegrationTest.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -40,6 +40,7 @@
import org.jboss.dna.spi.connector.BasicExecutionContext;
import org.jboss.dna.spi.connector.RepositoryConnection;
import org.jboss.dna.spi.connector.RepositoryConnectionFactory;
+import org.jboss.dna.spi.connector.RepositoryContext;
import org.jboss.dna.spi.connector.RepositorySource;
import org.jboss.dna.spi.connector.SimpleRepository;
import org.jboss.dna.spi.connector.SimpleRepositorySource;
@@ -90,6 +91,8 @@
private RepositoryConnectionFactory connectionFactory;
@Mock
private ExecutionContextFactory executionContextFactory;
+ @Mock
+ private RepositoryContext repositoryContext;
@Before
public void beforeEach() throws Exception {
@@ -105,6 +108,8 @@
stub(jndiContext.lookup(executionContextFactoryJndiName)).toReturn(executionContextFactory);
stub(jndiContext.lookup(repositoryConnectionFactoryJndiName)).toReturn(connectionFactory);
stub(executionContextFactory.create(eq(securityDomain), anyCallbackHandler())).toReturn(context);
+ stub(repositoryContext.getExecutionContextFactory()).toReturn(executionContextFactory);
+ stub(repositoryContext.getRepositoryConnectionFactory()).toReturn(connectionFactory);
// Set up the federated repository source ...
source = new FederatedRepositorySource("Test Repository");
@@ -116,10 +121,8 @@
source.setPassword(credentials);
source.setConfigurationSourceName(configurationSourceName);
source.setConfigurationSourcePath("/repos/RepoX");
- source.setRepositoryConnectionFactoryJndiName(repositoryConnectionFactoryJndiName);
- source.setExecutionContextFactoryJndiName(executionContextFactoryJndiName);
- source.setContext(jndiContext);
source.setSecurityDomain(securityDomain);
+ source.initialize(repositoryContext);
// Set up the configuration repository with its content ...
config = SimpleRepository.get("Configuration Repository");
Modified: trunk/extensions/dna-connector-federation/src/test/java/org/jboss/dna/connector/federation/FederatedRepositorySourceTest.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/test/java/org/jboss/dna/connector/federation/FederatedRepositorySourceTest.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-federation/src/test/java/org/jboss/dna/connector/federation/FederatedRepositorySourceTest.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -46,6 +46,7 @@
import org.jboss.dna.spi.connector.BasicExecutionContext;
import org.jboss.dna.spi.connector.RepositoryConnection;
import org.jboss.dna.spi.connector.RepositoryConnectionFactory;
+import org.jboss.dna.spi.connector.RepositoryContext;
import org.jboss.dna.spi.connector.RepositorySourceException;
import org.jboss.dna.spi.connector.SimpleRepository;
import org.jboss.dna.spi.connector.SimpleRepositorySource;
@@ -66,8 +67,6 @@
private String repositoryName;
private String username;
private String credentials;
- private String executionContextFactoryJndiName;
- private String repositoryConnectionFactoryJndiName;
private String configurationSourceName;
private String securityDomain;
private SimpleRepository configRepository;
@@ -77,11 +76,11 @@
@Mock
private RepositoryConnection connection;
@Mock
- private Context jndiContext;
- @Mock
private RepositoryConnectionFactory connectionFactory;
@Mock
private ExecutionContextFactory executionContextFactory;
+ @Mock
+ private RepositoryContext repositoryContext;
/**
* @throws java.lang.Exception
@@ -91,8 +90,6 @@
MockitoAnnotations.initMocks(this);
context = new BasicExecutionContext();
context.getNamespaceRegistry().register(DnaLexicon.Namespace.PREFIX, DnaLexicon.Namespace.URI);
- executionContextFactoryJndiName = "context factory jndi name";
- repositoryConnectionFactoryJndiName = "repository connection factory jndi name";
configurationSourceName = "configuration source name";
repositoryName = "Test Repository";
securityDomain = "security domain";
@@ -105,10 +102,8 @@
source.setPassword(credentials);
source.setConfigurationSourceName(configurationSourceName);
source.setConfigurationSourcePath("/dna:repositories/Test Repository");
- source.setRepositoryConnectionFactoryJndiName(repositoryConnectionFactoryJndiName);
- source.setExecutionContextFactoryJndiName(executionContextFactoryJndiName);
- source.setContext(jndiContext);
source.setSecurityDomain(securityDomain);
+ source.initialize(repositoryContext);
configRepository = SimpleRepository.get("Configuration Repository");
configRepository.setProperty(context, "/dna:repositories/Test Repository/dna:federation/", "dna:timeToExpire", "100000");
configRepository.setProperty(context, "/dna:repositories/Test Repository/dna:federation/", "dna:timeToCache", "100000");
@@ -128,9 +123,9 @@
configRepositorySource.setRepositoryName(configRepository.getRepositoryName());
configRepositorySource.setName(configurationSourceName);
configRepositoryConnection = configRepositorySource.getConnection();
+ stub(repositoryContext.getExecutionContextFactory()).toReturn(executionContextFactory);
+ stub(repositoryContext.getRepositoryConnectionFactory()).toReturn(connectionFactory);
stub(connectionFactory.createConnection(configurationSourceName)).toReturn(configRepositoryConnection);
- stub(jndiContext.lookup(executionContextFactoryJndiName)).toReturn(executionContextFactory);
- stub(jndiContext.lookup(repositoryConnectionFactoryJndiName)).toReturn(connectionFactory);
stub(executionContextFactory.create(eq(securityDomain), anyCallbackHandler())).toReturn(context);
}
@@ -272,9 +267,6 @@
source.setName("Some source");
source.setConfigurationSourceName("config source");
source.setConfigurationSourcePath("/a/b/c");
- source.setRepositoryConnectionFactoryJndiName("repository connection factory jndi name");
- source.setRepositoryJndiName("repository jndi name");
- source.setExecutionContextFactoryJndiName("env jndi name");
Reference ref = source.getReference();
assertThat(ref.getClassName(), is(FederatedRepositorySource.class.getName()));
@@ -295,12 +287,6 @@
assertThat((String)refAttributes.remove(FederatedRepositorySource.CONFIGURATION_SOURCE_NAME),
is(source.getConfigurationSourceName()));
assertThat((String)refAttributes.remove(FederatedRepositorySource.CONFIGURATION_SOURCE_PATH), is("/a/b/c"));
- assertThat((String)refAttributes.remove(FederatedRepositorySource.REPOSITORY_CONNECTION_FACTORY_JNDI_NAME),
- is(source.getRepositoryConnectionFactoryJndiName()));
- assertThat((String)refAttributes.remove(FederatedRepositorySource.EXECUTION_CONTEXT_FACTORY_JNDI_NAME),
- is(source.getExecutionContextFactoryJndiName()));
- assertThat((String)refAttributes.remove(FederatedRepositorySource.REPOSITORY_JNDI_NAME),
- is(source.getRepositoryJndiName()));
assertThat((String)refAttributes.remove(FederatedRepositorySource.SECURITY_DOMAIN), is(securityDomain));
assertThat(refAttributes.isEmpty(), is(true));
@@ -319,9 +305,6 @@
assertThat(recoveredSource.getRetryLimit(), is(source.getRetryLimit()));
assertThat(recoveredSource.getConfigurationSourceName(), is(source.getConfigurationSourceName()));
assertThat(recoveredSource.getConfigurationSourcePath(), is(source.getConfigurationSourcePath()));
- assertThat(recoveredSource.getRepositoryConnectionFactoryJndiName(), is(source.getRepositoryConnectionFactoryJndiName()));
- assertThat(recoveredSource.getExecutionContextFactoryJndiName(), is(source.getExecutionContextFactoryJndiName()));
- assertThat(recoveredSource.getRepositoryJndiName(), is(source.getRepositoryJndiName()));
assertThat(recoveredSource.getSecurityDomain(), is(source.getSecurityDomain()));
assertThat(recoveredSource.equals(source), is(true));
Modified: trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryConnection.java
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryConnection.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryConnection.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -129,15 +129,19 @@
}
}
+ CommandExecutor executor = this.content.getCommandExecutor(context, this.getSourceName());
try {
// Obtain the lock and execute the commands ...
- CommandExecutor executor = this.content.getCommandExecutor(context, this.getSourceName());
lock.lock();
for (GraphCommand command : commands) {
executor.execute(command);
}
} finally {
- lock.unlock();
+ try {
+ executor.close();
+ } finally {
+ lock.unlock();
+ }
}
if (logger.isTraceEnabled()) {
assert sw != null;
Modified: trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositorySource.java
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositorySource.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositorySource.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -45,6 +45,7 @@
import org.jboss.dna.common.util.ArgCheck;
import org.jboss.dna.spi.cache.CachePolicy;
import org.jboss.dna.spi.connector.RepositoryConnection;
+import org.jboss.dna.spi.connector.RepositoryContext;
import org.jboss.dna.spi.connector.RepositorySource;
import org.jboss.dna.spi.connector.RepositorySourceCapabilities;
import org.jboss.dna.spi.connector.RepositorySourceException;
@@ -78,6 +79,7 @@
private CachePolicy defaultCachePolicy;
private final AtomicInteger retryLimit = new AtomicInteger(DEFAULT_RETRY_LIMIT);
private transient InMemoryRepository repository;
+ private transient RepositoryContext repositoryContext;
/**
* Create a repository source instance.
@@ -89,6 +91,22 @@
/**
* {@inheritDoc}
*
+ * @see org.jboss.dna.spi.connector.RepositorySource#initialize(org.jboss.dna.spi.connector.RepositoryContext)
+ */
+ public void initialize( RepositoryContext context ) throws RepositorySourceException {
+ this.repositoryContext = context;
+ }
+
+ /**
+ * @return repositoryContext
+ */
+ public RepositoryContext getRepositoryContext() {
+ return repositoryContext;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
* @see org.jboss.dna.spi.connector.RepositorySource#getRetryLimit()
*/
public int getRetryLimit() {
Modified: trunk/extensions/dna-connector-jbosscache/src/main/java/org/jboss/dna/connector/jbosscache/JBossCacheSource.java
===================================================================
--- trunk/extensions/dna-connector-jbosscache/src/main/java/org/jboss/dna/connector/jbosscache/JBossCacheSource.java 2008-09-16 16:39:31 UTC (rev 520)
+++ trunk/extensions/dna-connector-jbosscache/src/main/java/org/jboss/dna/connector/jbosscache/JBossCacheSource.java 2008-09-16 19:03:58 UTC (rev 521)
@@ -48,6 +48,7 @@
import org.jboss.dna.spi.DnaLexicon;
import org.jboss.dna.spi.cache.CachePolicy;
import org.jboss.dna.spi.connector.RepositoryConnection;
+import org.jboss.dna.spi.connector.RepositoryContext;
import org.jboss.dna.spi.connector.RepositorySource;
import org.jboss.dna.spi.connector.RepositorySourceCapabilities;
import org.jboss.dna.spi.connector.RepositorySourceException;
@@ -99,6 +100,7 @@
private final AtomicInteger retryLimit = new AtomicInteger(DEFAULT_RETRY_LIMIT);
private transient Cache<Name, Object> cache;
private transient Context jndiContext;
+ private transient RepositoryContext repositoryContext;
/**
* Create a repository source instance.
@@ -108,7 +110,23 @@
/**
* {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.connector.RepositorySource#initialize(org.jboss.dna.spi.connector.RepositoryContext)
*/
+ public void initialize( RepositoryContext context ) throws RepositorySourceException {
+ this.repositoryContext = context;
+ }
+
+ /**
+ * @return repositoryContext
+ */
+ public RepositoryContext getRepositoryContext() {
+ return repositoryContext;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public String getName() {
return this.name;
}
15 years, 7 months
DNA SVN: r520 - in trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation: contribution and 1 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-16 12:39:31 -0400 (Tue, 16 Sep 2008)
New Revision: 520
Modified:
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/Projection.java
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/contribution/Contribution.java
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/executor/FederatingCommandExecutor.java
Log:
DNA-224 - dna-connector-federation: one test in FederatingCommandExecutorTest doesn't work with JDK 1.6.0_05 on Mac OS X
http://jira.jboss.com/jira/browse/DNA-224
The problem appeared because of a modified implementation of a Set, which resulted in a different order to some of the top-level nodes in a Projection. This in fact was a bug where the top-level nodes of a projection were not ordered. This was fixed by making them ordered, keeping the same order as the projection's rules.
All tests now pass on JDK 1.5 and JDK 1.6.
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/Projection.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/Projection.java 2008-09-16 15:38:12 UTC (rev 519)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/Projection.java 2008-09-16 16:39:31 UTC (rev 520)
@@ -322,13 +322,20 @@
* Get the paths in the repository that serve as top-level nodes exposed by this projection.
*
* @param factory the path factory that can be used to create new paths; may not be null
- * @return the set of top-level paths; never null
+ * @return the list of top-level paths, in the proper order and containing no duplicates; never null
*/
- public Set<Path> getTopLevelPathsInRepository( PathFactory factory ) {
+ public List<Path> getTopLevelPathsInRepository( PathFactory factory ) {
ArgCheck.isNotNull(factory, "factory");
- Set<Path> paths = new HashSet<Path>();
+ List<Rule> rules = getRules();
+ Set<Path> uniquePaths = new HashSet<Path>();
+ List<Path> paths = new ArrayList<Path>(rules.size());
for (Rule rule : getRules()) {
- paths.addAll(rule.getTopLevelPathsInRepository(factory));
+ for (Path path : rule.getTopLevelPathsInRepository(factory)) {
+ if (!uniquePaths.contains(path)) {
+ paths.add(path);
+ uniquePaths.add(path);
+ }
+ }
}
return paths;
}
@@ -450,9 +457,9 @@
* Get the paths in the repository that serve as top-level nodes exposed by this rule.
*
* @param factory the path factory that can be used to create new paths; may not be null
- * @return the set of top-level paths; never null
+ * @return the list of top-level paths, which are ordered and which must be unique; never null
*/
- public abstract Set<Path> getTopLevelPathsInRepository( PathFactory factory );
+ public abstract List<Path> getTopLevelPathsInRepository( PathFactory factory );
/**
* Get the path in source that is projected from the supplied repository path, or null if the supplied repository path is
@@ -500,6 +507,7 @@
/** The paths (relative to the source path) that identify exceptions to this rule */
private final List<Path> exceptions;
private final int hc;
+ private final List<Path> topLevelRepositoryPaths;
public PathRule( Path repositoryPath,
Path sourcePath ) {
@@ -524,6 +532,7 @@
}
this.hc = HashCode.compute(sourcePath, repositoryPath, exceptions);
assert exceptionPathsAreRelative();
+ this.topLevelRepositoryPaths = Collections.singletonList(getPathInRepository());
}
public PathRule( Path repositoryPath,
@@ -540,6 +549,7 @@
}
this.hc = HashCode.compute(sourcePath, repositoryPath, exceptions);
assert exceptionPathsAreRelative();
+ this.topLevelRepositoryPaths = Collections.singletonList(getPathInRepository());
}
private boolean exceptionPathsAreRelative() {
@@ -617,8 +627,8 @@
* @see org.jboss.dna.connector.federation.Projection.Rule#getTopLevelPathsInRepository(org.jboss.dna.spi.graph.PathFactory)
*/
@Override
- public Set<Path> getTopLevelPathsInRepository( PathFactory factory ) {
- return Collections.singleton(getPathInRepository());
+ public List<Path> getTopLevelPathsInRepository( PathFactory factory ) {
+ return topLevelRepositoryPaths;
}
/**
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/contribution/Contribution.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/contribution/Contribution.java 2008-09-16 15:38:12 UTC (rev 519)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/contribution/Contribution.java 2008-09-16 16:39:31 UTC (rev 520)
@@ -24,6 +24,7 @@
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
+import java.util.List;
import java.util.NoSuchElementException;
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.StringUtil;
@@ -141,7 +142,7 @@
Path pathInSource,
DateTime expirationTime,
Collection<Property> properties,
- Collection<Segment> children ) {
+ List<Segment> children ) {
if (properties == null || properties.isEmpty()) {
// There are no properties ...
if (children == null || children.isEmpty()) {
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/executor/FederatingCommandExecutor.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/executor/FederatingCommandExecutor.java 2008-09-16 15:38:12 UTC (rev 519)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/executor/FederatingCommandExecutor.java 2008-09-16 16:39:31 UTC (rev 520)
@@ -442,7 +442,7 @@
// We do this by getting the top-level repository paths of the projection, and then
// use those to figure out the children of the nodes.
Contribution contribution = null;
- Set<Path> topLevelPaths = projection.getTopLevelPathsInRepository(pathFactory);
+ List<Path> topLevelPaths = projection.getTopLevelPathsInRepository(pathFactory);
switch (topLevelPaths.size()) {
case 0:
break;
@@ -456,7 +456,8 @@
break;
}
default: {
- Set<Path.Segment> children = new HashSet<Path.Segment>();
+ // We assume that the top-level paths do not overlap ...
+ List<Path.Segment> children = new ArrayList<Path.Segment>(topLevelPaths.size());
for (Path topLevelPath : topLevelPaths) {
if (path.isAncestorOf(topLevelPath)) {
assert topLevelPath.size() > path.size();
@@ -482,7 +483,7 @@
sourceConnection.execute(getExecutionContext(), fromSource);
if (!fromSource.hasError()) {
Collection<Property> properties = fromSource.getProperties();
- Collection<Segment> children = fromSource.getChildren();
+ List<Segment> children = fromSource.getChildren();
DateTime expTime = fromSource.getCachePolicy() == null ? expirationTime : getCurrentTimeInUtc().plus(fromSource.getCachePolicy().getTimeToLive(),
TimeUnit.MILLISECONDS);
Contribution contribution = Contribution.create(source, pathInSource, expTime, properties, children);
@@ -498,7 +499,7 @@
for (BasicGetNodeCommand fromSource : fromSourceCommands) {
if (fromSource.hasError()) continue;
Collection<Property> properties = fromSource.getProperties();
- Collection<Segment> children = fromSource.getChildren();
+ List<Segment> children = fromSource.getChildren();
DateTime expTime = fromSource.getCachePolicy() == null ? expirationTime : getCurrentTimeInUtc().plus(fromSource.getCachePolicy().getTimeToLive(),
TimeUnit.MILLISECONDS);
Contribution contribution = Contribution.create(source,
15 years, 7 months
DNA SVN: r519 - in trunk: dna-repository/src/test/java/org/jboss/dna/repository/mimetype and 2 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-16 11:38:12 -0400 (Tue, 16 Sep 2008)
New Revision: 519
Modified:
trunk/dna-common/src/main/java/org/jboss/dna/common/math/Duration.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/mimetype/AbstractMimeTypeTest.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/mimetype/MimeTypeTest.java
trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/ConsoleInput.java
trunk/docs/examples/gettingstarted/sequencers/src/main/java/org/jboss/example/dna/sequencers/ConsoleInput.java
Log:
DNA-224 - dna-connector-federation: one test in FederatingCommandExecutorTest doesn't work with JDK 1.6.0_05 on Mac OS X
http://jira.jboss.com/jira/browse/DNA-224
Corrected several compiler warnings when compiling under JDK 1.6, some of which involved using TimeUnit.convert(...) to do conversions rather than switch statements. (Not only is it more correct, but JDK 1.6 adds more enumerations to the TimeUnit enum, which broke the previous logic.)
Modified: trunk/dna-common/src/main/java/org/jboss/dna/common/math/Duration.java
===================================================================
--- trunk/dna-common/src/main/java/org/jboss/dna/common/math/Duration.java 2008-09-16 13:30:16 UTC (rev 518)
+++ trunk/dna-common/src/main/java/org/jboss/dna/common/math/Duration.java 2008-09-16 15:38:12 UTC (rev 519)
@@ -38,6 +38,7 @@
/**
* Create a duration given the number of nanoseconds.
+ *
* @param nanos the number of nanoseconds in the duration
*/
public Duration( long nanos ) {
@@ -46,11 +47,13 @@
/**
* Create a duration and the time unit.
+ *
* @param duration the duration in the supplied time units
* @param unit the time unit
*/
- public Duration( long duration, TimeUnit unit ) {
- this.durationInNanos = getTimeInNanos(duration, unit);
+ public Duration( long duration,
+ TimeUnit unit ) {
+ this.durationInNanos = TimeUnit.NANOSECONDS.convert(duration, unit);
}
/**
@@ -91,28 +94,33 @@
/**
* Add the supplied duration to this duration, and return the result.
+ *
* @param duration the duration to add to this object
* @param unit the unit of the duration being added; may not be null
* @return the total duration
*/
- public Duration add( long duration, TimeUnit unit ) {
- long durationInNanos = getTimeInNanos(duration, unit);
+ public Duration add( long duration,
+ TimeUnit unit ) {
+ long durationInNanos = TimeUnit.NANOSECONDS.convert(duration, unit);
return new Duration(this.durationInNanos + durationInNanos);
}
/**
* Subtract the supplied duration from this duration, and return the result.
+ *
* @param duration the duration to subtract from this object
* @param unit the unit of the duration being subtracted; may not be null
* @return the total duration
*/
- public Duration subtract( long duration, TimeUnit unit ) {
- long durationInNanos = getTimeInNanos(duration, unit);
+ public Duration subtract( long duration,
+ TimeUnit unit ) {
+ long durationInNanos = TimeUnit.NANOSECONDS.convert(duration, unit);
return new Duration(this.durationInNanos - durationInNanos);
}
/**
* Add the supplied duration to this duration, and return the result. A null value is treated as a duration of 0 nanoseconds.
+ *
* @param duration the duration to add to this object
* @return the total duration
*/
@@ -123,6 +131,7 @@
/**
* Subtract the supplied duration from this duration, and return the result. A null value is treated as a duration of 0
* nanoseconds.
+ *
* @param duration the duration to subtract from this object
* @return the resulting duration
*/
@@ -132,6 +141,7 @@
/**
* Multiply the duration by the supplied scale factor, and return the result.
+ *
* @param scale the factor by which the duration is to be scaled.
* @return the scaled duration
*/
@@ -141,6 +151,7 @@
/**
* Divide the duration by the supplied number, and return the result.
+ *
* @param denominator the factor by which the duration is to be divided.
* @return the resulting duration
*/
@@ -150,6 +161,7 @@
/**
* Divide the duration by another duration to calculate the ratio.
+ *
* @param duration the duration that this duration is to be divided by; may not be null
* @return the resulting duration
*/
@@ -167,6 +179,7 @@
/**
* Return the total duration in nanoseconds.
+ *
* @return the total duration in nanoseconds
*/
public long getDuratinInNanoseconds() {
@@ -175,6 +188,7 @@
/**
* Return the total duration in microseconds, which may contain a fraction part for the sub-microsecond component.
+ *
* @return the total duration in microseconds
*/
public BigDecimal getDurationInMicroseconds() {
@@ -183,6 +197,7 @@
/**
* Return the total duration in microseconds, which may contain a fraction part for the sub-microsecond component.
+ *
* @return the total duration in microseconds
*/
public BigDecimal getDurationInMilliseconds() {
@@ -191,6 +206,7 @@
/**
* Return the total duration in microseconds, which may contain a fraction part for the sub-microsecond component.
+ *
* @return the total duration in microseconds
*/
public BigDecimal getDurationInSeconds() {
@@ -199,6 +215,7 @@
/**
* Return the duration components.
+ *
* @return the individual time components of this duration
*/
public Components getComponents() {
@@ -220,22 +237,13 @@
/**
* Get the duration value in the supplied unit of time.
+ *
* @param unit the unit of time for the returned value; may not be null
* @return the value of this duration in the supplied unit of time
*/
public long getDuration( TimeUnit unit ) {
if (unit == null) throw new IllegalArgumentException();
- switch (unit) {
- case NANOSECONDS:
- return this.durationInNanos;
- case MICROSECONDS:
- return this.toBigDecimal().divide(new BigDecimal(1000)).longValue();
- case MILLISECONDS:
- return this.toBigDecimal().divide(new BigDecimal(1000000)).longValue();
- case SECONDS:
- return this.toBigDecimal().divide(new BigDecimal(1000000000)).longValue();
- }
- return this.durationInNanos; // should never get here
+ return unit.convert(durationInNanos, TimeUnit.NANOSECONDS);
}
/**
@@ -249,9 +257,10 @@
* <dt>SS</dt>
* <dd>is the number of hours written in at least 2 digits (e.g., "03")</dd>
* <dt>mmm,mmm</dt>
- * <dd>is the fractional part of seconds, written in at least millisecond precision and up to microsecond precision. The
- * comma appears if more than 3 digits are used.
+ * <dd>is the fractional part of seconds, written in at least millisecond precision and up to microsecond precision. The comma
+ * appears if more than 3 digits are used.
* </dl>
+ *
* @return a string representation of the duration
*/
@Override
@@ -260,21 +269,6 @@
return this.getComponents().toString().replaceAll("(\\d{2}).(\\d{3})(\\d{1,3})", "$1.$2,$3");
}
- protected static long getTimeInNanos( long duration, TimeUnit unit ) {
- if (unit == null) throw new IllegalArgumentException();
- switch (unit) {
- case NANOSECONDS:
- return duration;
- case MICROSECONDS:
- return new BigDecimal(duration).multiply(new BigDecimal(1000)).longValue();
- case MILLISECONDS:
- return new BigDecimal(duration).multiply(new BigDecimal(1000000)).longValue();
- case SECONDS:
- return new BigDecimal(duration).multiply(new BigDecimal(1000000000)).longValue();
- }
- return duration; // should never get here
- }
-
/**
* The atomic components of this duration, broken down into whole hours, minutes and (fractional) seconds.
*/
@@ -284,7 +278,9 @@
private final int minutes;
private final double seconds;
- protected Components( int hours, int minutes, double seconds ) {
+ protected Components( int hours,
+ int minutes,
+ double seconds ) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
@@ -292,6 +288,7 @@
/**
* Get the whole hours in this duration.
+ *
* @return the hours
*/
public int getHours() {
@@ -300,6 +297,7 @@
/**
* Get the whole minutes in this duration.
+ *
* @return the minutes, from 0 to 59.
*/
public int getMinutes() {
@@ -308,6 +306,7 @@
/**
* Get the duration's seconds component.
+ *
* @return the number of seconds, including fractional part.
*/
public double getSeconds() {
@@ -327,13 +326,15 @@
* <dt>mmm</dt>
* <dd>is the fractional part of seconds, written with 3-6 digits (any trailing zeros are dropped)
* </dl>
+ *
* @return a string representation of the duration components
*/
@Override
public String toString() {
// Format the string, and have at least 2 digits for the hours, minutes and whole seconds,
// and between 3 and 6 digits for the fractional part of the seconds...
- String result = new DecimalFormat("######00").format(hours) + ':' + new DecimalFormat("00").format(minutes) + ':' + new DecimalFormat("00.000###").format(seconds);
+ String result = new DecimalFormat("######00").format(hours) + ':' + new DecimalFormat("00").format(minutes) + ':'
+ + new DecimalFormat("00.000###").format(seconds);
return result;
}
}
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/mimetype/AbstractMimeTypeTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/mimetype/AbstractMimeTypeTest.java 2008-09-16 13:30:16 UTC (rev 518)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/mimetype/AbstractMimeTypeTest.java 2008-09-16 15:38:12 UTC (rev 519)
@@ -58,7 +58,7 @@
protected void testMimeType( String name,
String mimeType ) throws Exception {
- InputStream content = new File("../../dna-repository/src/test/resources/" + name).toURL().openStream();
+ InputStream content = new File("../../dna-repository/src/test/resources/" + name).toURI().toURL().openStream();
assertThat(MimeType.of(name, content), is(mimeType));
}
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/mimetype/MimeTypeTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/mimetype/MimeTypeTest.java 2008-09-16 13:30:16 UTC (rev 518)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/mimetype/MimeTypeTest.java 2008-09-16 15:38:12 UTC (rev 519)
@@ -34,7 +34,7 @@
private final void testMimeType( String name,
String mimeType ) throws Exception {
- InputStream content = new File("src/test/resources/" + name).toURL().openStream();
+ InputStream content = new File("src/test/resources/" + name).toURI().toURL().openStream();
assertThat(MimeType.of(name, content), is(mimeType));
}
Modified: trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/ConsoleInput.java
===================================================================
--- trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/ConsoleInput.java 2008-09-16 13:30:16 UTC (rev 518)
+++ trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/ConsoleInput.java 2008-09-16 15:38:12 UTC (rev 519)
@@ -109,7 +109,8 @@
System.out.println();
System.out.println();
} catch (Exception err) {
- System.out.println("Error shutting down sequencing service and repository: " + err.getLocalizedMessage());
+ System.out.println("Error shutting down sequencing service and repository: "
+ + err.getLocalizedMessage());
err.printStackTrace(System.err);
}
}
@@ -152,9 +153,10 @@
throw new IllegalArgumentException("Unable to read \"" + file.getAbsolutePath() + "\".");
}
if (!file.isFile()) {
- throw new IllegalArgumentException("Please specify a file. The file \"" + file.getAbsolutePath() + "\" is a directory.");
+ throw new IllegalArgumentException("Please specify a file. The file \"" + file.getAbsolutePath()
+ + "\" is a directory.");
}
- return file.toURL();
+ return file.toURI().toURL();
}
public String getRepositoryPath( String defaultPath ) throws IllegalArgumentException, IOException {
@@ -195,12 +197,12 @@
for (Properties props : javaElement.getValue()) {
for (Map.Entry<Object, Object> entry : props.entrySet()) {
if (!entry.getKey().equals("jcr:primaryType")) {
- System.out.println(entry.getKey() + " => "+ entry.getValue());
+ System.out.println(entry.getKey() + " => " + entry.getValue());
}
}
}
}
-
+
}
System.out.println();
}
Modified: trunk/docs/examples/gettingstarted/sequencers/src/main/java/org/jboss/example/dna/sequencers/ConsoleInput.java
===================================================================
--- trunk/docs/examples/gettingstarted/sequencers/src/main/java/org/jboss/example/dna/sequencers/ConsoleInput.java 2008-09-16 13:30:16 UTC (rev 518)
+++ trunk/docs/examples/gettingstarted/sequencers/src/main/java/org/jboss/example/dna/sequencers/ConsoleInput.java 2008-09-16 15:38:12 UTC (rev 519)
@@ -108,7 +108,8 @@
System.out.println();
System.out.println();
} catch (Exception err) {
- System.out.println("Error shutting down sequencing service and repository: " + err.getLocalizedMessage());
+ System.out.println("Error shutting down sequencing service and repository: "
+ + err.getLocalizedMessage());
err.printStackTrace(System.err);
}
}
@@ -151,9 +152,10 @@
throw new IllegalArgumentException("Unable to read \"" + file.getAbsolutePath() + "\".");
}
if (!file.isFile()) {
- throw new IllegalArgumentException("Please specify a file. The file \"" + file.getAbsolutePath() + "\" is a directory.");
+ throw new IllegalArgumentException("Please specify a file. The file \"" + file.getAbsolutePath()
+ + "\" is a directory.");
}
- return file.toURL();
+ return file.toURI().toURL();
}
public String getRepositoryPath( String defaultPath ) throws IllegalArgumentException, IOException {
15 years, 7 months
DNA SVN: r518 - trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice.
by dna-commits@lists.jboss.org
Author: jverhaeg(a)redhat.com
Date: 2008-09-16 09:30:16 -0400 (Tue, 16 Sep 2008)
New Revision: 518
Modified:
trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice/MSOfficeMetadataSequencer.java
Log:
DNA-152: Changed MSOfficeMetadataSequencer to use new MIME-type detection available in sequencing context.
Modified: trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice/MSOfficeMetadataSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice/MSOfficeMetadataSequencer.java 2008-09-15 14:23:28 UTC (rev 517)
+++ trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice/MSOfficeMetadataSequencer.java 2008-09-16 13:30:16 UTC (rev 518)
@@ -121,8 +121,7 @@
MSOfficeMetadata metadata = MSOfficeMetadataReader.instance(stream);
progressMonitor.worked(3);
- // TODO
- String mimeType = "get mimetype here"; // This will be finished when the Sequencing Context class is done
+ String mimeType = context.getMimeType();
if (metadata != null) {
output.setProperty(METADATA_NODE, MSOFFICE_PRIMARY_TYPE, "msoffice:metadata");
15 years, 7 months
DNA SVN: r517 - trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-15 10:23:28 -0400 (Mon, 15 Sep 2008)
New Revision: 517
Modified:
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositorySource.java
Log:
Corrected misspelling in property name.
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositorySource.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositorySource.java 2008-09-15 14:02:57 UTC (rev 516)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/FederatedRepositorySource.java 2008-09-15 14:23:28 UTC (rev 517)
@@ -98,7 +98,7 @@
protected static final String CONFIGURATION_SOURCE_NAME = "configurationSourceName";
protected static final String CONFIGURATION_SOURCE_PATH = "configurationSourcePath";
protected static final String REPOSITORY_CONNECTION_FACTORY_JNDI_NAME = "repositoryConnectionFactoryJndiName";
- protected static final String EXECUTION_CONTEXT_FACTORY_JNDI_NAME = "executionContextFacotryJndiName";
+ protected static final String EXECUTION_CONTEXT_FACTORY_JNDI_NAME = "executionContextFactoryJndiName";
protected static final String REPOSITORY_JNDI_NAME = "repositoryJndiName";
protected static final String SECURITY_DOMAIN = "securityDomain";
protected static final String RETRY_LIMIT = "retryLimit";
15 years, 7 months
DNA SVN: r516 - in trunk/dna-jcr/src: test/java/org/jboss/dna/jcr and 1 other directory.
by dna-commits@lists.jboss.org
Author: jverhaeg(a)redhat.com
Date: 2008-09-15 10:02:57 -0400 (Mon, 15 Sep 2008)
New Revision: 516
Added:
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java
Modified:
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNamespaceRegistry.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrWorkspace.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNamespaceRegistryTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
Log:
DNA-90: Implemented namespace-related functionality in JCR implementation.
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNamespaceRegistry.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNamespaceRegistry.java 2008-09-11 23:33:03 UTC (rev 515)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNamespaceRegistry.java 2008-09-15 14:02:57 UTC (rev 516)
@@ -21,73 +21,74 @@
*/
package org.jboss.dna.jcr;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
+import java.util.Iterator;
+import java.util.Set;
import javax.jcr.NamespaceException;
import javax.jcr.NamespaceRegistry;
+import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
-import net.jcip.annotations.Immutable;
-import org.jboss.dna.common.util.ArgCheck;
/**
* @author John Verhaeg
* @author Randall Hauch
*/
-@Immutable
-class JcrNamespaceRegistry implements NamespaceRegistry {
+final class JcrNamespaceRegistry implements NamespaceRegistry {
- private Map<String, String> prefix2UriMap = new HashMap<String, String>();
+ private org.jboss.dna.spi.graph.NamespaceRegistry dnaNamespaceRegistry;
- JcrNamespaceRegistry() {
- prefix2UriMap.put("", "");
- prefix2UriMap.put("dna", "http://www.jboss.org/dna/1.0");
- prefix2UriMap.put("jcr", "http://www.jcp.org/jcr/1.0");
- prefix2UriMap.put("mix", "http://www.jcp.org/jcr/mix/1.0");
- prefix2UriMap.put("nt", "http://www.jcp.org/jcr/nt/1.0");
- prefix2UriMap.put("xml", "http://www.w3.org/XML/1998/namespace");
+ JcrNamespaceRegistry( org.jboss.dna.spi.graph.NamespaceRegistry dnaNamespaceRegistry ) {
+ this.dnaNamespaceRegistry = dnaNamespaceRegistry;
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.NamespaceRegistry#getPrefix(java.lang.String)
*/
- public String getPrefix( String uri ) throws NamespaceException {
- ArgCheck.isNotNull(uri, "uri");
- for (Entry<String, String> entry : prefix2UriMap.entrySet()) {
- if (uri.equals(entry.getValue())) {
- return entry.getKey();
- }
+ public String getPrefix( String uri ) throws NamespaceException, RepositoryException {
+ String prefix = dnaNamespaceRegistry.getPrefixForNamespaceUri(uri, false);
+ if (prefix == null) {
+ throw new NamespaceException();
}
- throw new NamespaceException();
+ return prefix;
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.NamespaceRegistry#getPrefixes()
*/
public String[] getPrefixes() {
- String[] prefixes = prefix2UriMap.keySet().toArray(new String[prefix2UriMap.size()]);
- Arrays.sort(prefixes);
+ Set<String> uris = dnaNamespaceRegistry.getRegisteredNamespaceUris();
+ String[] prefixes = new String[uris.size()];
+ Iterator<String> iter = uris.iterator();
+ for (int ndx = 0; iter.hasNext(); ndx++) {
+ prefixes[ndx] = dnaNamespaceRegistry.getPrefixForNamespaceUri(iter.next(), false);
+ }
return prefixes;
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.NamespaceRegistry#getURI(java.lang.String)
*/
public String getURI( String prefix ) throws NamespaceException {
- ArgCheck.isNotNull(prefix, "prefix");
- String uri = prefix2UriMap.get(prefix);
- if (uri == null) throw new NamespaceException();
+ String uri = dnaNamespaceRegistry.getNamespaceForPrefix(prefix);
+ if (uri == null) {
+ throw new NamespaceException();
+ }
return uri;
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.NamespaceRegistry#getURIs()
*/
public String[] getURIs() {
- String[] uris = prefix2UriMap.values().toArray(new String[prefix2UriMap.size()]);
- Arrays.sort(uris);
- return uris;
+ Set<String> uris = dnaNamespaceRegistry.getRegisteredNamespaceUris();
+ return uris.toArray(new String[uris.size()]);
}
/**
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2008-09-11 23:33:03 UTC (rev 515)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2008-09-15 14:02:57 UTC (rev 516)
@@ -204,6 +204,10 @@
return StringUtil.EMPTY_STRING_ARRAY;
}
+ ExecutionContext getExecutionContext() {
+ return executionContext;
+ }
+
/**
* {@inheritDoc}
*
@@ -262,31 +266,28 @@
/**
* {@inheritDoc}
*
- * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getNamespacePrefix(java.lang.String)
*/
- public String getNamespacePrefix( String uri ) {
- throw new UnsupportedOperationException();
+ public String getNamespacePrefix( String uri ) throws RepositoryException {
+ return workspace.getNamespaceRegistry().getPrefix(uri);
}
/**
* {@inheritDoc}
*
- * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getNamespacePrefixes()
*/
- public String[] getNamespacePrefixes() {
- throw new UnsupportedOperationException();
+ public String[] getNamespacePrefixes() throws RepositoryException {
+ return workspace.getNamespaceRegistry().getPrefixes();
}
/**
* {@inheritDoc}
*
- * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getNamespaceURI(java.lang.String)
*/
- public String getNamespaceURI( String prefix ) {
- throw new UnsupportedOperationException();
+ public String getNamespaceURI( String prefix ) throws RepositoryException {
+ return workspace.getNamespaceRegistry().getURI(prefix);
}
private Node getNode( Path path ) throws RepositoryException {
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrWorkspace.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrWorkspace.java 2008-09-11 23:33:03 UTC (rev 515)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrWorkspace.java 2008-09-15 14:02:57 UTC (rev 516)
@@ -40,6 +40,7 @@
private final String name;
private final JcrSession session;
+ private final NamespaceRegistry namespaceRegistry;
/**
* @param session the session that owns this workspace; may not be null
@@ -52,6 +53,7 @@
assert name != null;
this.session = session;
this.name = name;
+ this.namespaceRegistry = new JcrNamespaceRegistry(session.getExecutionContext().getNamespaceRegistry());
// Ensure workspace with supplied name is accessible
// if (name == null) name = session.getDnaRepository().getSource(session.getSubject()).getName();
// String matchedName = null;
@@ -68,6 +70,8 @@
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.Workspace#clone(java.lang.String, java.lang.String, java.lang.String, boolean)
*/
public void clone( String srcWorkspace,
String srcAbsPath,
@@ -137,9 +141,11 @@
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.Workspace#getNamespaceRegistry()
*/
public NamespaceRegistry getNamespaceRegistry() {
- throw new UnsupportedOperationException();
+ return namespaceRegistry;
}
/**
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNamespaceRegistryTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNamespaceRegistryTest.java 2008-09-11 23:33:03 UTC (rev 515)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNamespaceRegistryTest.java 2008-09-15 14:02:57 UTC (rev 516)
@@ -27,7 +27,10 @@
import static org.junit.Assert.assertThat;
import javax.jcr.NamespaceException;
import javax.jcr.UnsupportedRepositoryOperationException;
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.ExecutionContextFactory;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
/**
@@ -35,37 +38,42 @@
*/
public class JcrNamespaceRegistryTest {
+ static ExecutionContext executionContext;
private JcrNamespaceRegistry registry;
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ ExecutionContextFactory factory = TestUtil.getExecutionContextFactory();
+ executionContext = factory.create();
+ }
+
@Before
public void before() {
- registry = new JcrNamespaceRegistry();
+ registry = new JcrNamespaceRegistry(executionContext.getNamespaceRegistry());
}
@Test
public void shouldProvidePrefixes() {
String[] prefixes = registry.getPrefixes();
assertThat(prefixes, notNullValue());
- assertThat(prefixes.length, is(6));
assertThat(prefixes, hasItemInArray(""));
assertThat(prefixes, hasItemInArray("dna"));
assertThat(prefixes, hasItemInArray("jcr"));
assertThat(prefixes, hasItemInArray("mix"));
assertThat(prefixes, hasItemInArray("nt"));
- assertThat(prefixes, hasItemInArray("xml"));
+ // assertThat(prefixes, hasItemInArray("xml"));
}
@Test
public void shouldProvideUris() {
String[] uris = registry.getURIs();
assertThat(uris, notNullValue());
- assertThat(uris.length, is(6));
assertThat(uris, hasItemInArray(""));
assertThat(uris, hasItemInArray("http://www.jboss.org/dna/1.0"));
assertThat(uris, hasItemInArray("http://www.jcp.org/jcr/1.0"));
assertThat(uris, hasItemInArray("http://www.jcp.org/jcr/mix/1.0"));
assertThat(uris, hasItemInArray("http://www.jcp.org/jcr/nt/1.0"));
- assertThat(uris, hasItemInArray("http://www.w3.org/XML/1998/namespace"));
+ // assertThat(uris, hasItemInArray("http://www.w3.org/XML/1998/namespace"));
}
@Test( expected = UnsupportedRepositoryOperationException.class )
@@ -95,7 +103,7 @@
assertThat(registry.getPrefix("http://www.jcp.org/jcr/1.0"), is("jcr"));
assertThat(registry.getPrefix("http://www.jcp.org/jcr/mix/1.0"), is("mix"));
assertThat(registry.getPrefix("http://www.jcp.org/jcr/nt/1.0"), is("nt"));
- assertThat(registry.getPrefix("http://www.w3.org/XML/1998/namespace"), is("xml"));
+// assertThat(registry.getPrefix("http://www.w3.org/XML/1998/namespace"), is("xml"));
}
@Test
@@ -105,7 +113,7 @@
assertThat(registry.getURI("jcr"), is("http://www.jcp.org/jcr/1.0"));
assertThat(registry.getURI("mix"), is("http://www.jcp.org/jcr/mix/1.0"));
assertThat(registry.getURI("nt"), is("http://www.jcp.org/jcr/nt/1.0"));
- assertThat(registry.getURI("xml"), is("http://www.w3.org/XML/1998/namespace"));
+// assertThat(registry.getURI("xml"), is("http://www.w3.org/XML/1998/namespace"));
}
@Test( expected = NamespaceException.class )
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2008-09-11 23:33:03 UTC (rev 515)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2008-09-15 14:02:57 UTC (rev 516)
@@ -23,6 +23,7 @@
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
+import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
@@ -37,6 +38,7 @@
import java.util.Map;
import java.util.UUID;
import javax.jcr.Item;
+import javax.jcr.NamespaceException;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyType;
@@ -64,13 +66,13 @@
*/
public class JcrSessionTest {
- private static final String WORKSPACE_NAME = JcrI18n.defaultWorkspaceName.text();
+ static final String WORKSPACE_NAME = JcrI18n.defaultWorkspaceName.text();
- private static ExecutionContext executionContext;
- private static SimpleRepository simpleRepository;
- private static RepositoryConnectionFactory connectionFactory;
- private static RepositoryConnection connection;
- private static Repository repository;
+ static ExecutionContext executionContext;
+ static SimpleRepository simpleRepository;
+ static RepositoryConnectionFactory connectionFactory;
+ static RepositoryConnection connection;
+ static Repository repository;
@BeforeClass
public static void beforeClass() throws Exception {
@@ -287,4 +289,51 @@
public void shouldNotAllowItemExistsWithEmptyPath() throws Exception {
session.itemExists("");
}
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowNoNamespaceUri() throws Exception {
+ session.getNamespacePrefix(null);
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotProvidePrefixForUnknownUri() throws Exception {
+ session.getNamespacePrefix("bogus");
+ }
+
+ @Test
+ public void shouldProvideNamespacePrefix() throws Exception {
+ assertThat(session.getNamespacePrefix("http://www.jboss.org/dna/1.0"), is("dna"));
+ assertThat(session.getNamespacePrefix("http://www.jcp.org/jcr/1.0"), is("jcr"));
+ assertThat(session.getNamespacePrefix("http://www.jcp.org/jcr/mix/1.0"), is("mix"));
+ assertThat(session.getNamespacePrefix("http://www.jcp.org/jcr/nt/1.0"), is("nt"));
+ assertThat(session.getNamespacePrefix("http://www.jcp.org/jcr/sv/1.0"), is("sv"));
+ // assertThat(session.getNamespacePrefix("http://www.w3.org/XML/1998/namespace"), is("xml"));
+ }
+
+ @Test
+ public void shouldProvideNamespacePrefixes() throws Exception {
+ String[] prefixes = session.getNamespacePrefixes();
+ assertThat(prefixes, notNullValue());
+ assertThat(prefixes.length, is(not(0)));
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowNoNamespacePrefix() throws Exception {
+ session.getNamespaceURI(null);
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotProvideUriForUnknownPrefix() throws Exception {
+ session.getNamespaceURI("bogus");
+ }
+
+ @Test
+ public void shouldProvideNamespaceUri() throws Exception {
+ assertThat(session.getNamespaceURI("dna"), is("http://www.jboss.org/dna/1.0"));
+ assertThat(session.getNamespaceURI("jcr"), is("http://www.jcp.org/jcr/1.0"));
+ assertThat(session.getNamespaceURI("mix"), is("http://www.jcp.org/jcr/mix/1.0"));
+ assertThat(session.getNamespaceURI("nt"), is("http://www.jcp.org/jcr/nt/1.0"));
+ assertThat(session.getNamespaceURI("sv"), is("http://www.jcp.org/jcr/sv/1.0"));
+ // assertThat(session.getNamespaceURI("xml"), is("http://www.w3.org/XML/1998/namespace"));
+ }
}
Added: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java (rev 0)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java 2008-09-15 14:02:57 UTC (rev 516)
@@ -0,0 +1,154 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.jcr;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.notNullValue;
+import static org.junit.Assert.assertThat;
+import javax.jcr.Session;
+import javax.jcr.Workspace;
+import org.jboss.dna.spi.ExecutionContextFactory;
+import org.jboss.dna.spi.connector.SimpleRepository;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * @author jverhaeg
+ */
+public class JcrWorkspaceTest {
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ ExecutionContextFactory factory = TestUtil.getExecutionContextFactory();
+ JcrSessionTest.executionContext = factory.create();
+ JcrSessionTest.simpleRepository = SimpleRepository.get(JcrSessionTest.WORKSPACE_NAME);
+ JcrSessionTest.connectionFactory = TestUtil.createJackRabbitConnectionFactory(JcrSessionTest.simpleRepository,
+ JcrSessionTest.executionContext);
+ JcrSessionTest.repository = new JcrRepository(factory, JcrSessionTest.connectionFactory);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ SimpleRepository.shutdownAll();
+ }
+
+ private Session session;
+ private Workspace workspace;
+
+ @Before
+ public void before() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ session = JcrSessionTest.repository.login();
+ workspace = session.getWorkspace();
+ }
+
+ @After
+ public void after() throws Exception {
+ if (session.isLive()) {
+ session.logout();
+ }
+ }
+
+ @Test( expected = AssertionError.class )
+ public void shouldNotAllowNoSession() throws Exception {
+ new JcrWorkspace(null, JcrSessionTest.WORKSPACE_NAME);
+ }
+
+ @Test( expected = AssertionError.class )
+ public void shouldNotAllowNoWorkspaceName() throws Exception {
+ new JcrWorkspace((JcrSession)session, null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowClone() throws Exception {
+ workspace.clone(null, null, null, false);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowCopy() throws Exception {
+ workspace.copy(null, null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowCopyFromOtherWorkspace() throws Exception {
+ workspace.copy(null, null, null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowGetAccessibleWorkspaceNames() throws Exception {
+ workspace.getAccessibleWorkspaceNames();
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowImportContentHandler() throws Exception {
+ workspace.getImportContentHandler(null, 0);
+ }
+
+ @Test
+ public void shouldProvideName() throws Exception {
+ assertThat(workspace.getName(), is(JcrSessionTest.WORKSPACE_NAME));
+ }
+
+ @Test
+ public void shouldProvideNamespaceRegistry() throws Exception {
+ assertThat(workspace.getNamespaceRegistry(), notNullValue());
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowGetNodeTypeManager() throws Exception {
+ workspace.getNodeTypeManager();
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowGetObservationManager() throws Exception {
+ workspace.getObservationManager();
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowGetQueryManager() throws Exception {
+ workspace.getQueryManager();
+ }
+
+ @Test
+ public void shouldProvideSession() throws Exception {
+ assertThat(workspace.getSession(), is(session));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowImportXml() throws Exception {
+ workspace.importXML(null, null, 0);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowMove() throws Exception {
+ workspace.move(null, null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowRestore() throws Exception {
+ workspace.restore(null, false);
+ }
+}
Property changes on: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
15 years, 7 months
DNA SVN: r515 - in trunk: dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml and 17 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-11 19:33:03 -0400 (Thu, 11 Sep 2008)
New Revision: 515
Added:
trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/BasicExecutionContextFactory.java
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/UserInterface.java
trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml
trunk/docs/examples/gettingstarted/repositories/src/main/resources/cars.xml
trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml
trunk/docs/examples/gettingstarted/repositories/src/test/java/org/
trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/
trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/
trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/
trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/
trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java
trunk/extensions/dna-connector-inmemory/src/test/resources/log4j.properties
Modified:
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/XmlSequencer.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java
trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryConnectionPool.java
trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicName.java
trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicNamespaceRegistry.java
trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicNameTest.java
trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicNamespaceRegistryTest.java
trunk/docs/examples/gettingstarted/repositories/pom.xml
trunk/docs/examples/gettingstarted/repositories/src/main/assembly/basic.xml
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java
trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties
trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryConnectorI18n.java
trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepository.java
trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryConnection.java
trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositorySource.java
trunk/extensions/dna-connector-inmemory/src/main/resources/org/jboss/dna/connector/inmemory/InMemoryConnectorI18n.properties
Log:
DNA-222 - Create Getting Started example application for repositories
http://jira.jboss.com/jira/browse/DNA-222
Created a simple application (subproject under getting started examples) that allows a user to pick from a list of repositories so they can interactively navigate and explore them. Currently, only a console user interface is implemented. Several repositories are used: a configuration repository (which defines the others), two in-memory repositories ("Cars" and "Airplanes"), a federated repository ("Vehicles" that federates "Cars" and "Airplanes" below a "vehicles" root), and a cache repository used by "Vehicles".
Most of the unit testing is complete, and several issues have been fixed in other components. However, there still are a few outstanding issues as well as testing of the interactive mode. So, still a bit more work to do.
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -21,6 +21,7 @@
*/
package org.jboss.dna.repository;
+import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
@@ -33,11 +34,13 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import net.jcip.annotations.Immutable;
import org.jboss.dna.common.i18n.I18n;
import org.jboss.dna.common.monitor.ProgressMonitor;
import org.jboss.dna.common.monitor.SimpleProgressMonitor;
import org.jboss.dna.common.util.ArgCheck;
import org.jboss.dna.common.util.Logger;
+import org.jboss.dna.repository.sequencers.xml.DnaXmlLexicon;
import org.jboss.dna.repository.sequencers.xml.XmlSequencer;
import org.jboss.dna.spi.ExecutionContext;
import org.jboss.dna.spi.connector.RepositoryConnection;
@@ -69,27 +72,110 @@
*/
public class RepositoryImporter {
+ public interface ImportSpecification {
+ /**
+ * Specify the location where the content is to be imported, and then perform the import. This is equivalent to calling
+ * <code>{@link #into(String, Path) into(sourceName,rootPath)}</code>.
+ *
+ * @param sourceName the name of the source into which the content is to be imported
+ * @throws IllegalArgumentException if the <code>uri</code> or path are null
+ * @throws IOException if there is a problem reading the content
+ * @throws RepositorySourceException if there is a problem while writing the content to the {@link RepositorySource
+ * repository source}
+ */
+ void into( String sourceName ) throws IOException, RepositorySourceException;
+
+ /**
+ * Specify the location where the content is to be imported, and then perform the import.
+ *
+ * @param sourceName the name of the source into which the content is to be imported
+ * @param pathInSource the path in the {@link RepositorySource repository source} named <code>sourceName</code> where the
+ * content is to be written; may not be null
+ * @throws IllegalArgumentException if the <code>uri</code> or path are null
+ * @throws IOException if there is a problem reading the content
+ * @throws RepositorySourceException if there is a problem while writing the content to the {@link RepositorySource
+ * repository source}
+ */
+ void into( String sourceName,
+ Path pathInSource ) throws IOException, RepositorySourceException;
+ }
+
+ @Immutable
+ protected abstract class ImportedContentUsingSequencer implements ImportSpecification {
+ private final StreamSequencer sequencer;
+
+ protected ImportedContentUsingSequencer( StreamSequencer sequencer ) {
+ this.sequencer = sequencer;
+ }
+
+ protected StreamSequencer getSequencer() {
+ return this.sequencer;
+ }
+
+ protected NodeConflictBehavior getConflictBehavior() {
+ return NodeConflictBehavior.UPDATE;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.repository.RepositoryImporter.ImportSpecification#into(java.lang.String)
+ */
+ public void into( String sourceName ) throws IOException, RepositorySourceException {
+ Path root = getContext().getValueFactories().getPathFactory().createRootPath();
+ into(sourceName, root);
+ }
+ }
+
+ @Immutable
+ protected class UriImportedContent extends ImportedContentUsingSequencer {
+ private final URI uri;
+ private final String mimeType;
+
+ protected UriImportedContent( StreamSequencer sequencer,
+ URI uri,
+ String mimeType ) {
+ super(sequencer);
+ this.uri = uri;
+ this.mimeType = mimeType;
+ }
+
+ /**
+ * @return mimeType
+ */
+ public String getMimeType() {
+ return mimeType;
+ }
+
+ /**
+ * @return uri
+ */
+ public URI getUri() {
+ return uri;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.repository.RepositoryImporter.ImportSpecification#into(java.lang.String,
+ * org.jboss.dna.spi.graph.Path)
+ */
+ public void into( String sourceName,
+ Path pathInSource ) throws IOException, RepositorySourceException {
+ ArgCheck.isNotNull(sourceName, "sourceName");
+ ArgCheck.isNotNull(pathInSource, "pathInSource");
+ importWithSequencer(getSequencer(), uri, mimeType, sourceName, pathInSource, getConflictBehavior());
+ }
+ }
+
private final RepositoryConnectionFactory sources;
- private final String sourceName;
private final ExecutionContext context;
- public RepositoryImporter( RepositorySource source,
- ExecutionContext context ) {
- ArgCheck.isNotNull(source, "source");
- ArgCheck.isNotNull(context, "context");
- this.sources = new SingleRepositorySourceConnectionFactory(source);
- this.sourceName = source.getName();
- this.context = context;
- }
-
public RepositoryImporter( RepositoryConnectionFactory sources,
- String sourceName,
ExecutionContext context ) {
ArgCheck.isNotNull(sources, "sources");
- ArgCheck.isNotEmpty(sourceName, "sourceName");
ArgCheck.isNotNull(context, "context");
this.sources = sources;
- this.sourceName = sourceName;
this.context = context;
}
@@ -103,23 +189,68 @@
}
/**
+ * Import the content from the XML file at the supplied URI, specifying on the returned {@link ImportSpecification} where the
+ * content is to be imported.
+ *
+ * @param uri the URI where the importer can read the content that is to be imported
+ * @return the object that should be used to specify into which the content is to be imported
+ * @throws IllegalArgumentException if the <code>uri</code> or destination path are null
+ */
+ public ImportSpecification importXml( URI uri ) {
+ ArgCheck.isNotNull(uri, "uri");
+
+ // Create the sequencer ...
+ StreamSequencer sequencer = new XmlSequencer();
+ return new UriImportedContent(sequencer, uri, "text/xml");
+ }
+
+ /**
+ * Import the content from the XML file at the supplied file location, specifying on the returned {@link ImportSpecification}
+ * where the content is to be imported.
+ *
+ * @param pathToFile the path to the XML file that should be imported.
+ * @return the object that should be used to specify into which the content is to be imported
+ * @throws IllegalArgumentException if the <code>uri</code> or destination path are null
+ */
+ public ImportSpecification importXml( String pathToFile ) {
+ ArgCheck.isNotNull(pathToFile, "pathToFile");
+ return importXml(new File(pathToFile).toURI());
+ }
+
+ /**
+ * Import the content from the supplied XML file, specifying on the returned {@link ImportSpecification} where the content is
+ * to be imported.
+ *
+ * @param file the XML file that should be imported.
+ * @return the object that should be used to specify into which the content is to be imported
+ * @throws IllegalArgumentException if the <code>uri</code> or destination path are null
+ */
+ public ImportSpecification importXml( File file ) {
+ ArgCheck.isNotNull(file, "file");
+ return importXml(file.toURI());
+ }
+
+ /**
* Read the content from the supplied URI and import into the repository at the supplied location.
*
* @param uri the URI where the importer can read the content that is to be imported
- * @param destinationPathInSource
+ * @param sourceName the name of the source into which the content is to be imported
+ * @param destinationPathInSource the path in the {@link RepositorySource repository source} where the content is to be
+ * written; may not be null
* @throws IllegalArgumentException if the <code>uri</code> or destination path are null
* @throws IOException if there is a problem reading the content
* @throws RepositorySourceException if there is a problem while writing the content to the {@link RepositorySource repository
* source}
*/
public void importXml( URI uri,
+ String sourceName,
Path destinationPathInSource ) throws IOException, RepositorySourceException {
ArgCheck.isNotNull(uri, "uri");
ArgCheck.isNotNull(destinationPathInSource, "destinationPathInSource");
// Create the sequencer ...
StreamSequencer sequencer = new XmlSequencer();
- importWithSequencer(sequencer, uri, "text/xml", destinationPathInSource, NodeConflictBehavior.UPDATE);
+ importWithSequencer(sequencer, uri, "text/xml", sourceName, destinationPathInSource, NodeConflictBehavior.UPDATE);
}
/**
@@ -129,6 +260,7 @@
* @param sequencer the sequencer that should be used; may not be null
* @param contentUri the URI where the content can be found; may not be null
* @param mimeType the MIME type for the content; may not be null
+ * @param sourceName the name of the source into which the content is to be imported
* @param destinationPathInSource the path in the {@link RepositorySource repository source} where the content is to be
* written; may not be null
* @param conflictBehavior the behavior when a node is to be created when an existing node already exists; defaults to
@@ -140,11 +272,13 @@
protected void importWithSequencer( StreamSequencer sequencer,
URI contentUri,
String mimeType,
+ String sourceName,
Path destinationPathInSource,
NodeConflictBehavior conflictBehavior ) throws IOException, RepositorySourceException {
assert sequencer != null;
assert contentUri != null;
assert mimeType != null;
+ assert sourceName != null;
assert destinationPathInSource != null;
conflictBehavior = conflictBehavior != null ? conflictBehavior : NodeConflictBehavior.UPDATE;
@@ -183,7 +317,11 @@
// Now execute the commands against the repository ...
RepositoryConnection connection = null;
try {
- connection = sources.createConnection(this.sourceName);
+ connection = sources.createConnection(sourceName);
+ if (connection == null) {
+ I18n msg = RepositoryI18n.unableToFindRepositorySourceWithName;
+ throw new RepositorySourceException(msg.text(sourceName));
+ }
connection.execute(context, commands);
} finally {
if (connection != null) {
@@ -237,6 +375,8 @@
private final Map<Path, BasicCreateNodeCommand> createNodeCommands = new HashMap<Path, BasicCreateNodeCommand>();
private final NodeConflictBehavior conflictBehavior;
private final Path destinationPath;
+ private final NameFactory nameFactory;
+ private final Name primaryTypeName;
protected ImporterCommands( Path destinationPath,
NodeConflictBehavior conflictBehavior ) {
@@ -244,6 +384,8 @@
ArgCheck.isNotNull(conflictBehavior, "conflictBehavior");
this.conflictBehavior = conflictBehavior;
this.destinationPath = destinationPath;
+ this.nameFactory = getContext().getValueFactories().getNameFactory();
+ this.primaryTypeName = this.nameFactory.create("jcr:primaryType");
}
/**
@@ -287,6 +429,11 @@
public void setProperty( Path nodePath,
Name propertyName,
Object... values ) {
+ // Ignore the property value if the "jcr:primaryType" is "dnaxml:document" ...
+ if (this.primaryTypeName.equals(propertyName) && values.length == 1) {
+ Name typeName = this.nameFactory.create(values[0]);
+ if (DnaXmlLexicon.DOCUMENT.equals(typeName)) return;
+ }
PathFactory pathFactory = getFactories().getPathFactory();
if (nodePath.isAbsolute()) nodePath.relativeTo(pathFactory.createRootPath());
nodePath = pathFactory.create(destinationPath, nodePath).getNormalizedPath();
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -134,7 +134,7 @@
* @param sources the source manager
* @param configurationSourceName the name of the {@link RepositorySource} that is the configuration repository
* @param pathToConfigurationRoot the path of the node in the configuration source repository that should be treated by this
- * service as the root of the service's configuration; if null, then "/" is used
+ * service as the root of the service's configuration; if null, then "/dna:system" is used
* @param context the execution context in which this service should run
* @param classLoaderFactory the class loader factory used to instantiate {@link RepositorySource} instances; may be null if
* this instance should use a default factory that attempts to load classes first from the
@@ -150,7 +150,7 @@
ArgCheck.isNotNull(configurationSourceName, "configurationSourceName");
ArgCheck.isNotNull(sources, "sources");
ArgCheck.isNotNull(context, "context");
- if (pathToConfigurationRoot == null) pathToConfigurationRoot = context.getValueFactories().getPathFactory().createRootPath();
+ if (pathToConfigurationRoot == null) pathToConfigurationRoot = context.getValueFactories().getPathFactory().create("/dna:system");
this.sources = sources;
this.pathToConfigurationRoot = pathToConfigurationRoot;
this.configurationSourceName = configurationSourceName;
@@ -245,6 +245,8 @@
}
} catch (Throwable err) {
throw new FederationException(RepositoryI18n.errorStartingRepositoryService.text());
+ } finally {
+ executor.close();
}
this.started.set(true);
}
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/XmlSequencer.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/XmlSequencer.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/XmlSequencer.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -568,8 +568,21 @@
String name,
Attributes attributes ) throws SAXException {
stopIfCancelled();
- startElement(nameFactory.create(name));
- output.setProperty(path, getPrimaryTypeName(), getDefaultPrimaryType());
+ // Look for the "jcr:name" attribute, and use that if it's there
+ Name type = getDefaultPrimaryType();
+ Name nameObj = nameFactory.create(name);
+ for (int ndx = 0, len = attributes.getLength(); ndx < len; ++ndx) {
+ String ns = attributes.getURI(ndx);
+ String attrLocalName = attributes.getLocalName(ndx);
+ Object value = attributes.getValue(ndx);
+ String jcrNsUri = context.getNamespaceRegistry().getNamespaceForPrefix("jcr");
+ if (jcrNsUri != null && jcrNsUri.equals(ns) && attrLocalName.equals("name")) {
+ nameObj = nameFactory.create(value);
+ break;
+ }
+ }
+ startElement(nameObj);
+ output.setProperty(path, getPrimaryTypeName(), type);
// Output this element's attributes using the attribute's namespace, if supplied, or the current namespace in scope.
String inheritedNs = nsStack.getFirst();
for (int ndx = 0, len = attributes.getLength(); ndx < len; ++ndx) {
@@ -580,6 +593,9 @@
if (jcrNsUri != null && jcrNsUri.equals(ns) && attrLocalName.equals("primaryType")) {
value = nameFactory.create(value);
}
+ if (jcrNsUri != null && jcrNsUri.equals(ns) && attrLocalName.equals("name")) {
+ continue;
+ }
output.setProperty(path, nameFactory.create(ns.length() == 0 ? inheritedNs : ns, attrLocalName), value);
}
updateProgress();
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -83,7 +83,7 @@
context.getNamespaceRegistry().register("nt", "http://www.jcp.org/jcr/nt/1.0");
sourceName = "sourceA";
destinationPath = context.getValueFactories().getPathFactory().create("/a/b");
- importer = new RepositoryImporter(sources, sourceName, context);
+ importer = new RepositoryImporter(sources, context);
connection = new MockRepositoryConnection();
stub(sources.createConnection(sourceName)).toReturn(connection);
}
@@ -91,10 +91,11 @@
@Test
public void shouldImportXmlContentAndGenerateTheCorrectCommands() throws Exception {
System.out.println(xmlContent);
- importer.importXml(xmlContent, destinationPath); // writes commands as CompositeCommand to 'lastExecutedCommand'
+ importer.importXml(xmlContent).into(sourceName, destinationPath); // writes commands as CompositeCommand to
+ // 'lastExecutedCommand'
assertThat(lastExecutedCommand, is(instanceOf(CompositeCommand.class)));
Iterator<GraphCommand> iter = ((CompositeCommand)lastExecutedCommand).iterator();
- assertCreateNode(iter, "/a/b/", "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}document");
+ // assertCreateNode(iter, "/a/b/", "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}document");
assertCreateNode(iter, "/a/b/dnaxml:comment[1]", "any properties"); // jcr:primaryType and dnaxml:commentContent
assertCreateNode(iter, "/a/b/dna:system[1]", "jcr:primaryType={http://www.jcp.org/jcr/nt/1.0}unstructured");
assertCreateNode(iter, "/a/b/dna:system[1]/dnaxml:comment[1]", "any properties");
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -45,6 +45,7 @@
import org.jboss.dna.spi.connector.RepositorySource;
import org.jboss.dna.spi.connector.SimpleRepository;
import org.jboss.dna.spi.connector.SimpleRepositorySource;
+import org.jboss.dna.spi.graph.Path;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -62,6 +63,7 @@
private SimpleRepositorySource configRepositorySource;
private RepositoryConnection configRepositoryConnection;
private ExecutionContext context;
+ private Path root;
@Mock
private RepositorySourceManager sources;
@@ -77,6 +79,7 @@
configRepositorySource.setName(configSourceName);
configRepositoryConnection = configRepositorySource.getConnection();
stub(sources.createConnection(configSourceName)).toReturn(configRepositoryConnection);
+ root = context.getValueFactories().getPathFactory().createRootPath();
service = new RepositoryService(sources, configSourceName, context, null);
}
@@ -150,7 +153,7 @@
sources.addSource(configRepositorySource);
assertThat(sources.getSources(), hasItems((RepositorySource)configRepositorySource));
assertThat(sources.getSources().size(), is(1));
- service = new RepositoryService(sources, configSourceName, context, null);
+ service = new RepositoryService(sources, configSourceName, root, context, null);
// Set up the configuration repository to contain 3 sources ...
final String className = SimpleRepositorySource.class.getName();
Added: trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/BasicExecutionContextFactory.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/BasicExecutionContextFactory.java (rev 0)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/BasicExecutionContextFactory.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -0,0 +1,166 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.spi.connector;
+
+import java.security.AccessControlContext;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.ExecutionContextFactory;
+import org.jboss.dna.spi.graph.NamespaceRegistry;
+import org.jboss.dna.spi.graph.impl.BasicNamespaceRegistry;
+
+/**
+ * Basic implementation of a {@link ExecutionContextFactory} that returns {@link BasicExecutionContext basic}
+ * {@link ExecutionContext}s.
+ *
+ * @author Randall Hauch
+ */
+public class BasicExecutionContextFactory implements ExecutionContextFactory {
+
+ private final NamespaceRegistry defaultNamespaces = new BasicNamespaceRegistry();
+
+ /**
+ * Create a new instance of this factory.
+ */
+ public BasicExecutionContextFactory() {
+ defaultNamespaces.register("jcr", "http://www.jcp.org/jcr/1.0");
+ defaultNamespaces.register("mix", "http://www.jcp.org/jcr/mix/1.0");
+ defaultNamespaces.register("nt", "http://www.jcp.org/jcr/nt/1.0");
+ defaultNamespaces.register("dna", "http://www.jboss.org/dna");
+ defaultNamespaces.register("dnadtd", "http://www.jboss.org/dna/dtd/1.0");
+ defaultNamespaces.register("dnaxml", "http://www.jboss.org/dna/xml/1.0");
+ }
+
+ /**
+ * Create a new instance of this factory.
+ *
+ * @param defaultNamespaceUri the URI of the namespace that should be used with names that have no specified namespace prefix
+ * @throws IllegalArgumentException if the URI is null
+ */
+ public BasicExecutionContextFactory( String defaultNamespaceUri ) {
+ this();
+ defaultNamespaces.register("", defaultNamespaceUri);
+ }
+
+ /**
+ * @return defaultNamespaces
+ */
+ public NamespaceRegistry getDefaultNamespaces() {
+ return defaultNamespaces;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.ExecutionContextFactory#create()
+ */
+ public ExecutionContext create() {
+ ExecutionContext context = new BasicExecutionContext();
+ initialize(context);
+ return context;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.ExecutionContextFactory#create(java.security.AccessControlContext)
+ */
+ public ExecutionContext create( AccessControlContext accessControlContext ) {
+ ExecutionContext context = new BasicExecutionContext(accessControlContext);
+ initialize(context);
+ return context;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.ExecutionContextFactory#create(javax.security.auth.login.LoginContext)
+ */
+ public ExecutionContext create( LoginContext loginContext ) {
+ ExecutionContext context = new BasicExecutionContext(loginContext);
+ initialize(context);
+ return context;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.ExecutionContextFactory#create(java.lang.String)
+ */
+ public ExecutionContext create( String name ) throws LoginException {
+ LoginContext loginContext = new LoginContext(name);
+ ExecutionContext context = new BasicExecutionContext(loginContext);
+ initialize(context);
+ return context;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.ExecutionContextFactory#create(java.lang.String, javax.security.auth.Subject)
+ */
+ public ExecutionContext create( String name,
+ Subject subject ) throws LoginException {
+ LoginContext loginContext = new LoginContext(name, subject);
+ ExecutionContext context = new BasicExecutionContext(loginContext);
+ initialize(context);
+ return context;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.ExecutionContextFactory#create(java.lang.String, javax.security.auth.callback.CallbackHandler)
+ */
+ public ExecutionContext create( String name,
+ CallbackHandler callbackHandler ) throws LoginException {
+ LoginContext loginContext = new LoginContext(name, callbackHandler);
+ ExecutionContext context = new BasicExecutionContext(loginContext);
+ initialize(context);
+ return context;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.ExecutionContextFactory#create(java.lang.String, javax.security.auth.Subject,
+ * javax.security.auth.callback.CallbackHandler)
+ */
+ public ExecutionContext create( String name,
+ Subject subject,
+ CallbackHandler callbackHandler ) throws LoginException {
+ LoginContext loginContext = new LoginContext(name, subject, callbackHandler);
+ ExecutionContext context = new BasicExecutionContext(loginContext);
+ initialize(context);
+ return context;
+ }
+
+ protected synchronized void initialize( ExecutionContext context ) {
+ for (String uri : this.defaultNamespaces.getRegisteredNamespaceUris()) {
+ String prefix = this.defaultNamespaces.getPrefixForNamespaceUri(uri, false);
+ context.getNamespaceRegistry().register(prefix, uri);
+ }
+ }
+}
Property changes on: trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/BasicExecutionContextFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryConnectionPool.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryConnectionPool.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/connector/RepositoryConnectionPool.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -638,19 +638,22 @@
*/
public boolean awaitTermination( long timeout,
TimeUnit unit ) throws InterruptedException {
+ this.logger.trace("Awaiting termination");
long nanos = unit.toNanos(timeout);
final ReentrantLock mainLock = this.mainLock;
try {
mainLock.lock();
for (;;) {
- // this.logger.debug("---> Run state = {}; condition = {}", runState, termination);
+ // this.logger.trace("---> Run state = {0}; condition = {1}, {2} open", runState, termination, poolSize);
if (runState == TERMINATED) return true;
if (nanos <= 0) return false;
nanos = termination.awaitNanos(nanos);
- // this.logger.debug("---> Done waiting: run state = {}; condition = {}", runState, termination);
+ //this.logger.trace("---> Done waiting: run state = {0}; condition = {1}, {2} open",runState,termination,poolSize)
+ // ;
}
} finally {
mainLock.unlock();
+ this.logger.trace("Finished awaiting termination");
}
}
@@ -798,7 +801,7 @@
}
// Close the connection if we're supposed to (do it outside of the main lock)...
if (wrapperToClose != null) {
- closeConnection(wrapper);
+ closeConnection(wrapperToClose);
}
}
@@ -853,7 +856,7 @@
RepositoryConnection original = wrapper.getOriginal();
assert original != null;
try {
- this.logger.debug("Closing repository connection to {0}", getSourceName());
+ this.logger.debug("Closing repository connection to {0} ({1} open connections remain)", getSourceName(), poolSize);
original.close();
} finally {
final ReentrantLock mainLock = this.mainLock;
@@ -862,7 +865,7 @@
// No matter what reduce the pool size count
--this.poolSize;
// And if shutting down and this was the last connection being used...
- if (this.runState == SHUTDOWN && this.poolSize <= 0) {
+ if ((runState == SHUTDOWN || runState == STOP) && this.poolSize <= 0) {
// then signal anybody that has called "awaitTermination(...)"
this.logger.trace("Signalling termination of repository connection pool for {0}", getSourceName());
this.runState = TERMINATED;
@@ -890,7 +893,7 @@
}
int numClosed = extraConnections.size();
this.poolSize -= numClosed;
- this.logger.trace("Drained {0} unused connections", numClosed);
+ this.logger.trace("Drained {0} unused connections ({1} open connections remain)", numClosed, poolSize);
return numClosed;
}
Modified: trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicName.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicName.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicName.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -31,125 +31,125 @@
/**
* A basic implementation of {@link Name}.
- *
+ *
* @author Randall Hauch
* @author John Verhaeg
*/
@Immutable
public class BasicName implements Name {
- /**
+ /**
*/
private static final long serialVersionUID = -1737537720336990144L;
private final String namespaceUri;
- private final String localName;
- private final int hc;
+ private final String localName;
+ private final int hc;
- public BasicName( String namespaceUri,
- String localName ) {
- ArgCheck.isNotEmpty(localName, "localName");
- this.namespaceUri = namespaceUri != null ? namespaceUri.trim() : "";
- this.localName = localName != null ? localName.trim() : "";
- this.hc = HashCode.compute(this.namespaceUri, this.localName);
- }
+ public BasicName( String namespaceUri,
+ String localName ) {
+ ArgCheck.isNotEmpty(localName, "localName");
+ this.namespaceUri = namespaceUri != null ? namespaceUri.trim() : "";
+ this.localName = localName != null ? localName.trim() : "";
+ this.hc = HashCode.compute(this.namespaceUri, this.localName);
+ }
- /**
- * {@inheritDoc}
- */
- public String getLocalName() {
- return this.localName;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public String getLocalName() {
+ return this.localName;
+ }
- /**
- * {@inheritDoc}
- */
- public String getNamespaceUri() {
- return this.namespaceUri;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public String getNamespaceUri() {
+ return this.namespaceUri;
+ }
- /**
- * {@inheritDoc}
- */
- public String getString() {
- return getString(Path.DEFAULT_ENCODER);
- }
+ /**
+ * {@inheritDoc}
+ */
+ public String getString() {
+ return getString(Path.DEFAULT_ENCODER);
+ }
- /**
- * {@inheritDoc}
- */
- public String getString( TextEncoder encoder ) {
- if (this.getNamespaceUri().length() == 0) {
- if (this.getLocalName().equals(Path.SELF)) return Path.SELF;
- if (this.getLocalName().equals(Path.PARENT)) return Path.PARENT;
- }
- if (encoder == null) encoder = Path.DEFAULT_ENCODER;
- return "{" + encoder.encode(this.namespaceUri) + "}" + encoder.encode(this.localName);
- }
+ /**
+ * {@inheritDoc}
+ */
+ public String getString( TextEncoder encoder ) {
+ if (this.getNamespaceUri().length() == 0) {
+ if (this.getLocalName().equals(Path.SELF)) return Path.SELF;
+ if (this.getLocalName().equals(Path.PARENT)) return Path.PARENT;
+ }
+ if (encoder == null) encoder = Path.DEFAULT_ENCODER;
+ return "{" + encoder.encode(this.namespaceUri) + "}" + encoder.encode(this.localName);
+ }
- /**
- * {@inheritDoc}
- */
- public String getString( NamespaceRegistry namespaceRegistry ) {
- ArgCheck.isNotNull(namespaceRegistry, "namespaceRegistry");
- String prefix = namespaceRegistry.getPrefixForNamespaceUri(this.namespaceUri, true);
- if (prefix != null) {
- return prefix + ":" + this.localName;
- }
- return this.localName;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public String getString( NamespaceRegistry namespaceRegistry ) {
+ ArgCheck.isNotNull(namespaceRegistry, "namespaceRegistry");
+ String prefix = namespaceRegistry.getPrefixForNamespaceUri(this.namespaceUri, true);
+ if (prefix != null && prefix.length() != 0) {
+ return prefix + ":" + this.localName;
+ }
+ return this.localName;
+ }
- /**
- * {@inheritDoc}
- */
- public String getString( NamespaceRegistry namespaceRegistry,
- TextEncoder encoder ) {
- ArgCheck.isNotNull(namespaceRegistry, "namespaceRegistry");
- String prefix = namespaceRegistry.getPrefixForNamespaceUri(this.namespaceUri, true);
- if (prefix != null && prefix.length() != 0) {
- return encoder.encode(prefix) + ":" + encoder.encode(this.localName);
- }
- return this.localName;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public String getString( NamespaceRegistry namespaceRegistry,
+ TextEncoder encoder ) {
+ ArgCheck.isNotNull(namespaceRegistry, "namespaceRegistry");
+ String prefix = namespaceRegistry.getPrefixForNamespaceUri(this.namespaceUri, true);
+ if (prefix != null && prefix.length() != 0) {
+ return encoder.encode(prefix) + ":" + encoder.encode(this.localName);
+ }
+ return this.localName;
+ }
- /**
- * {@inheritDoc}
- */
- public int compareTo( Name that ) {
- if (that == this) return 0;
- int diff = this.getNamespaceUri().compareTo(that.getNamespaceUri());
- if (diff != 0) return diff;
- diff = this.getLocalName().compareTo(that.getLocalName());
- return diff;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public int compareTo( Name that ) {
+ if (that == this) return 0;
+ int diff = this.getNamespaceUri().compareTo(that.getNamespaceUri());
+ if (diff != 0) return diff;
+ diff = this.getLocalName().compareTo(that.getLocalName());
+ return diff;
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public int hashCode() {
- return this.hc;
- }
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode() {
+ return this.hc;
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean equals( Object obj ) {
- if (obj == this) return true;
- if (obj instanceof Name) {
- Name that = (Name)obj;
- if (!this.getNamespaceUri().equals(that.getNamespaceUri())) return false;
- return this.getLocalName().equals(that.getLocalName());
- }
- return false;
- }
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals( Object obj ) {
+ if (obj == this) return true;
+ if (obj instanceof Name) {
+ Name that = (Name)obj;
+ if (!this.getNamespaceUri().equals(that.getNamespaceUri())) return false;
+ return this.getLocalName().equals(that.getLocalName());
+ }
+ return false;
+ }
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- return "{" + this.namespaceUri + "}" + this.localName;
- }
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public String toString() {
+ return "{" + this.namespaceUri + "}" + this.localName;
+ }
}
Modified: trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicNamespaceRegistry.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicNamespaceRegistry.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicNamespaceRegistry.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -109,7 +109,8 @@
/**
* {@inheritDoc}
*/
- public String getPrefixForNamespaceUri( String namespaceUri, boolean generateIfMissing ) {
+ public String getPrefixForNamespaceUri( String namespaceUri,
+ boolean generateIfMissing ) {
ArgCheck.isNotNull(namespaceUri, "namespaceUri");
String prefix = null;
Lock lock = this.registryLock.readLock();
@@ -169,7 +170,8 @@
/**
* {@inheritDoc}
*/
- public String register( String prefix, String namespaceUri ) {
+ public String register( String prefix,
+ String namespaceUri ) {
ArgCheck.isNotNull(namespaceUri, "namespaceUri");
String previousNamespaceForPrefix = null;
namespaceUri = namespaceUri.trim();
@@ -180,9 +182,12 @@
prefix = prefix.trim();
previousNamespaceForPrefix = this.namespacesByPrefix.put(prefix, namespaceUri);
String previousPrefix = this.prefixesByNamespace.put(namespaceUri, prefix);
- if (previousPrefix != null) {
+ if (previousPrefix != null && !previousPrefix.equals(prefix)) {
this.namespacesByPrefix.remove(previousPrefix);
}
+ if (previousNamespaceForPrefix != null && !previousNamespaceForPrefix.equals(namespaceUri)) {
+ this.prefixesByNamespace.remove(previousNamespaceForPrefix);
+ }
} finally {
lock.unlock();
}
Modified: trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicNameTest.java
===================================================================
--- trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicNameTest.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicNameTest.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -155,4 +155,18 @@
assertThat(result, is("dna:some%3aname%3awith%3acolons"));
}
+ @Test
+ public void shouldNotIncludeNamespacePrefixOrColonInResultFromGetStringWithNamespaceRegistry() {
+ validNamespaceUri = namespaceRegistry.getDefaultNamespaceUri();
+ name = new BasicName(validNamespaceUri, validLocalName);
+ String result = name.getString(namespaceRegistry, encoder);
+ assertThat(result, is(validLocalName));
+ result = name.getString(namespaceRegistry); // default encoder
+ assertThat(result, is(validLocalName));
+
+ validLocalName = "some:name:with:colons";
+ name = new BasicName(validNamespaceUri, validLocalName);
+ result = name.getString(namespaceRegistry, encoder);
+ assertThat(result, is("some:name:with:colons"));
+ }
}
Modified: trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicNamespaceRegistryTest.java
===================================================================
--- trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicNamespaceRegistryTest.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicNamespaceRegistryTest.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -25,6 +25,7 @@
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
+import static org.junit.matchers.JUnitMatchers.hasItem;
import org.junit.Before;
import org.junit.Test;
@@ -122,6 +123,9 @@
namespaceRegistry.register(validPrefix1, validNamespaceUri1);
namespaceRegistry.register("", validNamespaceUri2);
assertThat(namespaceRegistry.getDefaultNamespaceUri(), is(validNamespaceUri2));
+ assertThat(namespaceRegistry.getNamespaceForPrefix(""), is(validNamespaceUri2));
+ assertThat(namespaceRegistry.getRegisteredNamespaceUris(), hasItem(validNamespaceUri2));
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri2, false), is(""));
}
@Test
@@ -144,4 +148,36 @@
assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri2), is(true));
}
+ @Test
+ public void shouldBeAbleToCopyNamespacesToAnotherRegistry() {
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ namespaceRegistry.register("", validNamespaceUri3);
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri1), is(true));
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri2), is(true));
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri3), is(true));
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri1, false), is(validPrefix1));
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri2, false), is(validPrefix2));
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, false), is(""));
+ assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix1), is(validNamespaceUri1));
+ assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix2), is(validNamespaceUri2));
+ assertThat(namespaceRegistry.getNamespaceForPrefix(""), is(validNamespaceUri3));
+
+ BasicNamespaceRegistry newRegistry = new BasicNamespaceRegistry();
+ for (String uri : this.namespaceRegistry.getRegisteredNamespaceUris()) {
+ String prefix = this.namespaceRegistry.getPrefixForNamespaceUri(uri, false);
+ newRegistry.register(prefix, uri);
+ }
+ assertThat(newRegistry.isRegisteredNamespaceUri(validNamespaceUri1), is(true));
+ assertThat(newRegistry.isRegisteredNamespaceUri(validNamespaceUri2), is(true));
+ assertThat(newRegistry.isRegisteredNamespaceUri(validNamespaceUri3), is(true));
+ assertThat(newRegistry.getPrefixForNamespaceUri(validNamespaceUri1, false), is(validPrefix1));
+ assertThat(newRegistry.getPrefixForNamespaceUri(validNamespaceUri2, false), is(validPrefix2));
+ assertThat(newRegistry.getPrefixForNamespaceUri(validNamespaceUri3, false), is(""));
+ assertThat(newRegistry.getNamespaceForPrefix(validPrefix1), is(validNamespaceUri1));
+ assertThat(newRegistry.getNamespaceForPrefix(validPrefix2), is(validNamespaceUri2));
+ assertThat(newRegistry.getNamespaceForPrefix(""), is(validNamespaceUri3));
+
+ }
+
}
Modified: trunk/docs/examples/gettingstarted/repositories/pom.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/pom.xml 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/docs/examples/gettingstarted/repositories/pom.xml 2008-09-11 23:33:03 UTC (rev 515)
@@ -50,6 +50,12 @@
<version>${dna-version}</version>
<scope>runtime</scope>
</dependency>
+ <dependency>
+ <groupId>org.jboss.dna</groupId>
+ <artifactId>dna-connector-federation</artifactId>
+ <version>${dna-version}</version>
+ <scope>runtime</scope>
+ </dependency>
<!--
Logging (require SLF4J API for compiling, but use Log4J and its SLF4J binding for testing)
-->
@@ -80,6 +86,11 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
Modified: trunk/docs/examples/gettingstarted/repositories/src/main/assembly/basic.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/assembly/basic.xml 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/assembly/basic.xml 2008-09-11 23:33:03 UTC (rev 515)
@@ -16,7 +16,7 @@
<directory>src/main/resources/</directory>
<outputDirectory/>
<includes>
- <include>*.*</include>
+ <include>*.xml</include>
</includes>
</fileSet>
</fileSets>
Added: trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -0,0 +1,243 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.example.dna.repository;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.jboss.dna.common.util.StringUtil;
+
+/**
+ * @author Randall Hauch
+ */
+public class ConsoleInput implements UserInterface {
+
+ protected static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
+
+ private final RepositoryClient repositoryClient;
+ private final Map<Integer, String> selectionToSourceName = new HashMap<Integer, String>();
+
+ public ConsoleInput( final RepositoryClient client,
+ final String[] args ) {
+ this.repositoryClient = client;
+ try {
+ System.out.println();
+ System.out.print("Starting repositories ... ");
+ client.startRepositories();
+ System.out.println("done.");
+ System.out.println();
+
+ System.out.println(getMenu());
+ Thread eventThread = new Thread(new Runnable() {
+
+ private boolean quit = false;
+
+ @SuppressWarnings( "synthetic-access" )
+ public void run() {
+ try {
+ while (!quit) {
+ System.out.print(">");
+ try {
+ String input = in.readLine();
+ if (input.length() != 1) {
+ System.out.println("Please enter a valid option.");
+ continue;
+ }
+
+ char option = input.charAt(0);
+ switch (option) {
+ case '?':
+ case 'h':
+ System.out.println(getMenu());
+ break;
+ case 'q':
+ quit = true;
+ break;
+ default:
+ try {
+ int selection = Integer.parseInt("" + option);
+ String sourceName = selectionToSourceName.get(selection);
+ navigate(sourceName);
+ } catch (NumberFormatException e) {
+ System.out.println("Invalid option.");
+ break;
+ }
+ }
+ } catch (NumberFormatException e) {
+ System.out.println("Invalid integer " + e.getMessage());
+ } catch (IllegalArgumentException e) {
+ System.out.println(e.getMessage());
+ } catch (IOException e) {
+ e.printStackTrace();
+ } catch (Throwable e) {
+ e.printStackTrace();
+ }
+ }
+ } finally {
+ try {
+ // Terminate ...
+ System.out.println();
+ System.out.print("done.\nShutting down repositories and services ... ");
+ client.shutdown();
+ System.out.print("done.");
+ System.out.println();
+ System.out.println();
+ } catch (Exception err) {
+ System.out.println("Error shutting down sequencing service and repository: "
+ + err.getLocalizedMessage());
+ err.printStackTrace(System.err);
+ }
+ }
+ }
+ });
+
+ eventThread.start();
+ } catch (Exception err) {
+ System.out.println("Error: " + err.getLocalizedMessage());
+ err.printStackTrace(System.err);
+ }
+ }
+
+ protected String getMenu() {
+ selectionToSourceName.clear();
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("-----------------------------------\n");
+ buffer.append("Menu:\n");
+ buffer.append("\n");
+ buffer.append(" Select a repository to view:\n");
+ int selection = 1;
+ for (String sourceName : this.repositoryClient.getNamesOfRepositories()) {
+ selectionToSourceName.put(selection, sourceName);
+ buffer.append(" " + selection + ") " + sourceName + "\n");
+ }
+ buffer.append(" or\n");
+ buffer.append(" ?) Show this menu\n");
+ buffer.append(" q) Quit");
+ return buffer.toString();
+ }
+
+ protected void navigate( String sourceName ) {
+ String currentPath = "/";
+ while (true) {
+
+ // Ask for the command ...
+ System.out.print("> ");
+ try {
+ String input = in.readLine().trim();
+ if (input.length() == 0) {
+ continue;
+ }
+
+ if ("?".equals(input) || "help".equals(input) || "h".equals(input)) {
+ System.out.println(" Enter a command:");
+ System.out.println(" pwd print the current node's path");
+ System.out.println(" ls [path] to list the details of the node at the specified absolute or relative path");
+ System.out.println(" (or the current path if none is supplied)");
+ System.out.println(" cd path to change to the node at the specified absolute or relative path");
+ System.out.println(" exit to exit this repository and return to the main menu");
+ System.out.println(" and press return:");
+ } else if ("pwd".equals(input)) {
+ System.out.println(" " + currentPath);
+ } else if ("exit".equals(input)) {
+ return;
+ } else if (input.startsWith("ls")) {
+ input = input.substring("ls".length()).trim();
+ String path = currentPath;
+ if (input.length() != 0) path = input;
+ displayNode(sourceName, path);
+ } else if (input.startsWith("cd ")) {
+ input = input.substring("cd ".length()).trim();
+ if (input.length() == 0) continue;
+ // Check to see if the new path exists ...
+ if (!repositoryClient.getNodeInfo(sourceName, input, null, null)) {
+ System.out.println(" \"" + input + "\" does not exist");
+ } else {
+ currentPath = input;
+ }
+ }
+ } catch (Throwable e) {
+ displayError(" processing your command", e);
+ }
+ }
+
+ }
+
+ protected void displayNode( String sourceName,
+ String path ) {
+ Map<String, Object[]> properties = new HashMap<String, Object[]>();
+ List<String> children = new ArrayList<String>();
+ try {
+ repositoryClient.getNodeInfo(sourceName, path, properties, children);
+ } catch (Throwable t) {
+ displayError(" displaying node \"" + path + "\"", t);
+ }
+
+ System.out.println(" Path:" + path);
+ System.out.println(" Properties:");
+ int maxLength = 0;
+ for (String propertyName : properties.keySet()) {
+ maxLength = Math.max(maxLength, propertyName.length());
+ }
+ for (Map.Entry<String, Object[]> property : properties.entrySet()) {
+ String name = property.getKey();
+ name = StringUtil.justifyLeft(name, maxLength, ' ');
+ Object[] values = property.getValue();
+ String valueStr = StringUtil.readableString(values);
+ if (values.length == 1) StringUtil.readableString(values[0]);
+ System.out.println(" " + name + " = " + valueStr);
+ }
+ System.out.println(" Children:");
+ for (String childName : children) {
+ System.out.println(" " + childName);
+ }
+ System.out.println();
+ }
+
+ protected void displayError( String activity,
+ Throwable t ) {
+ System.err.println();
+ System.err.println("There has been an error" + activity);
+ System.err.println(" " + t.getMessage());
+ t.printStackTrace(System.err);
+ System.err.println();
+ System.err.println("Press any key to continue:");
+ try {
+ in.readLine();
+ } catch (IOException err) {
+ err.printStackTrace(System.err);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.example.dna.repository.UserInterface#getLocationOfRepositoryFiles()
+ */
+ public String getLocationOfRepositoryFiles() {
+ return new File("").getAbsolutePath();
+ }
+}
Property changes on: trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -21,17 +21,284 @@
*/
package org.jboss.example.dna.repository;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import javax.jcr.Credentials;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.PropertyIterator;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.security.auth.callback.PasswordCallback;
+import org.jboss.dna.common.component.ClassLoaderFactory;
+import org.jboss.dna.common.component.StandardClassLoaderFactory;
+import org.jboss.dna.connector.inmemory.InMemoryRepositorySource;
+import org.jboss.dna.jcr.JcrRepository;
+import org.jboss.dna.repository.RepositoryImporter;
+import org.jboss.dna.repository.RepositoryService;
+import org.jboss.dna.repository.RepositorySourceManager;
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.ExecutionContextFactory;
+import org.jboss.dna.spi.connector.BasicExecutionContextFactory;
+import org.jboss.dna.spi.connector.RepositoryConnection;
+import org.jboss.dna.spi.graph.Path;
+import org.jboss.dna.spi.graph.PathFactory;
+import org.jboss.dna.spi.graph.PathNotFoundException;
+import org.jboss.dna.spi.graph.Property;
+import org.jboss.dna.spi.graph.commands.impl.BasicGetNodeCommand;
+
/**
- *
* @author Randall Hauch
*/
public class RepositoryClient {
+ public static final String INMEMORY_REPOSITORY_SOURCE_CLASSNAME = "org.jboss.dna.connector.inmemory.InMemoryRepositorySource";
+ public static final String JAAS_LOGIN_CONTEXT_NAME = "dna-repository-example";
+
/**
* @param args
*/
public static void main( String[] args ) {
+ RepositoryClient client = new RepositoryClient();
+ for (String arg : args) {
+ arg = arg.trim();
+ if (arg.equals("--api=jcr")) client.setApi(Api.JCR);
+ if (arg.equals("--api=dna")) client.setApi(Api.DNA);
+ if (arg.startsWith("--user=") && arg.length() > 7) client.setUsername(arg.substring(7).trim());
+ }
+ client.setUserInterface(new ConsoleInput(client, args));
+ }
+ public enum Api {
+ JCR,
+ DNA;
}
+ private ClassLoaderFactory classLoaderFactory;
+ private RepositorySourceManager sources;
+ private ExecutionContextFactory contextFactory;
+ private RepositoryService repositoryService;
+ private Api api = Api.DNA;
+ private String username = null;
+ private char[] password = null;
+ private UserInterface userInterface;
+
+ /**
+ * @param userInterface Sets userInterface to the specified value.
+ */
+ public void setUserInterface( UserInterface userInterface ) {
+ this.userInterface = userInterface;
+ }
+
+ /**
+ * Set the API that this client should use to interact with the repositories.
+ *
+ * @param api The API that should be used
+ */
+ public void setApi( Api api ) {
+ this.api = api != null ? api : Api.DNA;
+ }
+
+ /**
+ * Set the username that this client should use.
+ *
+ * @param username the new username, or null if no username should be used.
+ */
+ public void setUsername( String username ) {
+ this.username = username;
+ this.password = null;
+ }
+
+ /**
+ * Clear any cached password.
+ */
+ public void clearPassword() {
+ password = null;
+ }
+
+ /**
+ * Method used internally to obtain the password, which is obtained from the user (only once per process) if needed
+ *
+ * @return the user's password, or null if no username is known
+ */
+ private char[] getPassword() {
+ if (username == null) return null;
+ if (password == null) {
+ PasswordCallback callback = new PasswordCallback("Password:", false);
+ password = callback.getPassword();
+ }
+ return password;
+ }
+
+ /**
+ * Start up the repositories. This method creates the necessary components and services, and initializes the in-memory
+ * repositories.
+ *
+ * @throws IOException if there is a problem initializing the repositories from the files.
+ */
+ public void startRepositories() throws IOException {
+ if (repositoryService != null) return; // already started
+
+ // Create the class loader factory, which for this example will simply use this class' class loader...
+ classLoaderFactory = new StandardClassLoaderFactory();
+
+ // Create the factory for execution contexts.
+ contextFactory = new BasicExecutionContextFactory();
+
+ // Create the execution context that we'll use for the services. If we'd want to use JAAS, we'd create the context
+ // by supply LoginContext, AccessControlContext, or even Subject with CallbackHandlers. But no JAAS in this example.
+ ExecutionContext context = contextFactory.create();
+
+ // Create the manager for the RepositorySource instances ...
+ sources = new RepositorySourceManager();
+
+ // Load into the source manager the repository source for the configuration repository ...
+ InMemoryRepositorySource configSource = new InMemoryRepositorySource();
+ configSource.setName("Configuration");
+ sources.addSource(configSource);
+
+ // For this example, we're using a couple of in-memory repositories (including one for the configuration repository).
+ // Normally, these would exist already and would simply be accessed. But in this example, we're going to
+ // populate these repositories here by importing from files. First do the configuration repository ...
+ String location = this.userInterface.getLocationOfRepositoryFiles();
+ RepositoryImporter importer = new RepositoryImporter(sources, context);
+ importer.importXml(location + "/configRepository.xml").into(configSource.getName());
+
+ // Now instantiate the Repository Service ...
+ repositoryService = new RepositoryService(sources, configSource.getName(), context, classLoaderFactory);
+ repositoryService.getAdministrator().start();
+
+ // Now import the conten for two of the other in-memory repositories ...
+ importer.importXml(location + "/cars.xml").into("Cars");
+ importer.importXml(location + "/aircraft.xml").into("Aircraft");
+ }
+
+ /**
+ * Get the names of the repositories.
+ *
+ * @return the repository names
+ */
+ public Collection<String> getNamesOfRepositories() {
+ return sources.getSourceNames();
+ }
+
+ /**
+ * Shut down the components and services and blocking until all resources have been released.
+ *
+ * @throws InterruptedException if the thread was interrupted before completing the shutdown.
+ */
+ public void shutdown() throws InterruptedException {
+ if (repositoryService == null) return;
+ try {
+ // Shut down the various services ...
+ repositoryService.getAdministrator().shutdown();
+
+ // Shut down the manager of the RepositorySource instances, waiting until all connections are closed
+ sources.getAdministrator().shutdown();
+ sources.getAdministrator().awaitTermination(1, TimeUnit.SECONDS);
+ } finally {
+ repositoryService = null;
+ sources = null;
+ }
+ }
+
+ /**
+ * Get the information about a node, using the {@link #setApi(Api) API} method.
+ *
+ * @param sourceName the name of the repository source
+ * @param pathToNode the path to the node in the repository that is to be retrieved
+ * @param properties the map into which the property values will be placed; may be null if the properties are not to be
+ * retrieved
+ * @param children the collection into which the child names should be placed; may be null if the children are not to be
+ * retrieved
+ * @return true if the node was found, or false if it was not
+ * @throws Throwable
+ */
+ public boolean getNodeInfo( String sourceName,
+ String pathToNode,
+ Map<String, Object[]> properties,
+ List<String> children ) throws Throwable {
+ switch (api) {
+ case JCR: {
+ JcrRepository jcrRepository = new JcrRepository(contextFactory, sources);
+ Session session = null;
+ if (username != null) {
+ Credentials credentials = new SimpleCredentials(username, getPassword());
+ session = jcrRepository.login(credentials, sourceName);
+ } else {
+ session = jcrRepository.login(sourceName);
+ }
+ try {
+ // Get the node by path ...
+ Node root = session.getRootNode();
+ Node node = root.getNode(pathToNode);
+
+ // Now populate the properties and children ...
+ if (properties != null) {
+ for (PropertyIterator iter = node.getProperties(); iter.hasNext();) {
+ javax.jcr.Property property = iter.nextProperty();
+ properties.put(property.getName(), property.getValues());
+ }
+ }
+ if (children != null) {
+ for (NodeIterator iter = node.getNodes(); iter.hasNext();) {
+ javax.jcr.Node child = iter.nextNode();
+ children.add(child.getName());
+ }
+ }
+ } catch (javax.jcr.PathNotFoundException e) {
+ return false;
+ } finally {
+ if (session != null) session.logout();
+ }
+ break;
+ }
+ case DNA: {
+ ExecutionContext context = null;
+ if (username != null) {
+ context = contextFactory.create(JAAS_LOGIN_CONTEXT_NAME);
+ } else {
+ context = contextFactory.create();
+ }
+ PathFactory pathFactory = context.getValueFactories().getPathFactory();
+
+ // Get the node submitting a graph command to a repository connection.
+ // (Using commands is a little verbose, but we'll be introducing in the next release
+ // an API that is much easier and concise.)
+ Path path = pathToNode != null ? pathFactory.create(pathToNode) : pathFactory.createRootPath();
+ BasicGetNodeCommand command = new BasicGetNodeCommand(path);
+ RepositoryConnection connection = sources.createConnection(sourceName);
+ try {
+ connection.execute(context, command);
+ } finally {
+ if (connection != null) connection.close();
+ }
+
+ // Check whether there's been an error ...
+ if (command.hasError()) {
+ if (command.getError() instanceof PathNotFoundException) return false;
+ throw command.getError();
+ }
+
+ // Now populate the properties and children ...
+ if (properties != null) {
+ for (Property property : command.getProperties()) {
+ String name = property.getName().getString(context.getNamespaceRegistry());
+ properties.put(name, property.getValuesAsArray());
+ }
+ }
+ if (children != null) {
+ for (Path.Segment child : command.getChildren()) {
+ String name = child.getString(context.getNamespaceRegistry());
+ children.add(name);
+ }
+ }
+ break;
+ }
+ }
+ return true;
+ }
}
Added: trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/UserInterface.java
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/UserInterface.java (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/UserInterface.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -0,0 +1,31 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.example.dna.repository;
+
+/**
+ * @author Randall Hauch
+ */
+public interface UserInterface {
+
+ String getLocationOfRepositoryFiles();
+
+}
Property changes on: trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/UserInterface.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml 2008-09-11 23:33:03 UTC (rev 515)
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ JBoss, Home of Professional Open Source.
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+<Aircraft xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <Business>
+ <aircraft jcr:name="Gulfstream V" maker="Gulfstream" model="G-V" introduced="1995" range="5800nm" cruiseSpeed="488kt" crew="2" emptyWeight="46200lb" url="http://en.wikipedia.org/wiki/Gulfstream_V"/>
+ <aircraft jcr:name="Learjet 45" maker="Learjet" model="LJ45" introduced="1995" numberBuilt="264+" crew="2" emptyWeight="13695lb" range="2120nm" cruiseSpeed="457kt" url="http://en.wikipedia.org/wiki/Learjet_45"/>
+ </Business>
+ <Commercial>
+ <aircraft jcr:name="Boeing 777" maker="Boeing" model="777-200LR" introduced="1995" numberBuilt="731+" maxRange="7500nm" emptyWeight="326000lb" cruiseSpeed="560mph" url="http://en.wikipedia.org/wiki/Boeing_777"/>
+ <aircraft jcr:name="Boeing 767" maker="Boeing" model="767-200" introduced="1982" numberBuilt="966+" maxRange="3950nm" emptyWeight="176650lb" cruiseSpeed="530mph" url="http://en.wikipedia.org/wiki/Boeing_767"/>
+ <aircraft jcr:name="Boeing 787" maker="Boeing" model="787-3" introduced="2009" range="3050nm" emptyWeight="223000lb" cruiseSpeed="561mph" url="http://en.wikipedia.org/wiki/Boeing_787"/>
+ <aircraft jcr:name="Boeing 757" maker="Boeing" model="757-200" introduced="1983" numberBuilt="1050" range="3900nm" maxWeight="255000lb" cruiseSpeed="530mph" url="http://en.wikipedia.org/wiki/Boeing_757"/>
+ <aircraft jcr:name="Airbus A380" maker="Airbus" model="A380-800" introduced="2007" numberBuilt="18" range="8200nm" maxWeight="1235000lb" cruiseSpeed="647mph" url="http://en.wikipedia.org/wiki/Airbus_a380"/>
+ <aircraft jcr:name="Airbus A340" maker="Airbus" model="A340-200" introduced="1993" numberBuilt="354" range="8000nm" maxWeight="606300lb" cruiseSpeed="557mph" url="http://en.wikipedia.org/wiki/Airbus_A-340"/>
+ <aircraft jcr:name="Airbus A310" maker="Airbus" model="A310-200" introduced="1983" numberBuilt="255" cruiseSpeed="850km/h" emptyWeight="176312lb" range="3670nm" url="http://en.wikipedia.org/wiki/Airbus_A-310"/>
+ <aircraft jcr:name="Embraer " maker="Embraer" model="ERJ170-200" introduced="2004" range="3334km" cruiseSpeed="481kt" emptyWeight="21810kg" url="http://en.wikipedia.org/wiki/EMBRAER_170"/>
+ </Commercial>
+ <Vintage>
+ <aircraft jcr:name="Fokker Trimotor" maker="Fokker" model="F.VII" introduced="1925" cruiseSpeed="170km/h" emptyWeight="3050kg" crew="2" url="http://en.wikipedia.org/wiki/Fokker_trimotor"/>
+ <aircraft jcr:name="P-38 Lightning" maker="Lockheed" model="P-38" designedBy="Kelly Johnson" introduced="1941" numberBuilt="10037" rateOfClimb="4750ft/min" range="1300mi" emptyWeight="12780lb" crew="1" url="http://en.wikipedia.org/wiki/P-38_Lightning"/>
+ <aircraft jcr:name="A6M Zero" maker="Mitsubishi" model="A6M" designedBy="Jiro Horikoshi" introduced="1940" numberBuilt="11000" crew="1" emptyWeight="3704lb" serviceCeiling="33000ft" maxSpeed="331mph" range="1929mi" rateOfClimb="3100ft/min" url="http://en.wikipedia.org/wiki/A6M_Zero"/>
+ <aircraft jcr:name="Bf 109" maker="Messerschmitt" model="Bf 109" introduced="1937" url="http://en.wikipedia.org/wiki/BF_109"/>
+ <aircraft jcr:name="Wright Flyer" maker="Wright Brothers" introduced="1903" range="852ft" maxSpeed="30mph" emptyWeight="605lb" crew="1"/>
+ </Vintage>
+ <Homebuilt>
+ <aircraft jcr:name="Long-EZ" maker="Rutan Aircraft Factory" model="61" emptyWeight="760lb" fuelCapacity="200L" maxSpeed="185kt" since="1976" range="1200nm" url="http://en.wikipedia.org/wiki/Rutan_Long-EZ"/>
+ <aircraft jcr:name="Cirrus VK-30" maker="Cirrus Design" model="VK-30" emptyWeight="2400lb" maxLoad="1200lb" maxSpeed="250mph" rateOfClimb="1500ft/min" range="1300mi" url="http://en.wikipedia.org/wiki/Cirrus_VK-30"/>
+ <aircraft jcr:name="Van's RV-4" maker="Van's Aircraft" model="RV-4" introduced="1980" emptyWeight="905lb" maxLoad="500lb" maxSpeed="200mph" rateOfClimb="2450ft/min" range="725mi" url="http://en.wikipedia.org/wiki/Van%27s_Aircraft_RV-4"/>
+ </Homebuilt>
+</Aircraft>
\ No newline at end of file
Property changes on: trunk/docs/examples/gettingstarted/repositories/src/main/resources/aircraft.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/docs/examples/gettingstarted/repositories/src/main/resources/cars.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/resources/cars.xml (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/resources/cars.xml 2008-09-11 23:33:03 UTC (rev 515)
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ JBoss, Home of Professional Open Source.
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+<Cars xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <Hybrid>
+ <car jcr:name="Toyota Prius" maker="Toyota" model="Prius" year="2008" msrp="$21,500" userRating="4.2" valueRating="5" mpgCity="48" mpgHighway="45"/>
+ <car jcr:name="Toyota Highlander" maker="Toyota" model="Highlander" year="2008" msrp="$34,200" userRating="4" valueRating="5" mpgCity="27" mpgHighway="25"/>
+ <car jcr:name="Nissan Altima" maker="Nissan" model="Altima" year="2008" msrp="$18,260" mpgCity="23" mpgHighway="32"/>
+ </Hybrid>
+ <Sports>
+ <car jcr:name="Aston Martin DB9" maker="Aston Martin" model="DB9" year="2008" msrp="$171,600" userRating="5" mpgCity="12" mpgHighway="19" lengthInInches="185.5" wheelbaseInInches="108.0" engine="5,935 cc 5.9 liters V 12"/>
+ <car jcr:name="Infiniti G37" maker="Infiniti" model="G37" year="2008" msrp="$34,900" userRating="3.5" valueRating="4" mpgCity="18" mpgHighway="24" />
+ </Sports>
+ <Luxury>
+ <car jcr:name="Cadillac DTS" maker="Cadillac" model="DTS" year="2008" engine="3.6-liter V6" userRating="0"/>
+ <car jcr:name="Bentley Continental" maker="Bentley" model="Continental" year="2008" msrp="$170,990" mpgCity="10" mpgHighway="17" />
+ <car jcr:name="Lexus IS350" maker="Lexus" model="IS350" year="2008" msrp="$36,305" mpgCity="18" mpgHighway="25" userRating="4" valueRating="5" />
+ </Luxury>
+ <Utility>
+ <car jcr:name="Land Rover LR2" maker="Land Rover" model="LR2" year="2008" msrp="$33,985" userRating="4.5" valueRating="5" mpgCity="16" mpgHighway="23" />
+ <car jcr:name="Land Rover LR3" maker="Land Rover" model="LR3" year="2008" msrp="$48,525" userRating="5" valueRating="2" mpgCity="12" mpgHighway="17" />
+ <car jcr:name="Hummer H3" maker="Hummer" model="H3" year="2008" msrp="$30,595" userRating="3.5" valueRating="4" mpgCity="13" mpgHighway="16" />
+ <car jcr:name="Ford F-150" maker="Ford" model="F-150" year="2008" msrp="$23,910" userRating="4" valueRating="1" mpgCity="14" mpgHighway="20" />
+ </Utility>
+</Cars>
\ No newline at end of file
Property changes on: trunk/docs/examples/gettingstarted/repositories/src/main/resources/cars.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml 2008-09-11 23:33:03 UTC (rev 515)
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ JBoss, Home of Professional Open Source.
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+<dna:system xmlns:dna="http://www.jboss.org/dna" xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <!-- Define the sources from which content is made available -->
+ <dna:sources>
+ <sourceA name="Cars" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" retryLimit="3" />
+ <sourceB name="Aircraft" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" />
+ <sourceC name="Vehicles" dna:classname="org.jboss.dna.connector.federation.FederatedRepositorySource" configurationSourceName="Configuration" configurationSourcePath="/dna:system/dna:federatedRepositories/Vehicles" />
+ <sourceD name="Cache" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" />
+ </dna:sources>
+ <dna:federatedRepositories>
+ <Vehicles>
+ <!-- This section defines from where the content of the 'Vehicles' federated repository is obtained -->
+ <dna:federation dna:timeToCache="100000">
+ <dna:cache>
+ <!-- Define how the content in the 'Cache' source is to map to the federated cache -->
+ <Cache dna:projectionRules="/ => /" />
+ </dna:cache>
+ <dna:projections>
+ <!-- Define how the content in the difference sources maps to the federated/unified repository.
+ This example puts the 'Cars' and 'Aircraft' content underneath '/vehicles', but the
+ 'Configuration' content (which is defined by this file) will appear under '/'. -->
+ <Cars dna:projectionRules="/vehicles => /" />
+ <Aircraft dna:projectionRules="/vehicles => /" />
+ <Configuration dna:projectionRules="/ => /" />
+ </dna:projections>
+ </dna:federation>
+ </Vehicles>
+ </dna:federatedRepositories>
+</dna:system>
\ No newline at end of file
Property changes on: trunk/docs/examples/gettingstarted/repositories/src/main/resources/configRepository.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties 2008-09-11 23:33:03 UTC (rev 515)
@@ -9,4 +9,9 @@
# Set up the default logging to be INFO level, then override specific units
log4j.logger.org.jboss.dna=INFO
+#log4j.logger.org.jboss.dna.repository.sequencers=TRACE
+#log4j.logger.org.jboss.dna.sequencer=DEBUG
+#log4j.logger.org.jboss.dna.connector=TRACE
+#log4j.logger.org.jboss.dna.spi.connector.RepositoryConnectionPool=TRACE
+#log4j.logger.org.jboss.dna.spi=DEBUG
Added: trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -0,0 +1,158 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.example.dna.repository;
+
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+import static org.junit.matchers.IsCollectionContaining.hasItems;
+import static org.mockito.Mockito.stub;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.jboss.dna.common.util.StringUtil;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoAnnotations.Mock;
+
+/**
+ * @author Randall Hauch
+ */
+public class RepositoryClientTest {
+
+ private RepositoryClient client;
+ private Map<String, Object[]> properties;
+ private List<String> children;
+ @Mock
+ private UserInterface userInterface;
+
+ @Before
+ public void beforeEach() {
+ MockitoAnnotations.initMocks(this);
+ properties = new HashMap<String, Object[]>();
+ children = new ArrayList<String>();
+ client = new RepositoryClient();
+ client.setUserInterface(userInterface);
+ stub(userInterface.getLocationOfRepositoryFiles()).toReturn(new File("src/main/resources").getAbsolutePath());
+ }
+
+ @After
+ public void afterEach() throws Exception {
+ client.shutdown();
+ }
+
+ protected void assertProperty( String propertyName,
+ Object... values ) {
+ Object[] actualValues = properties.get(propertyName);
+ assertThat(actualValues, is(values));
+ }
+
+ @Test
+ public void shouldStartupWithoutError() throws Exception {
+ client.startRepositories();
+ assertThat(client.getNamesOfRepositories(), hasItems("Aircraft", "Cars", "Configuration", "Vehicles", "Cache"));
+ }
+
+ @Test
+ public void shouldStartupWithoutErrorMoreThanOnce() throws Exception {
+ client.startRepositories();
+ assertThat(client.getNamesOfRepositories(), hasItems("Aircraft", "Cars", "Configuration", "Vehicles", "Cache"));
+ }
+
+ @Ignore
+ @Test
+ public void shouldHaveContentFromConfigurationRepository() throws Throwable {
+ client.startRepositories();
+ assertThat(client.getNodeInfo("Configuration", "/dna:system", properties, children), is(true));
+ assertThat(children, hasItems("dna:sources", "dna:federatedRepositories"));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertThat(properties.size(), is(2));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Configuration", "/dna:system/dna:sources", properties, children), is(true));
+ assertThat(children, hasItems("sourceA", "sourceB", "sourceC", "sourceD"));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertThat(properties.size(), is(2));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Configuration", "/dna:system/dna:sources/sourceA", properties, children), is(true));
+ assertThat(children.size(), is(0));
+ System.out.println(StringUtil.readableString(properties));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertProperty("dna:classname", "org.jboss.dna.connector.inmemory.InMemoryRepositorySource");
+ assertProperty("name", "Cars");
+ assertProperty("retryLimit", "3");
+ assertThat(properties.size(), is(4));
+ }
+
+ @Test
+ public void shouldLoadCarsRepository() throws Throwable {
+ client.startRepositories();
+ assertThat(client.getNodeInfo("Cars", "/Cars", properties, children), is(true));
+ assertThat(children, hasItems("Hybrid", "Sports", "Luxury", "Utility"));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertThat(properties.size(), is(2));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Cars", "/Cars/Hybrid", properties, children), is(true));
+ assertThat(children, hasItems("Toyota Prius", "Toyota Highlander", "Nissan Altima"));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertThat(properties.size(), is(2));
+
+ properties.clear();
+ children.clear();
+ assertThat(client.getNodeInfo("Cars", "/Cars/Sports/Aston Martin DB9", properties, children), is(true));
+ assertThat(children.size(), is(0));
+ assertThat(properties.containsKey("jcr:primaryType"), is(true));
+ assertThat(properties.containsKey("dna:uuid"), is(true));
+ assertProperty("maker", "Aston Martin");
+ assertProperty("maker", "Aston Martin");
+ assertProperty("model", "DB9");
+ assertProperty("year", "2008");
+ assertProperty("msrp", "$171,600");
+ assertProperty("userRating", "5");
+ assertProperty("mpgCity", "12");
+ assertProperty("mpgHighway", "19");
+ assertProperty("lengthInInches", "185.5");
+ assertProperty("wheelbaseInInches", "108.0");
+ assertProperty("engine", "5,935 cc 5.9 liters V 12");
+ assertThat(properties.size(), is(12));
+ }
+
+ @Test
+ public void shouldReturnNullForNonExistantNode() throws Throwable {
+ client.startRepositories();
+ assertThat(client.getNodeInfo("Cars", "/Cars/Sports/Non Existant Car", properties, children), is(false));
+ }
+}
Property changes on: trunk/docs/examples/gettingstarted/repositories/src/test/java/org/jboss/example/dna/repository/RepositoryClientTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryConnectorI18n.java
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryConnectorI18n.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryConnectorI18n.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -32,6 +32,7 @@
public static I18n connectorName;
public static I18n nodeDoesNotExist;
+ public static I18n errorSerializingCachePolicyInSource;
static {
try {
Modified: trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepository.java
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepository.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepository.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -44,6 +44,7 @@
import org.jboss.dna.spi.graph.commands.DeleteBranchCommand;
import org.jboss.dna.spi.graph.commands.GetChildrenCommand;
import org.jboss.dna.spi.graph.commands.GetPropertiesCommand;
+import org.jboss.dna.spi.graph.commands.GraphCommand;
import org.jboss.dna.spi.graph.commands.MoveBranchCommand;
import org.jboss.dna.spi.graph.commands.RecordBranchCommand;
import org.jboss.dna.spi.graph.commands.SetPropertiesCommand;
@@ -344,12 +345,15 @@
@Override
public void execute( CreateNodeCommand command ) {
Path path = command.getPath();
- Path parent = path.getParent();
- // Look up the parent node, which must exist ...
- Node parentNode = getNode(parent);
- if (parentNode == null) {
- Path lowestExisting = getLowestExistingPath(parent);
- throw new PathNotFoundException(path, lowestExisting, InMemoryConnectorI18n.nodeDoesNotExist.text(parent));
+ Node parentNode = null;
+ if (!path.isRoot()) {
+ Path parent = path.getParent();
+ // Look up the parent node, which must exist ...
+ parentNode = getNode(parent);
+ if (parentNode == null) {
+ Path lowestExisting = getLowestExistingPath(parent);
+ throw new PathNotFoundException(path, lowestExisting, InMemoryConnectorI18n.nodeDoesNotExist.text(parent));
+ }
}
UUID uuid = null;
for (Property property : command.getProperties()) {
@@ -376,6 +380,7 @@
@Override
public void execute( GetChildrenCommand command ) {
Node node = getTargetNode(command);
+ if (node == null) return;
// Get the names of the children ...
List<Node> children = node.getChildren();
for (Node child : children) {
@@ -387,6 +392,7 @@
@Override
public void execute( GetPropertiesCommand command ) {
Node node = getTargetNode(command);
+ if (node == null) return;
for (Property property : node.getProperties().values()) {
command.setProperty(property);
}
@@ -396,6 +402,7 @@
@Override
public void execute( SetPropertiesCommand command ) {
Node node = getTargetNode(command);
+ if (node == null) return;
// Now set (or remove) the properties to the supplied node ...
for (Property property : command.getProperties()) {
Name propName = property.getName();
@@ -412,12 +419,14 @@
@Override
public void execute( DeleteBranchCommand command ) {
Node node = getTargetNode(command);
+ if (node == null) return;
removeNode(getExecutionContext(), node);
}
@Override
public void execute( CopyNodeCommand command ) {
Node node = getTargetNode(command);
+ if (node == null) return;
// Look up the new parent, which must exist ...
Path newPath = command.getNewPath();
Node newParent = getNode(newPath.getParent());
@@ -427,6 +436,7 @@
@Override
public void execute( CopyBranchCommand command ) {
Node node = getTargetNode(command);
+ if (node == null) return;
// Look up the new parent, which must exist ...
Path newPath = command.getNewPath();
Node newParent = getNode(newPath.getParent());
@@ -436,6 +446,7 @@
@Override
public void execute( MoveBranchCommand command ) {
Node node = getTargetNode(command);
+ if (node == null) return;
// Look up the new parent, which must exist ...
Path newPath = command.getNewPath();
Node newParent = getNode(newPath.getParent());
@@ -445,6 +456,7 @@
@Override
public void execute( RecordBranchCommand command ) {
Node node = getTargetNode(command);
+ if (node == null) return;
recordNode(command, node);
}
@@ -456,15 +468,17 @@
}
}
- protected Node getTargetNode( ActsOnPath command ) {
+ protected <T extends ActsOnPath & GraphCommand> Node getTargetNode( T command ) {
Path path = command.getPath();
// Look up the node with the supplied path ...
Node node = InMemoryRepository.this.getNode(path);
if (node == null) {
Path lowestExisting = getLowestExistingPath(path);
- throw new PathNotFoundException(path, lowestExisting, InMemoryConnectorI18n.nodeDoesNotExist.text(path));
+ command.setError(new PathNotFoundException(path, lowestExisting,
+ InMemoryConnectorI18n.nodeDoesNotExist.text(path)));
+ return null;
}
- return null;
+ return node;
}
}
Modified: trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryConnection.java
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryConnection.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryConnection.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -24,6 +24,8 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import javax.transaction.xa.XAResource;
+import org.jboss.dna.common.stats.Stopwatch;
+import org.jboss.dna.common.util.Logger;
import org.jboss.dna.spi.ExecutionContext;
import org.jboss.dna.spi.cache.CachePolicy;
import org.jboss.dna.spi.connector.RepositoryConnection;
@@ -112,6 +114,12 @@
*/
public void execute( ExecutionContext context,
GraphCommand... commands ) throws RepositorySourceException {
+ Logger logger = context.getLogger(getClass());
+ Stopwatch sw = null;
+ if (logger.isTraceEnabled()) {
+ sw = new Stopwatch();
+ sw.start();
+ }
// Do any commands update/write?
Lock lock = this.content.getLock().readLock();
for (GraphCommand command : commands) {
@@ -131,6 +139,11 @@
} finally {
lock.unlock();
}
+ if (logger.isTraceEnabled()) {
+ assert sw != null;
+ sw.stop();
+ logger.trace("InMemoryRepositoryConnection.execute(...) took " + sw.getTotalDuration());
+ }
}
protected InMemoryRepository getContent() {
Modified: trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositorySource.java
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositorySource.java 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/extensions/dna-connector-inmemory/src/main/java/org/jboss/dna/connector/inmemory/InMemoryRepositorySource.java 2008-09-11 23:33:03 UTC (rev 515)
@@ -21,16 +21,18 @@
*/
package org.jboss.dna.connector.inmemory;
-import java.util.Collections;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.Enumeration;
+import java.util.HashMap;
import java.util.Hashtable;
-import java.util.Set;
+import java.util.Map;
import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
+import javax.naming.BinaryRefAddr;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@@ -39,6 +41,7 @@
import javax.naming.StringRefAddr;
import javax.naming.spi.ObjectFactory;
import net.jcip.annotations.GuardedBy;
+import org.jboss.dna.common.i18n.I18n;
import org.jboss.dna.common.util.ArgCheck;
import org.jboss.dna.spi.cache.CachePolicy;
import org.jboss.dna.spi.connector.RepositoryConnection;
@@ -61,40 +64,12 @@
*/
public static final int DEFAULT_RETRY_LIMIT = 0;
- private static final ConcurrentMap<String, InMemoryRepositorySource> sources = new ConcurrentHashMap<String, InMemoryRepositorySource>();
- private static final ReadWriteLock sourcesLock = new ReentrantReadWriteLock();
+ protected static final String ROOT_NODE_UUID = "rootNodeUuid";
+ protected static final String SOURCE_NAME = "sourceName";
+ protected static final String DEFAULT_CACHE_POLICY = "defaultCachePolicy";
+ protected static final String JNDI_NAME = "jndiName";
+ protected static final String RETRY_LIMIT = "retryLimit";
- /**
- * Get the names of the in-memory repository sources that are currently registered
- *
- * @return the unmodifiable set of names
- */
- public static Set<String> getSourceNames() {
- Lock lock = sourcesLock.readLock();
- try {
- lock.lock();
- return Collections.unmodifiableSet(sources.keySet());
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * Get the source with the supplied name.
- *
- * @param name the name
- * @return the source, or null if there is no source with the supplied name
- */
- public static InMemoryRepositorySource getSource( String name ) {
- Lock lock = sourcesLock.readLock();
- try {
- lock.lock();
- return sources.get(name);
- } finally {
- lock.unlock();
- }
- }
-
@GuardedBy( "sourcesLock" )
private String name;
@GuardedBy( "this" )
@@ -212,37 +187,14 @@
* {@inheritDoc}
*/
public String getName() {
- Lock lock = sourcesLock.readLock();
- try {
- lock.lock();
- return this.name;
- } finally {
- lock.unlock();
- }
+ return this.name;
}
/**
* @param name Sets name to the specified value.
- * @return true if the name was changed, or false if an existing instance already exists with that name
*/
- public boolean setName( String name ) {
- Lock lock = sourcesLock.writeLock();
- try {
- lock.lock();
- // Determine if this name is allowed ...
- if (sources.containsKey(name)) return false;
-
- // Remove this object under its current name
- if (this.name != null) {
- sources.remove(this.name);
- }
- // Register this object under the new name
- this.name = name;
- sources.put(this.name, this);
- return true;
- } finally {
- lock.unlock();
- }
+ public void setName( String name ) {
+ this.name = name;
}
/**
@@ -260,11 +212,34 @@
/**
* {@inheritDoc}
*/
- public Reference getReference() {
+ public synchronized Reference getReference() {
String className = getClass().getName();
- String factoryClassName = className;
- return new Reference(className, new StringRefAddr("DnaConnectorInMemoryRepositorySource", getName()), factoryClassName,
- null);
+ String factoryClassName = this.getClass().getName();
+ Reference ref = new Reference(className, factoryClassName, null);
+
+ if (getName() != null) {
+ ref.add(new StringRefAddr(SOURCE_NAME, getName()));
+ }
+ if (getRootNodeUuid() != null) {
+ ref.add(new StringRefAddr(ROOT_NODE_UUID, getRootNodeUuid().toString()));
+ }
+ if (getJndiName() != null) {
+ ref.add(new StringRefAddr(JNDI_NAME, getJndiName()));
+ }
+ if (getDefaultCachePolicy() != null) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ CachePolicy policy = getDefaultCachePolicy();
+ try {
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(policy);
+ ref.add(new BinaryRefAddr(DEFAULT_CACHE_POLICY, baos.toByteArray()));
+ } catch (IOException e) {
+ I18n msg = InMemoryConnectorI18n.errorSerializingCachePolicyInSource;
+ throw new RepositorySourceException(getName(), msg.text(policy.getClass().getName(), getName()), e);
+ }
+ }
+ ref.add(new StringRefAddr(RETRY_LIMIT, Integer.toString(getRetryLimit())));
+ return ref;
}
/**
@@ -273,13 +248,45 @@
public Object getObjectInstance( Object obj,
javax.naming.Name name,
Context nameCtx,
- Hashtable<?, ?> environment ) {
+ Hashtable<?, ?> environment ) throws Exception {
if (obj instanceof Reference) {
+ Map<String, Object> values = new HashMap<String, Object>();
Reference ref = (Reference)obj;
- if (ref.getClassName().equals(getClass().getName())) {
- RefAddr addr = ref.get("DnaConnectorInMemoryRepositorySource");
- return InMemoryRepositorySource.getSource((String)addr.getContent());
+ Enumeration<?> en = ref.getAll();
+ while (en.hasMoreElements()) {
+ RefAddr subref = (RefAddr)en.nextElement();
+ if (subref instanceof StringRefAddr) {
+ String key = subref.getType();
+ Object value = subref.getContent();
+ if (value != null) values.put(key, value.toString());
+ } else if (subref instanceof BinaryRefAddr) {
+ String key = subref.getType();
+ Object value = subref.getContent();
+ if (value instanceof byte[]) {
+ // Deserialize ...
+ ByteArrayInputStream bais = new ByteArrayInputStream((byte[])value);
+ ObjectInputStream ois = new ObjectInputStream(bais);
+ value = ois.readObject();
+ values.put(key, value);
+ }
+ }
}
+ String sourceName = (String)values.get(SOURCE_NAME);
+ String rootNodeUuidString = (String)values.get(ROOT_NODE_UUID);
+ String jndiName = (String)values.get(JNDI_NAME);
+ Object defaultCachePolicy = values.get(DEFAULT_CACHE_POLICY);
+ String retryLimit = (String)values.get(RETRY_LIMIT);
+
+ // Create the source instance ...
+ InMemoryRepositorySource source = new InMemoryRepositorySource();
+ if (sourceName != null) source.setName(sourceName);
+ if (rootNodeUuidString != null) source.setRootNodeUuid(UUID.fromString(rootNodeUuidString));
+ if (jndiName != null) source.setJndiName(jndiName);
+ if (defaultCachePolicy instanceof CachePolicy) {
+ source.setDefaultCachePolicy((CachePolicy)defaultCachePolicy);
+ }
+ if (retryLimit != null) source.setRetryLimit(Integer.parseInt(retryLimit));
+ return source;
}
return null;
}
Modified: trunk/extensions/dna-connector-inmemory/src/main/resources/org/jboss/dna/connector/inmemory/InMemoryConnectorI18n.properties
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/main/resources/org/jboss/dna/connector/inmemory/InMemoryConnectorI18n.properties 2008-09-10 18:05:54 UTC (rev 514)
+++ trunk/extensions/dna-connector-inmemory/src/main/resources/org/jboss/dna/connector/inmemory/InMemoryConnectorI18n.properties 2008-09-11 23:33:03 UTC (rev 515)
@@ -21,4 +21,5 @@
#
connectorName = In-Memory Connector
-nodeDoesNotExist = Could not find an existing node at {0}
\ No newline at end of file
+nodeDoesNotExist = Could not find an existing node at {0}
+errorSerializingCachePolicyInSource = Error serializing a {0} instance owned by the {1} InMemoryRepositorySource
Added: trunk/extensions/dna-connector-inmemory/src/test/resources/log4j.properties
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/test/resources/log4j.properties (rev 0)
+++ trunk/extensions/dna-connector-inmemory/src/test/resources/log4j.properties 2008-09-11 23:33:03 UTC (rev 515)
@@ -0,0 +1,20 @@
+# Direct log messages to stdout
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %m%n
+
+# Root logger option
+log4j.rootLogger=INFO, stdout
+
+# Set up the default logging to be INFO level, then override specific units
+log4j.logger.org.jboss.dna=INFO
+#log4j.logger.org.jboss.dna.repository.sequencers=TRACE
+#log4j.logger.org.jboss.dna.sequencer=DEBUG
+#log4j.logger.org.jboss.dna.connector=TRACE
+#log4j.logger.org.jboss.dna.spi=DEBUG
+
+# Jackrabbit logging
+log4j.logger.org.apache.jackrabbit=WARN, stdout
+log4j.logger.org.apache.derby=INFO, stdout
+
Property changes on: trunk/extensions/dna-connector-inmemory/src/test/resources/log4j.properties
___________________________________________________________________
Name: svn:mime-type
+ text/plain
15 years, 7 months
DNA SVN: r514 - in trunk: dna-spi/src/test/java/org/jboss/dna/spi/graph/impl and 1 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-10 14:05:54 -0400 (Wed, 10 Sep 2008)
New Revision: 514
Modified:
trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicPathSegment.java
trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicPathSegmentTest.java
trunk/extensions/dna-connector-inmemory/src/test/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryTest.java
Log:
DNA-220 - Path segment without an index is not considered equal to a segment with an index of 1
http://jira.jboss.com/jira/browse/DNA-220
Changed the behavior of BasicPathSegment.equals(...) so that a segment without an index is equivalent to another segment with the same name but with an index of 1. Also corrected a test case of the InMemory connector.
Modified: trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicPathSegment.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicPathSegment.java 2008-09-10 15:19:33 UTC (rev 513)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicPathSegment.java 2008-09-10 18:05:54 UTC (rev 514)
@@ -125,7 +125,7 @@
if (obj instanceof Path.Segment) {
Path.Segment that = (Path.Segment)obj;
if (!this.getName().equals(that.getName())) return false;
- return this.getIndex() == that.getIndex();
+ return Math.abs(getIndex()) == Math.abs(that.getIndex());
}
return false;
}
Modified: trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicPathSegmentTest.java
===================================================================
--- trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicPathSegmentTest.java 2008-09-10 15:19:33 UTC (rev 513)
+++ trunk/dna-spi/src/test/java/org/jboss/dna/spi/graph/impl/BasicPathSegmentTest.java 2008-09-10 18:05:54 UTC (rev 514)
@@ -22,6 +22,7 @@
package org.jboss.dna.spi.graph.impl;
import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
import org.jboss.dna.common.text.TextEncoder;
import org.jboss.dna.spi.DnaLexicon;
@@ -141,4 +142,20 @@
assertThat(segment.equals(Path.PARENT_SEGMENT), is(true));
}
+ @Test
+ public void shouldConsiderSegmentWithSameNameSiblingIndexOfOneToBeEqualToSegmentWithSameNameButNoIndex() {
+ segment = new BasicPathSegment(validName, Path.NO_INDEX);
+ Path.Segment segment2 = new BasicPathSegment(validName, 1);
+ assertThat(segment, is(segment2));
+ }
+
+ @Test
+ public void shouldConsiderSegmentWithSameNameSiblingIndexOfTwoOrMoreToNotBeEqualToSegmentWithSameNameButNoIndex() {
+ segment = new BasicPathSegment(validName, Path.NO_INDEX);
+ Path.Segment segment2 = new BasicPathSegment(validName, 2);
+ assertThat(segment, is(not(segment2)));
+ segment2 = new BasicPathSegment(validName, 3);
+ assertThat(segment, is(not(segment2)));
+ }
+
}
Modified: trunk/extensions/dna-connector-inmemory/src/test/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryTest.java
===================================================================
--- trunk/extensions/dna-connector-inmemory/src/test/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryTest.java 2008-09-10 15:19:33 UTC (rev 513)
+++ trunk/extensions/dna-connector-inmemory/src/test/java/org/jboss/dna/connector/inmemory/InMemoryRepositoryTest.java 2008-09-10 18:05:54 UTC (rev 514)
@@ -187,7 +187,13 @@
/*Node node_c =*/repository.createNode(context, node_b, nameFactory.create("c"), null);
assertThat(repository.getNodesByUuid().size(), is(4));
- assertThat(repository.getNode(pathFactory.create("/a[1]")), is(nullValue()));
+ assertThat(repository.getNode(pathFactory.create("/a")), is(node_a));
+ assertThat(repository.getNode(pathFactory.create("/a/b")), is(node_b));
+ assertThat(repository.getNode(pathFactory.create("/a[1]")), is(node_a));
+ assertThat(repository.getNode(pathFactory.create("/a/b[1]")), is(node_b));
+ assertThat(repository.getNode(pathFactory.create("/a[1]/b[1]")), is(node_b));
+ assertThat(repository.getNode(pathFactory.create("/a[2]")), is(nullValue()));
+ assertThat(repository.getNode(pathFactory.create("/b[2]")), is(nullValue()));
assertThat(repository.getNode(pathFactory.create("/d")), is(nullValue()));
}
15 years, 7 months
DNA SVN: r513 - in trunk: dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml and 7 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-10 11:19:33 -0400 (Wed, 10 Sep 2008)
New Revision: 513
Added:
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaDtdLexicon.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaXmlLexicon.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java
trunk/dna-repository/src/test/resources/repositoryImporterTestData1.xml
Modified:
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryI18n.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/XmlSequencer.java
trunk/dna-repository/src/main/resources/org/jboss/dna/repository/RepositoryI18n.properties
trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/xml/XmlSequencerTest.java
trunk/dna-repository/src/test/resources/CurrencyFormatterExample.mxml
trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/ValueComparators.java
trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicProperty.java
trunk/dna-spi/src/test/java/org/jboss/dna/spi/sequencers/MockSequencerOutput.java
Log:
Added RepositoryImporter that is capable of importing content from an XML document into a RepositorySource. This will be used in the example and is an easy way to populate an InMemoryRepositorySource. Also added several lexicon classes rather than miscellaneous constants.
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryI18n.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryI18n.java 2008-09-09 18:56:21 UTC (rev 512)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryI18n.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -122,8 +122,9 @@
public static I18n canceledSequencingXmlDocument;
public static I18n warningSequencingXmlDocument;
- // Federation
+ // Repository
public static I18n errorStartingRepositoryService;
+ public static I18n errorImportingContent;
static {
try {
Added: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java (rev 0)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -0,0 +1,440 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.repository;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+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 org.jboss.dna.common.i18n.I18n;
+import org.jboss.dna.common.monitor.ProgressMonitor;
+import org.jboss.dna.common.monitor.SimpleProgressMonitor;
+import org.jboss.dna.common.util.ArgCheck;
+import org.jboss.dna.common.util.Logger;
+import org.jboss.dna.repository.sequencers.xml.XmlSequencer;
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.connector.RepositoryConnection;
+import org.jboss.dna.spi.connector.RepositoryConnectionFactory;
+import org.jboss.dna.spi.connector.RepositorySource;
+import org.jboss.dna.spi.connector.RepositorySourceException;
+import org.jboss.dna.spi.graph.Name;
+import org.jboss.dna.spi.graph.NameFactory;
+import org.jboss.dna.spi.graph.NamespaceRegistry;
+import org.jboss.dna.spi.graph.Path;
+import org.jboss.dna.spi.graph.PathFactory;
+import org.jboss.dna.spi.graph.Property;
+import org.jboss.dna.spi.graph.PropertyFactory;
+import org.jboss.dna.spi.graph.Reference;
+import org.jboss.dna.spi.graph.ValueFactories;
+import org.jboss.dna.spi.graph.ValueFactory;
+import org.jboss.dna.spi.graph.ValueFormatException;
+import org.jboss.dna.spi.graph.commands.CompositeCommand;
+import org.jboss.dna.spi.graph.commands.GraphCommand;
+import org.jboss.dna.spi.graph.commands.NodeConflictBehavior;
+import org.jboss.dna.spi.graph.commands.impl.BasicCreateNodeCommand;
+import org.jboss.dna.spi.graph.commands.impl.BasicGraphCommand;
+import org.jboss.dna.spi.sequencers.SequencerContext;
+import org.jboss.dna.spi.sequencers.SequencerOutput;
+import org.jboss.dna.spi.sequencers.StreamSequencer;
+
+/**
+ * @author Randall Hauch
+ */
+public class RepositoryImporter {
+
+ private final RepositoryConnectionFactory sources;
+ private final String sourceName;
+ private final ExecutionContext context;
+
+ public RepositoryImporter( RepositorySource source,
+ ExecutionContext context ) {
+ ArgCheck.isNotNull(source, "source");
+ ArgCheck.isNotNull(context, "context");
+ this.sources = new SingleRepositorySourceConnectionFactory(source);
+ this.sourceName = source.getName();
+ this.context = context;
+ }
+
+ public RepositoryImporter( RepositoryConnectionFactory sources,
+ String sourceName,
+ ExecutionContext context ) {
+ ArgCheck.isNotNull(sources, "sources");
+ ArgCheck.isNotEmpty(sourceName, "sourceName");
+ ArgCheck.isNotNull(context, "context");
+ this.sources = sources;
+ this.sourceName = sourceName;
+ this.context = context;
+ }
+
+ /**
+ * Get the context in which the importer will be executed.
+ *
+ * @return the execution context; never null
+ */
+ public ExecutionContext getContext() {
+ return this.context;
+ }
+
+ /**
+ * Read the content from the supplied URI and import into the repository at the supplied location.
+ *
+ * @param uri the URI where the importer can read the content that is to be imported
+ * @param destinationPathInSource
+ * @throws IllegalArgumentException if the <code>uri</code> or destination path are null
+ * @throws IOException if there is a problem reading the content
+ * @throws RepositorySourceException if there is a problem while writing the content to the {@link RepositorySource repository
+ * source}
+ */
+ public void importXml( URI uri,
+ Path destinationPathInSource ) throws IOException, RepositorySourceException {
+ ArgCheck.isNotNull(uri, "uri");
+ ArgCheck.isNotNull(destinationPathInSource, "destinationPathInSource");
+
+ // Create the sequencer ...
+ StreamSequencer sequencer = new XmlSequencer();
+ importWithSequencer(sequencer, uri, "text/xml", destinationPathInSource, NodeConflictBehavior.UPDATE);
+ }
+
+ /**
+ * Use the supplied sequencer to read the content at the given URI (with the specified MIME type) and write that content to
+ * the {@link RepositorySource repository source} into the specified location.
+ *
+ * @param sequencer the sequencer that should be used; may not be null
+ * @param contentUri the URI where the content can be found; may not be null
+ * @param mimeType the MIME type for the content; may not be null
+ * @param destinationPathInSource the path in the {@link RepositorySource repository source} where the content is to be
+ * written; may not be null
+ * @param conflictBehavior the behavior when a node is to be created when an existing node already exists; defaults to
+ * {@link NodeConflictBehavior#UPDATE} if null
+ * @throws IOException if there is a problem reading the content
+ * @throws RepositorySourceException if there is a problem while writing the content to the {@link RepositorySource repository
+ * source}
+ */
+ protected void importWithSequencer( StreamSequencer sequencer,
+ URI contentUri,
+ String mimeType,
+ Path destinationPathInSource,
+ NodeConflictBehavior conflictBehavior ) throws IOException, RepositorySourceException {
+ assert sequencer != null;
+ assert contentUri != null;
+ assert mimeType != null;
+ assert destinationPathInSource != null;
+ conflictBehavior = conflictBehavior != null ? conflictBehavior : NodeConflictBehavior.UPDATE;
+
+ // Get the input path by creating from the URI, in case the URI is a valid path ...
+ Path inputPath = extractInputPathFrom(contentUri);
+ assert inputPath != null;
+
+ // Now create the importer context ...
+ PropertyFactory propertyFactory = getContext().getPropertyFactory();
+ NameFactory nameFactory = getContext().getValueFactories().getNameFactory();
+ Set<Property> inputProperties = new HashSet<Property>();
+ inputProperties.add(propertyFactory.create(nameFactory.create("jcr:mimeType"), mimeType));
+ ImporterContext importerContext = new ImporterContext(inputPath, inputProperties, "text/xml");
+
+ // Now run the sequencer ...
+ String activity = RepositoryI18n.errorImportingContent.text(destinationPathInSource, contentUri);
+ ProgressMonitor progressMonitor = new SimpleProgressMonitor(activity);
+ ImporterCommands commands = new ImporterCommands(destinationPathInSource, conflictBehavior);
+ InputStream stream = null;
+ try {
+ stream = contentUri.toURL().openStream();
+ sequencer.sequence(stream, commands, importerContext, progressMonitor);
+ } catch (MalformedURLException err) {
+ throw new IOException(err.getMessage());
+ } finally {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ I18n msg = RepositoryI18n.errorImportingContent;
+ context.getLogger(getClass()).error(e, msg, mimeType, contentUri);
+ }
+ }
+ }
+
+ // Now execute the commands against the repository ...
+ RepositoryConnection connection = null;
+ try {
+ connection = sources.createConnection(this.sourceName);
+ connection.execute(context, commands);
+ } finally {
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (RepositorySourceException e) {
+ I18n msg = RepositoryI18n.errorImportingContent;
+ context.getLogger(getClass()).error(e, msg, mimeType, contentUri);
+ }
+ }
+ }
+ }
+
+ /**
+ * @param contentUri
+ * @return the input path
+ */
+ protected Path extractInputPathFrom( URI contentUri ) {
+ try {
+ return getContext().getValueFactories().getPathFactory().create(contentUri);
+ } catch (ValueFormatException e) {
+ // Get the last component of the URI, and use it to create the input path ...
+ String path = contentUri.getPath();
+ return getContext().getValueFactories().getPathFactory().create(path);
+ }
+ }
+
+ protected class SingleRepositorySourceConnectionFactory implements RepositoryConnectionFactory {
+ private final RepositorySource source;
+
+ protected SingleRepositorySourceConnectionFactory( RepositorySource source ) {
+ ArgCheck.isNotNull(source, "source");
+ this.source = source;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.connector.RepositoryConnectionFactory#createConnection(java.lang.String)
+ */
+ public RepositoryConnection createConnection( String sourceName ) throws RepositorySourceException {
+ if (source.getName().equals(sourceName)) {
+ return source.getConnection();
+ }
+ return null;
+ }
+ }
+
+ protected class ImporterCommands extends BasicGraphCommand implements SequencerOutput, CompositeCommand {
+ private final List<GraphCommand> commands = new ArrayList<GraphCommand>();
+ private final Map<Path, BasicCreateNodeCommand> createNodeCommands = new HashMap<Path, BasicCreateNodeCommand>();
+ private final NodeConflictBehavior conflictBehavior;
+ private final Path destinationPath;
+
+ protected ImporterCommands( Path destinationPath,
+ NodeConflictBehavior conflictBehavior ) {
+ ArgCheck.isNotNull(destinationPath, "destinationPath");
+ ArgCheck.isNotNull(conflictBehavior, "conflictBehavior");
+ this.conflictBehavior = conflictBehavior;
+ this.destinationPath = destinationPath;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerOutput#getFactories()
+ */
+ public ValueFactories getFactories() {
+ return getContext().getValueFactories();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerOutput#getNamespaceRegistry()
+ */
+ public NamespaceRegistry getNamespaceRegistry() {
+ return getContext().getNamespaceRegistry();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerOutput#setProperty(java.lang.String, java.lang.String, java.lang.Object[])
+ */
+ public void setProperty( String nodePath,
+ String propertyName,
+ Object... values ) {
+ // Create a command that sets the property ...
+ Path path = getFactories().getPathFactory().create(nodePath);
+ Name name = getFactories().getNameFactory().create(propertyName);
+ setProperty(path, name, values);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerOutput#setProperty(org.jboss.dna.spi.graph.Path,
+ * org.jboss.dna.spi.graph.Name, java.lang.Object[])
+ */
+ public void setProperty( Path nodePath,
+ Name propertyName,
+ Object... values ) {
+ PathFactory pathFactory = getFactories().getPathFactory();
+ if (nodePath.isAbsolute()) nodePath.relativeTo(pathFactory.createRootPath());
+ nodePath = pathFactory.create(destinationPath, nodePath).getNormalizedPath();
+ Property property = getContext().getPropertyFactory().create(propertyName, values);
+ BasicCreateNodeCommand command = createNodeCommands.get(nodePath);
+ if (command != null) {
+ // We've already created the node, so find that command and add to it.
+ Collection<Property> properties = command.getProperties();
+ // See if the property was already added and remove it if so
+ Iterator<Property> iter = properties.iterator();
+ while (iter.hasNext()) {
+ Property existingProperty = iter.next();
+ if (existingProperty.getName().equals(propertyName)) {
+ iter.remove();
+ break;
+ }
+ }
+ command.getProperties().add(property);
+ } else {
+ // We haven't created the node yet (and we're assuming that we need to), so create the node
+ List<Property> properties = new ArrayList<Property>();
+ properties.add(property);
+ command = new BasicCreateNodeCommand(nodePath, properties, conflictBehavior);
+ createNodeCommands.put(nodePath, command);
+ commands.add(command);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerOutput#setReference(java.lang.String, java.lang.String, java.lang.String[])
+ */
+ public void setReference( String nodePath,
+ String propertyName,
+ String... paths ) {
+ Path path = getFactories().getPathFactory().create(nodePath);
+ Name name = getFactories().getNameFactory().create(propertyName);
+ // Create an array of reference values ...
+ ValueFactory<Reference> factory = getFactories().getReferenceFactory();
+ Object[] values = new Object[paths.length];
+ int i = 0;
+ for (String referencedPath : paths) {
+ values[i++] = factory.create(referencedPath);
+ }
+ setProperty(path, name, values);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.lang.Iterable#iterator()
+ */
+ public Iterator<GraphCommand> iterator() {
+ return this.commands.iterator();
+ }
+
+ }
+
+ protected class ImporterContext implements SequencerContext {
+
+ private final Path inputPath;
+ private final Set<Property> inputProperties;
+ private final String mimeType;
+
+ protected ImporterContext( Path inputPath,
+ Set<Property> inputProperties,
+ String mimeType ) {
+ this.inputPath = inputPath;
+ this.inputProperties = inputProperties;
+ this.mimeType = mimeType;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerContext#getFactories()
+ */
+ public ValueFactories getFactories() {
+ return getContext().getValueFactories();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerContext#getInputPath()
+ */
+ public Path getInputPath() {
+ return inputPath;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerContext#getInputProperties()
+ */
+ public Set<Property> getInputProperties() {
+ return inputProperties;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerContext#getInputProperty(org.jboss.dna.spi.graph.Name)
+ */
+ public Property getInputProperty( Name name ) {
+ for (Property property : inputProperties) {
+ if (property.getName().equals(name)) return property;
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerContext#getLogger(java.lang.Class)
+ */
+ public Logger getLogger( Class<?> clazz ) {
+ return getContext().getLogger(clazz);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerContext#getLogger(java.lang.String)
+ */
+ public Logger getLogger( String name ) {
+ return getContext().getLogger(name);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerContext#getMimeType()
+ */
+ public String getMimeType() {
+ return mimeType;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerContext#getNamespaceRegistry()
+ */
+ public NamespaceRegistry getNamespaceRegistry() {
+ return getContext().getNamespaceRegistry();
+ }
+
+ }
+
+}
Property changes on: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryImporter.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaDtdLexicon.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaDtdLexicon.java (rev 0)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaDtdLexicon.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -0,0 +1,42 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.repository.sequencers.xml;
+
+import org.jboss.dna.spi.graph.Name;
+import org.jboss.dna.spi.graph.impl.BasicName;
+
+/**
+ * @author Randall Hauch
+ */
+public class DnaDtdLexicon {
+
+ public static class Namespace {
+ public static final String URI = "http://www.jboss.org/dna/dtd/1.0";
+ public static final String PREFIX = "dnadtd";
+ }
+
+ public static final Name NAME = new BasicName(Namespace.URI, "name");
+ public static final Name PUBLIC_ID = new BasicName(Namespace.URI, "publicId");
+ public static final Name SYSTEM_ID = new BasicName(Namespace.URI, "systemId");
+ public static final Name VALUE = new BasicName(Namespace.URI, "value");
+ public static final Name ENTITY = new BasicName(Namespace.URI, "entity");
+}
Property changes on: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaDtdLexicon.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaXmlLexicon.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaXmlLexicon.java (rev 0)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaXmlLexicon.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -0,0 +1,46 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.repository.sequencers.xml;
+
+import org.jboss.dna.spi.graph.Name;
+import org.jboss.dna.spi.graph.impl.BasicName;
+
+/**
+ * @author Randall Hauch
+ */
+public class DnaXmlLexicon {
+
+ public static class Namespace {
+ public static final String URI = "http://www.jboss.org/dna/xml/1.0";
+ public static final String PREFIX = "dnaxml";
+ }
+
+ public static final Name CDATA = new BasicName(Namespace.URI, "cData");
+ public static final Name CDATA_CONTENT = new BasicName(Namespace.URI, "cDataContent");
+ public static final Name COMMENT = new BasicName(Namespace.URI, "comment");
+ public static final Name COMMENT_CONTENT = new BasicName(Namespace.URI, "commentContent");
+ public static final Name DOCUMENT = new BasicName(Namespace.URI, "document");
+ public static final Name ELEMENT_CONTENT = new BasicName(Namespace.URI, "elementContent");
+ public static final Name PROCESSING_INSTRUCTION = new BasicName(Namespace.URI, "processingInstruction");
+ public static final Name PROCESSING_INSTRUCTION_CONTENT = new BasicName(Namespace.URI, "processingInstructionContent");
+ public static final Name TARGET = new BasicName(Namespace.URI, "target");
+}
Property changes on: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/DnaXmlLexicon.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/XmlSequencer.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/XmlSequencer.java 2008-09-09 18:56:21 UTC (rev 512)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/xml/XmlSequencer.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -28,7 +28,6 @@
import java.util.List;
import java.util.Map;
import org.jboss.dna.common.monitor.ProgressMonitor;
-import org.jboss.dna.common.util.Logger;
import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.repository.RepositoryI18n;
import org.jboss.dna.spi.graph.Name;
@@ -52,23 +51,7 @@
*/
public class XmlSequencer implements StreamSequencer {
- static final Logger LOGGER = Logger.getLogger(XmlSequencer.class);
-
- static final String CDATA = "dnaxml:cData";
- static final String CDATA_CONTENT = "dnaxml:cDataContent";
- static final String COMMENT = "dnaxml:comment";
- static final String COMMENT_CONTENT = "dnaxml:commentContent";
- static final String DOCUMENT = "dnaxml:document";
- static final String DTD_NAME = "dnadtd:name";
- static final String DTD_PUBLIC_ID = "dnadtd:publicId";
- static final String DTD_SYSTEM_ID = "dnadtd:systemId";
- static final String DTD_VALUE = "dnadtd:value";
- static final String ELEMENT_CONTENT = "dnaxml:elementContent";
- static final String ENTITY = "dnadtd:entity";
- static final String PI = "dnaxml:processingInstruction";
- static final String PI_CONTENT = "dnaxml:processingInstructionContent";
- static final String TARGET = "dnaxml:target";
-
+ private static final String DEFAULT_PRIMARY_TYPE = "nt:unstructured";
private static final String DECL_HANDLER_FEATURE = "http://xml.org/sax/properties/declaration-handler";
private static final String ENTITY_RESOLVER_2_FEATURE = "http://xml.org/sax/features/use-entity-resolver2";
private static final String LEXICAL_HANDLER_FEATURE = "http://xml.org/sax/properties/lexical-handler";
@@ -124,11 +107,8 @@
// Cached instances of the name factory and commonly referenced names
private final NameFactory nameFactory;
- private Name commentContentName;
- private Name commentName;
- private Name elementContentName;
private Name primaryTypeName;
- private Name targetName;
+ private Name defaultPrimaryType;
// Recursive map used to track the number of occurrences of names for elements under a particular path
private Map<Name, List<IndexedName>> nameToIndexedNamesMap = new HashMap<Name, List<IndexedName>>();
@@ -231,9 +211,9 @@
int length ) throws SAXException {
stopIfCancelled();
// Output separate nodes for each comment since multiple are allowed
- startElement(getCommentName());
- output.setProperty(path, getPrimaryTypeName(), getCommentName());
- output.setProperty(path, getCommentContentName(), String.valueOf(ch, start, length));
+ startElement(DnaXmlLexicon.COMMENT);
+ output.setProperty(path, getPrimaryTypeName(), DnaXmlLexicon.COMMENT);
+ output.setProperty(path, DnaXmlLexicon.COMMENT_CONTENT, String.valueOf(ch, start, length));
endElement();
updateProgress();
}
@@ -262,7 +242,7 @@
public void endCDATA() throws SAXException {
stopIfCancelled();
// Output CDATA built in characters() method
- output.setProperty(path, nameFactory.create(CDATA_CONTENT), cDataBuilder.toString());
+ output.setProperty(path, DnaXmlLexicon.CDATA_CONTENT, cDataBuilder.toString());
endElement();
// Null-out builder to free memory
cDataBuilder = null;
@@ -279,9 +259,9 @@
// Skip if nothing in content but whitespace
if (content.length() > 0) {
// Create separate node for each content entry since entries can be interspersed amongst child elements
- startElement(getElementContentName());
- output.setProperty(path, getPrimaryTypeName(), getElementContentName());
- output.setProperty(path, getElementContentName(), content);
+ startElement(DnaXmlLexicon.ELEMENT_CONTENT);
+ output.setProperty(path, getPrimaryTypeName(), DnaXmlLexicon.ELEMENT_CONTENT);
+ output.setProperty(path, DnaXmlLexicon.ELEMENT_CONTENT, content);
endElement();
}
}
@@ -360,7 +340,7 @@
*/
@Override
public void error( SAXParseException error ) {
- LOGGER.error(error, RepositoryI18n.errorSequencingXmlDocument, error);
+ context.getLogger(XmlSequencer.class).error(error, RepositoryI18n.errorSequencingXmlDocument, error);
monitor.getProblems().addError(error, RepositoryI18n.errorSequencingXmlDocument, error);
}
@@ -377,12 +357,12 @@
String systemId ) throws SAXException {
stopIfCancelled();
// Add "synthetic" entity container to path to help prevent name collisions with XML elements
- Name entityName = nameFactory.create(ENTITY);
+ Name entityName = DnaDtdLexicon.ENTITY;
startElement(entityName);
output.setProperty(path, getPrimaryTypeName(), entityName);
- output.setProperty(path, nameFactory.create(DTD_NAME), name);
- output.setProperty(path, nameFactory.create(DTD_PUBLIC_ID), publicId);
- output.setProperty(path, nameFactory.create(DTD_SYSTEM_ID), systemId);
+ output.setProperty(path, nameFactory.create(DnaDtdLexicon.NAME), name);
+ output.setProperty(path, nameFactory.create(DnaDtdLexicon.PUBLIC_ID), publicId);
+ output.setProperty(path, nameFactory.create(DnaDtdLexicon.SYSTEM_ID), systemId);
endElement();
updateProgress();
}
@@ -396,31 +376,10 @@
*/
@Override
public void fatalError( SAXParseException error ) {
- LOGGER.error(error, RepositoryI18n.fatalErrorSequencingXmlDocument);
+ context.getLogger(XmlSequencer.class).error(error, RepositoryI18n.fatalErrorSequencingXmlDocument, error);
monitor.getProblems().addError(error, RepositoryI18n.fatalErrorSequencingXmlDocument, error);
}
- private Name getCommentContentName() {
- if (commentContentName == null) {
- commentContentName = nameFactory.create(COMMENT_CONTENT);
- }
- return commentContentName;
- }
-
- private Name getCommentName() {
- if (commentName == null) {
- commentName = nameFactory.create(COMMENT);
- }
- return commentName;
- }
-
- private Name getElementContentName() {
- if (elementContentName == null) {
- elementContentName = nameFactory.create(ELEMENT_CONTENT);
- }
- return elementContentName;
- }
-
private Name getPrimaryTypeName() {
if (primaryTypeName == null) {
primaryTypeName = nameFactory.create(NameFactory.JCR_PRIMARY_TYPE);
@@ -428,11 +387,11 @@
return primaryTypeName;
}
- private Name getTargetName() {
- if (targetName == null) {
- targetName = nameFactory.create(TARGET);
+ private Name getDefaultPrimaryType() {
+ if (defaultPrimaryType == null) {
+ defaultPrimaryType = nameFactory.create(DEFAULT_PRIMARY_TYPE);
}
- return targetName;
+ return defaultPrimaryType;
}
/**
@@ -461,11 +420,11 @@
String value ) throws SAXException {
stopIfCancelled();
// Add "synthetic" entity container to path to help prevent name collisions with XML elements
- Name entityName = nameFactory.create(ENTITY);
+ Name entityName = DnaDtdLexicon.ENTITY;
startElement(entityName);
output.setProperty(path, getPrimaryTypeName(), entityName);
- output.setProperty(path, nameFactory.create(DTD_NAME), name);
- output.setProperty(path, nameFactory.create(DTD_VALUE), value);
+ output.setProperty(path, DnaDtdLexicon.NAME, name);
+ output.setProperty(path, DnaDtdLexicon.VALUE, value);
endElement();
updateProgress();
}
@@ -496,11 +455,11 @@
String data ) throws SAXException {
stopIfCancelled();
// Output separate nodes for each instruction since multiple are allowed
- Name name = nameFactory.create(PI);
+ Name name = DnaXmlLexicon.PROCESSING_INSTRUCTION;
startElement(name);
output.setProperty(path, getPrimaryTypeName(), name);
- output.setProperty(path, getTargetName(), target);
- output.setProperty(path, nameFactory.create(PI_CONTENT), data);
+ output.setProperty(path, DnaXmlLexicon.TARGET, target);
+ output.setProperty(path, DnaXmlLexicon.PROCESSING_INSTRUCTION_CONTENT, data);
endElement();
updateProgress();
}
@@ -528,7 +487,7 @@
public void startCDATA() throws SAXException {
stopIfCancelled();
// Output separate nodes for each CDATA since multiple are allowed
- startElement(nameFactory.create(CDATA));
+ startElement(DnaXmlLexicon.CDATA);
// Prepare builder for concatenating consecutive lines of CDATA
cDataBuilder = new StringBuilder();
updateProgress();
@@ -544,7 +503,7 @@
@Override
public void startDocument() throws SAXException {
stopIfCancelled();
- output.setProperty(path, getPrimaryTypeName(), nameFactory.create(DOCUMENT));
+ output.setProperty(path, getPrimaryTypeName(), DnaXmlLexicon.DOCUMENT);
updateProgress();
}
@@ -560,9 +519,9 @@
String publicId,
String systemId ) throws SAXException {
stopIfCancelled();
- output.setProperty(path, nameFactory.create(DTD_NAME), name);
- output.setProperty(path, nameFactory.create(DTD_PUBLIC_ID), publicId);
- output.setProperty(path, nameFactory.create(DTD_SYSTEM_ID), systemId);
+ output.setProperty(path, DnaDtdLexicon.NAME, name);
+ output.setProperty(path, DnaDtdLexicon.PUBLIC_ID, publicId);
+ output.setProperty(path, DnaDtdLexicon.SYSTEM_ID, systemId);
updateProgress();
}
@@ -581,6 +540,7 @@
// Add element name and the appropriate index to the path.
// Per the JCR spec, the index must be relative to same-name sibling nodes
path = context.getFactories().getPathFactory().create(path, name, indexedNames.size());
+ path = path.getNormalizedPath();
// Add the indexed name map to the stack and set the current map to the new element's map
nameToIndexedNamesMapStack.addFirst(nameToIndexedNamesMap);
nameToIndexedNamesMap = indexedName.nameToIndexedNamesMap;
@@ -609,14 +569,18 @@
Attributes attributes ) throws SAXException {
stopIfCancelled();
startElement(nameFactory.create(name));
- output.setProperty(path, getPrimaryTypeName(), nameFactory.create(uri, localName));
+ output.setProperty(path, getPrimaryTypeName(), getDefaultPrimaryType());
// Output this element's attributes using the attribute's namespace, if supplied, or the current namespace in scope.
String inheritedNs = nsStack.getFirst();
for (int ndx = 0, len = attributes.getLength(); ndx < len; ++ndx) {
String ns = attributes.getURI(ndx);
- output.setProperty(path,
- nameFactory.create(ns.length() == 0 ? inheritedNs : ns, attributes.getLocalName(ndx)),
- attributes.getValue(ndx));
+ String attrLocalName = attributes.getLocalName(ndx);
+ Object value = attributes.getValue(ndx);
+ String jcrNsUri = context.getNamespaceRegistry().getNamespaceForPrefix("jcr");
+ if (jcrNsUri != null && jcrNsUri.equals(ns) && attrLocalName.equals("primaryType")) {
+ value = nameFactory.create(value);
+ }
+ output.setProperty(path, nameFactory.create(ns.length() == 0 ? inheritedNs : ns, attrLocalName), value);
}
updateProgress();
}
@@ -694,7 +658,7 @@
*/
@Override
public void warning( SAXParseException warning ) {
- LOGGER.warn(warning, RepositoryI18n.warningSequencingXmlDocument);
+ context.getLogger(XmlSequencer.class).warn(warning, RepositoryI18n.warningSequencingXmlDocument);
monitor.getProblems().addWarning(warning, RepositoryI18n.warningSequencingXmlDocument, warning);
}
}
Modified: trunk/dna-repository/src/main/resources/org/jboss/dna/repository/RepositoryI18n.properties
===================================================================
--- trunk/dna-repository/src/main/resources/org/jboss/dna/repository/RepositoryI18n.properties 2008-09-09 18:56:21 UTC (rev 512)
+++ trunk/dna-repository/src/main/resources/org/jboss/dna/repository/RepositoryI18n.properties 2008-09-10 15:19:33 UTC (rev 513)
@@ -103,3 +103,4 @@
warningSequencingXmlDocument = A warning was received while sequencing XML: {0}
errorStartingRepositoryService = Error while starting repository service
+errorImportingContent = Error importing {0} content from {1}
Added: trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java (rev 0)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -0,0 +1,182 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.repository;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsInstanceOf.instanceOf;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.stub;
+import java.io.File;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.transaction.xa.XAResource;
+import org.jboss.dna.common.util.StringUtil;
+import org.jboss.dna.repository.sequencers.xml.DnaDtdLexicon;
+import org.jboss.dna.repository.sequencers.xml.DnaXmlLexicon;
+import org.jboss.dna.spi.DnaLexicon;
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.cache.CachePolicy;
+import org.jboss.dna.spi.connector.BasicExecutionContext;
+import org.jboss.dna.spi.connector.RepositoryConnection;
+import org.jboss.dna.spi.connector.RepositoryConnectionFactory;
+import org.jboss.dna.spi.connector.RepositorySourceException;
+import org.jboss.dna.spi.connector.RepositorySourceListener;
+import org.jboss.dna.spi.graph.Name;
+import org.jboss.dna.spi.graph.Path;
+import org.jboss.dna.spi.graph.Property;
+import org.jboss.dna.spi.graph.commands.CompositeCommand;
+import org.jboss.dna.spi.graph.commands.CreateNodeCommand;
+import org.jboss.dna.spi.graph.commands.GraphCommand;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoAnnotations.Mock;
+
+/**
+ * @author Randall Hauch
+ */
+public class RepositoryImporterTest {
+
+ private RepositoryImporter importer;
+ private String sourceName;
+ private ExecutionContext context;
+ private URI xmlContent;
+ private MockRepositoryConnection connection;
+ private GraphCommand lastExecutedCommand;
+ private Path destinationPath;
+ @Mock
+ private RepositoryConnectionFactory sources;
+
+ @Before
+ public void beforeEach() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ xmlContent = new File("src/test/resources/repositoryImporterTestData1.xml").toURI();
+ context = new BasicExecutionContext();
+ context.getNamespaceRegistry().register(DnaLexicon.Namespace.PREFIX, DnaLexicon.Namespace.URI);
+ context.getNamespaceRegistry().register(DnaXmlLexicon.Namespace.PREFIX, DnaXmlLexicon.Namespace.URI);
+ context.getNamespaceRegistry().register(DnaDtdLexicon.Namespace.PREFIX, DnaDtdLexicon.Namespace.URI);
+ context.getNamespaceRegistry().register("jcr", "http://www.jcp.org/jcr/1.0");
+ context.getNamespaceRegistry().register("nt", "http://www.jcp.org/jcr/nt/1.0");
+ sourceName = "sourceA";
+ destinationPath = context.getValueFactories().getPathFactory().create("/a/b");
+ importer = new RepositoryImporter(sources, sourceName, context);
+ connection = new MockRepositoryConnection();
+ stub(sources.createConnection(sourceName)).toReturn(connection);
+ }
+
+ @Test
+ public void shouldImportXmlContentAndGenerateTheCorrectCommands() throws Exception {
+ System.out.println(xmlContent);
+ importer.importXml(xmlContent, destinationPath); // writes commands as CompositeCommand to 'lastExecutedCommand'
+ assertThat(lastExecutedCommand, is(instanceOf(CompositeCommand.class)));
+ Iterator<GraphCommand> iter = ((CompositeCommand)lastExecutedCommand).iterator();
+ assertCreateNode(iter, "/a/b/", "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}document");
+ assertCreateNode(iter, "/a/b/dnaxml:comment[1]", "any properties"); // jcr:primaryType and dnaxml:commentContent
+ assertCreateNode(iter, "/a/b/dna:system[1]", "jcr:primaryType={http://www.jcp.org/jcr/nt/1.0}unstructured");
+ assertCreateNode(iter, "/a/b/dna:system[1]/dnaxml:comment[1]", "any properties");
+ assertCreateNode(iter, "/a/b/dna:system[1]/dna:sources[1]", "jcr:primaryType={http://www.jcp.org/jcr/nt/1.0}unstructured");
+ assertCreateNode(iter,
+ "/a/b/dna:system[1]/dna:sources[1]/sourceA[1]",
+ "dna:repositoryName=repositoryA",
+ "dna:retryLimit=3",
+ "jcr:primaryType={http://www.jboss.org/dna}xyz",
+ "dna:classname=org.jboss.dna.connector.inmemory.InMemoryRepositorySource");
+ assertCreateNode(iter,
+ "/a/b/dna:system[1]/dna:sources[1]/sourceB[1]",
+ "dna:repositoryName=repositoryB",
+ "jcr:primaryType={http://www.jcp.org/jcr/nt/1.0}unstructured",
+ "dna:classname=org.jboss.dna.connector.inmemory.InMemoryRepositorySource");
+ assertThat(iter.hasNext(), is(false));
+ }
+
+ public void assertCreateNode( Iterator<GraphCommand> iterator,
+ String path,
+ String... properties ) {
+ GraphCommand nextCommand = iterator.next();
+ assertThat(nextCommand, is(instanceOf(CreateNodeCommand.class)));
+ CreateNodeCommand createNode = (CreateNodeCommand)nextCommand;
+ Path expectedPath = context.getValueFactories().getPathFactory().create(path);
+ assertThat(createNode.getPath(), is(expectedPath));
+ Map<Name, Property> propertiesByName = new HashMap<Name, Property>();
+ for (Property prop : createNode.getProperties()) {
+ propertiesByName.put(prop.getName(), prop);
+ }
+ for (String propertyStr : properties) {
+ if (propertyStr == "any properties") {
+ propertiesByName.clear();
+ break;
+ }
+ Matcher matcher = Pattern.compile("([^=]+)=(.*)").matcher(propertyStr);
+ if (!matcher.matches()) continue;
+ System.out.println("Property: " + propertyStr + " ==> " + matcher);
+ Name propertyName = context.getValueFactories().getNameFactory().create(matcher.group(1));
+ System.out.println("Property name: " + matcher.group(1));
+ String value = matcher.group(2); // doesn't handle multiple values!!
+ if (value.trim().length() == 0) value = null;
+ Property actual = propertiesByName.remove(propertyName);
+ Property expectedProperty = context.getPropertyFactory().create(propertyName, value);
+ assertThat(actual, is(expectedProperty));
+ }
+ if (!propertiesByName.isEmpty()) {
+ System.out.println("Properties for " + path + "\n" + StringUtil.readableString(propertiesByName));
+ }
+ assertThat(propertiesByName.isEmpty(), is(true));
+ }
+
+ protected class MockRepositoryConnection implements RepositoryConnection {
+ public void close() {
+ }
+
+ @SuppressWarnings( "synthetic-access" )
+ public void execute( ExecutionContext context,
+ GraphCommand... commands ) throws RepositorySourceException {
+ lastExecutedCommand = commands[0];
+ }
+
+ public CachePolicy getDefaultCachePolicy() {
+ return null;
+ }
+
+ @SuppressWarnings( "synthetic-access" )
+ public String getSourceName() {
+ return sourceName;
+ }
+
+ public XAResource getXAResource() {
+ return null;
+ }
+
+ public boolean ping( long time,
+ TimeUnit unit ) {
+ return true;
+ }
+
+ public void setListener( RepositorySourceListener listener ) {
+ }
+ }
+
+}
Property changes on: trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryImporterTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/xml/XmlSequencerTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/xml/XmlSequencerTest.java 2008-09-09 18:56:21 UTC (rev 512)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/xml/XmlSequencerTest.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -46,6 +46,21 @@
*/
public class XmlSequencerTest {
+ private static final String CDATA = "dnaxml:cData";
+ private static final String CDATA_CONTENT = "dnaxml:cDataContent";
+ private static final String COMMENT = "dnaxml:comment";
+ private static final String COMMENT_CONTENT = "dnaxml:commentContent";
+ private static final String DOCUMENT = "dnaxml:document";
+ private static final String DTD_NAME = "dnadtd:name";
+ private static final String DTD_PUBLIC_ID = "dnadtd:publicId";
+ private static final String DTD_SYSTEM_ID = "dnadtd:systemId";
+ private static final String DTD_VALUE = "dnadtd:value";
+ private static final String ELEMENT_CONTENT = "dnaxml:elementContent";
+ private static final String ENTITY = "dnadtd:entity";
+ private static final String PI = "dnaxml:processingInstruction";
+ private static final String PI_CONTENT = "dnaxml:processingInstructionContent";
+ private static final String TARGET = "dnaxml:target";
+
private XmlSequencer sequencer;
private InputStream stream;
private MockSequencerOutput output;
@@ -92,67 +107,67 @@
@Test
public void shouldSequenceXml() throws IOException {
verifyDocument(xml1);
- verifyName(XmlSequencer.COMMENT + "[1]", NameFactory.JCR_PRIMARY_TYPE, XmlSequencer.COMMENT);
- String text = verify(XmlSequencer.COMMENT + "[1]", XmlSequencer.COMMENT_CONTENT, String.class);
+ verifyName(COMMENT + "[1]", NameFactory.JCR_PRIMARY_TYPE, COMMENT);
+ String text = verify(COMMENT + "[1]", COMMENT_CONTENT, String.class);
assertThat(text.startsWith("\n Licensed to the Apache Software Foundation (ASF)"), is(true));
assertThat(text.endsWith(" limitations under the License.\n"), is(true));
- verifyString("", XmlSequencer.DTD_NAME, "Repository");
- verifyString("", XmlSequencer.DTD_PUBLIC_ID, "-//The Apache Software Foundation//DTD Jackrabbit 1.2//EN");
- verifyString("", XmlSequencer.DTD_SYSTEM_ID, "http://jackrabbit.apache.org/dtd/repository-1.2.dtd");
- verifyName(XmlSequencer.COMMENT + "[2]", NameFactory.JCR_PRIMARY_TYPE, XmlSequencer.COMMENT);
- verifyString(XmlSequencer.COMMENT + "[2]", XmlSequencer.COMMENT_CONTENT, " Example Repository Configuration File ");
- verifyName("Repository[1]", NameFactory.JCR_PRIMARY_TYPE, "Repository");
- verifyName("Repository[1]/" + XmlSequencer.COMMENT + "[1]", NameFactory.JCR_PRIMARY_TYPE, XmlSequencer.COMMENT);
+ verifyString("/", DTD_NAME, "Repository");
+ verifyString("/", DTD_PUBLIC_ID, "-//The Apache Software Foundation//DTD Jackrabbit 1.2//EN");
+ verifyString("/", DTD_SYSTEM_ID, "http://jackrabbit.apache.org/dtd/repository-1.2.dtd");
+ verifyName(COMMENT + "[2]", NameFactory.JCR_PRIMARY_TYPE, COMMENT);
+ verifyString(COMMENT + "[2]", COMMENT_CONTENT, " Example Repository Configuration File ");
+ verifyName("Repository[1]", NameFactory.JCR_PRIMARY_TYPE, "nt:unstructured");
+ verifyName("Repository[1]/" + COMMENT + "[1]", NameFactory.JCR_PRIMARY_TYPE, COMMENT);
}
@Test
public void shouldHandleNamespaces() throws IOException {
verifyDocument(xml2);
- verifyName("book[1]/bookinfo[1]/xi:include[1]", NameFactory.JCR_PRIMARY_TYPE, "xi:include");
+ verifyName("book[1]/bookinfo[1]/xi:include[1]", NameFactory.JCR_PRIMARY_TYPE, "nt:unstructured");
verifyString("book[1]/bookinfo[1]/xi:include[1]", "xi:href", "Author_Group.xml");
- verifyName("book[1]/bookinfo[1]/xi:include[2]", NameFactory.JCR_PRIMARY_TYPE, "xi:include");
+ verifyName("book[1]/bookinfo[1]/xi:include[2]", NameFactory.JCR_PRIMARY_TYPE, "nt:unstructured");
verifyString("book[1]/bookinfo[1]/xi:include[2]", "xi:href", "Legal_Notice.xml");
}
@Test
public void shouldSequenceEntityDeclarations() throws IOException {
verifyDocument(xml2);
- verifyName(XmlSequencer.ENTITY + "[1]", NameFactory.JCR_PRIMARY_TYPE, XmlSequencer.ENTITY);
- verifyString(XmlSequencer.ENTITY + "[1]", XmlSequencer.DTD_NAME, "%RH-ENTITIES");
- verifyString(XmlSequencer.ENTITY + "[1]", XmlSequencer.DTD_SYSTEM_ID, "Common_Config/rh-entities.ent");
- verifyName(XmlSequencer.ENTITY + "[2]", NameFactory.JCR_PRIMARY_TYPE, XmlSequencer.ENTITY);
- verifyString(XmlSequencer.ENTITY + "[2]", XmlSequencer.DTD_NAME, "versionNumber");
- verifyString(XmlSequencer.ENTITY + "[2]", XmlSequencer.DTD_VALUE, "0.1");
- verifyName(XmlSequencer.ENTITY + "[3]", NameFactory.JCR_PRIMARY_TYPE, XmlSequencer.ENTITY);
- verifyString(XmlSequencer.ENTITY + "[3]", XmlSequencer.DTD_NAME, "copyrightYear");
- verifyString(XmlSequencer.ENTITY + "[3]", XmlSequencer.DTD_VALUE, "2008");
+ verifyName(ENTITY + "[1]", NameFactory.JCR_PRIMARY_TYPE, ENTITY);
+ verifyString(ENTITY + "[1]", DTD_NAME, "%RH-ENTITIES");
+ verifyString(ENTITY + "[1]", DTD_SYSTEM_ID, "Common_Config/rh-entities.ent");
+ verifyName(ENTITY + "[2]", NameFactory.JCR_PRIMARY_TYPE, ENTITY);
+ verifyString(ENTITY + "[2]", DTD_NAME, "versionNumber");
+ verifyString(ENTITY + "[2]", DTD_VALUE, "0.1");
+ verifyName(ENTITY + "[3]", NameFactory.JCR_PRIMARY_TYPE, ENTITY);
+ verifyString(ENTITY + "[3]", DTD_NAME, "copyrightYear");
+ verifyString(ENTITY + "[3]", DTD_VALUE, "2008");
}
@Test
public void shouldSequenceElementContent() throws IOException {
verifyDocument(xml2);
- verifyString("book[1]/chapter[4]/sect1[1]/para[8]/" + XmlSequencer.ELEMENT_CONTENT + "[1]",
- XmlSequencer.ELEMENT_CONTENT,
+ verifyString("book[1]/chapter[4]/sect1[1]/para[8]/" + ELEMENT_CONTENT + "[1]",
+ ELEMENT_CONTENT,
"The path expression is more complicated."
+ " Sequencer path expressions are used by the sequencing service to determine whether a particular changed node should be sequenced."
+ " The expressions consist of two parts: a selection criteria and an output expression."
+ " Here's a simple example:");
- verifyString("book[1]/chapter[4]/sect1[1]/para[8]/programlisting[1]/" + XmlSequencer.ELEMENT_CONTENT + "[1]",
- XmlSequencer.ELEMENT_CONTENT,
+ verifyString("book[1]/chapter[4]/sect1[1]/para[8]/programlisting[1]/" + ELEMENT_CONTENT + "[1]",
+ ELEMENT_CONTENT,
"/a/b/c@title => /d/e/f");
}
@Test
public void shouldSequenceCData() throws IOException {
verifyDocument(xml3);
- verifyString("mx:Application[1]/mx:Script[1]/" + XmlSequencer.CDATA + "[1]",
- XmlSequencer.CDATA_CONTENT,
+ verifyString("mx:Application[1]/mx:Script[1]/" + CDATA + "[1]",
+ CDATA_CONTENT,
"\n\n" + " import mx.events.ValidationResultEvent;\t\t\t\n"
+ " private var vResult:ValidationResultEvent;\n" + "\t\t\t\n"
+ " // Event handler to validate and format input.\n"
+ " private function Format():void {\n" + " \n"
- + " vResult = numVal.validate();\n\n"
- + " if (vResult.type==ValidationResultEvent.VALID) {\n"
+ + " vResult = numVal.validate();\n\n"
+ + " if (vResult.type==ValidationResultEvent.VALID) {\n"
+ " var temp:Number=Number(priceUS.text); \n"
+ " formattedUSPrice.text= usdFormatter.format(temp);\n" + " }\n"
+ " \n" + " else {\n"
@@ -163,25 +178,25 @@
@Test
public void shouldSequenceProcessingInstructions() throws IOException {
verifyDocument(xml4);
- verifyName(XmlSequencer.PI + "[1]", NameFactory.JCR_PRIMARY_TYPE, XmlSequencer.PI);
- verifyString(XmlSequencer.PI + "[1]", XmlSequencer.TARGET, "eclipse");
- verifyString(XmlSequencer.PI + "[1]", XmlSequencer.PI_CONTENT, "version=\"3.0\"");
+ verifyName(PI + "[1]", NameFactory.JCR_PRIMARY_TYPE, PI);
+ verifyString(PI + "[1]", TARGET, "eclipse");
+ verifyString(PI + "[1]", PI_CONTENT, "version=\"3.0\"");
}
@Test
public void shouldSequenceXsds() throws IOException {
verifyDocument(xsd);
- verifyName("xs:schema[1]", NameFactory.JCR_PRIMARY_TYPE, "xs:schema");
+ verifyName("xs:schema[1]", NameFactory.JCR_PRIMARY_TYPE, "nt:unstructured");
verifyString("xs:schema[1]", "xs:targetNamespace", "http://ns.adobe.com/air/application/1.0");
verifyString("xs:schema[1]", "xs:elementFormDefault", "qualified");
- verifyName("xs:schema[1]/xs:element[1]", NameFactory.JCR_PRIMARY_TYPE, "xs:element");
+ verifyName("xs:schema[1]/xs:element[1]", NameFactory.JCR_PRIMARY_TYPE, "nt:unstructured");
verifyString("xs:schema[1]/xs:element[1]", "xs:name", "application");
}
private <T> T verify( String nodePath,
String property,
Class<T> expectedClass ) {
- Object[] values = output.getPropertyValues(nodePath.length() == 0 ? "." : "./" + nodePath, property);
+ Object[] values = output.getPropertyValues(nodePath.length() == 0 ? "." : nodePath, property);
assertThat(values, notNullValue());
assertThat(values.length, is(1));
Object value = values[0];
@@ -193,7 +208,7 @@
stream = url.openStream();
assertThat(stream, is(notNullValue()));
sequencer.sequence(stream, output, context, monitor);
- verifyName("", NameFactory.JCR_PRIMARY_TYPE, XmlSequencer.DOCUMENT);
+ verifyName("", NameFactory.JCR_PRIMARY_TYPE, DOCUMENT);
}
private void verifyName( String nodePath,
Modified: trunk/dna-repository/src/test/resources/CurrencyFormatterExample.mxml
===================================================================
--- trunk/dna-repository/src/test/resources/CurrencyFormatterExample.mxml 2008-09-09 18:56:21 UTC (rev 512)
+++ trunk/dna-repository/src/test/resources/CurrencyFormatterExample.mxml 2008-09-10 15:19:33 UTC (rev 513)
@@ -11,9 +11,9 @@
// Event handler to validate and format input.
private function Format():void {
- vResult = numVal.validate();
+ vResult = numVal.validate();
- if (vResult.type==ValidationResultEvent.VALID) {
+ if (vResult.type==ValidationResultEvent.VALID) {
var temp:Number=Number(priceUS.text);
formattedUSPrice.text= usdFormatter.format(temp);
}
Added: trunk/dna-repository/src/test/resources/repositoryImporterTestData1.xml
===================================================================
--- trunk/dna-repository/src/test/resources/repositoryImporterTestData1.xml (rev 0)
+++ trunk/dna-repository/src/test/resources/repositoryImporterTestData1.xml 2008-09-10 15:19:33 UTC (rev 513)
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ JBoss, Home of Professional Open Source.
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+<dna:system xmlns:dna="http://www.jboss.org/dna" xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <!-- Define the RepositorySource instances that will be added if not already defined -->
+ <dna:sources>
+ <sourceA jcr:primaryType="dna:xyz" repositoryName="repositoryA" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" retryLimit="3" />
+ <sourceB repositoryName="repositoryB" dna:classname="org.jboss.dna.connector.inmemory.InMemoryRepositorySource" />
+ </dna:sources>
+</dna:system>
\ No newline at end of file
Property changes on: trunk/dna-repository/src/test/resources/repositoryImporterTestData1.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/ValueComparators.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/ValueComparators.java 2008-09-09 18:56:21 UTC (rev 512)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/ValueComparators.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -303,10 +303,10 @@
if (type1 == type2) return ((Comparator<Object>)type1.getComparator()).compare(o1, o2);
// The types are different but the classes are the same ...
- if (type1.getDeclaringClass().isAssignableFrom(type2.getDeclaringClass())) {
+ if (type1.getValueClass().isAssignableFrom(type2.getValueClass())) {
return ((Comparator<Object>)type1.getComparator()).compare(o1, o2);
}
- if (type2.getDeclaringClass().isAssignableFrom(type1.getDeclaringClass())) {
+ if (type2.getValueClass().isAssignableFrom(type1.getValueClass())) {
return ((Comparator<Object>)type2.getComparator()).compare(o1, o2);
}
}
Modified: trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicProperty.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicProperty.java 2008-09-09 18:56:21 UTC (rev 512)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/impl/BasicProperty.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -26,6 +26,7 @@
import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.spi.graph.Name;
import org.jboss.dna.spi.graph.Property;
+import org.jboss.dna.spi.graph.ValueComparators;
/**
* @author Randall Hauch
@@ -101,12 +102,7 @@
while (thisIter.hasNext()) { // && thatIter.hasNext()
Object thisValue = thisIter.next();
Object thatValue = thatIter.next();
- if (thisValue == null) {
- if (thatValue != null) return false;
- // else both are null
- } else {
- if (!thisValue.equals(thatValue)) return false;
- }
+ if (ValueComparators.OBJECT_COMPARATOR.compare(thisValue, thatValue) != 0) return false;
}
return true;
}
Modified: trunk/dna-spi/src/test/java/org/jboss/dna/spi/sequencers/MockSequencerOutput.java
===================================================================
--- trunk/dna-spi/src/test/java/org/jboss/dna/spi/sequencers/MockSequencerOutput.java 2008-09-09 18:56:21 UTC (rev 512)
+++ trunk/dna-spi/src/test/java/org/jboss/dna/spi/sequencers/MockSequencerOutput.java 2008-09-10 15:19:33 UTC (rev 513)
@@ -24,6 +24,7 @@
import java.util.HashMap;
import java.util.Map;
import net.jcip.annotations.NotThreadSafe;
+import org.jboss.dna.spi.DnaLexicon;
import org.jboss.dna.spi.graph.Name;
import org.jboss.dna.spi.graph.NamespaceRegistry;
import org.jboss.dna.spi.graph.Path;
@@ -39,112 +40,112 @@
@NotThreadSafe
public class MockSequencerOutput implements SequencerOutput {
- private final Map<Path, Object[]> properties;
- private final ValueFactories factories;
+ private final Map<Path, Object[]> properties;
+ private final ValueFactories factories;
- /**
+ /**
*/
- public MockSequencerOutput() {
- this.properties = new HashMap<Path, Object[]>();
- NamespaceRegistry registry = new BasicNamespaceRegistry();
- registry.register("jcr", "http://www.jcp.org/jcr/1.0");
- registry.register("mix", "http://www.jcp.org/jcr/mix/1.0");
- registry.register("nt", "http://www.jcp.org/jcr/nt/1.0");
- registry.register("dna", "http://www.jboss.org/dna/1.0");
- registry.register("dnadtd", "http://www.jboss.org/dna/1.0/dtd");
- registry.register("dnaxml", "http://www.jboss.org/dna/1.0/xml");
- factories = new StandardValueFactories(registry);
- }
+ public MockSequencerOutput() {
+ this.properties = new HashMap<Path, Object[]>();
+ NamespaceRegistry registry = new BasicNamespaceRegistry();
+ registry.register("jcr", "http://www.jcp.org/jcr/1.0");
+ registry.register("mix", "http://www.jcp.org/jcr/mix/1.0");
+ registry.register("nt", "http://www.jcp.org/jcr/nt/1.0");
+ registry.register(DnaLexicon.Namespace.PREFIX, DnaLexicon.Namespace.URI);
+ registry.register("dnadtd", "http://www.jboss.org/dna/dtd/1.0");
+ registry.register("dnaxml", "http://www.jboss.org/dna/xml/1.0");
+ factories = new StandardValueFactories(registry);
+ }
- /**
- * {@inheritDoc}
- */
- public ValueFactories getFactories() {
- return this.factories;
- }
+ /**
+ * {@inheritDoc}
+ */
+ public ValueFactories getFactories() {
+ return this.factories;
+ }
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.jboss.dna.spi.sequencers.SequencerOutput#getNamespaceRegistry()
- */
- public NamespaceRegistry getNamespaceRegistry() {
- return factories.getNameFactory().getNamespaceRegistry();
- }
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.jboss.dna.spi.sequencers.SequencerOutput#getNamespaceRegistry()
+ */
+ public NamespaceRegistry getNamespaceRegistry() {
+ return factories.getNameFactory().getNamespaceRegistry();
+ }
- /**
- * {@inheritDoc}
- */
- public void setProperty( Path nodePath,
- Name propertyName,
- Object... values ) {
- Path key = createKey(nodePath, propertyName);
- if (values == null || values.length == 0) {
- this.properties.remove(key);
- } else {
- this.properties.put(key, values);
- }
- }
+ /**
+ * {@inheritDoc}
+ */
+ public void setProperty( Path nodePath,
+ Name propertyName,
+ Object... values ) {
+ Path key = createKey(nodePath, propertyName);
+ if (values == null || values.length == 0) {
+ this.properties.remove(key);
+ } else {
+ this.properties.put(key, values);
+ }
+ }
- /**
- * {@inheritDoc}
- */
- public void setProperty( String nodePath,
- String propertyName,
- Object... values ) {
- Path path = this.factories.getPathFactory().create(nodePath);
- Name name = this.factories.getNameFactory().create(propertyName);
- setProperty(path, name, values);
- }
+ /**
+ * {@inheritDoc}
+ */
+ public void setProperty( String nodePath,
+ String propertyName,
+ Object... values ) {
+ Path path = this.factories.getPathFactory().create(nodePath);
+ Name name = this.factories.getNameFactory().create(propertyName);
+ setProperty(path, name, values);
+ }
- /**
- * {@inheritDoc}
- */
- public void setReference( String nodePath,
- String propertyName,
- String... paths ) {
- PathFactory pathFactory = this.factories.getPathFactory();
- Path path = pathFactory.create(nodePath);
- Name name = this.factories.getNameFactory().create(propertyName);
- Object[] values = null;
- if (paths != null && paths.length != 0) {
- values = new Path[paths.length];
- for (int i = 0, len = paths.length; i != len; ++i) {
- String pathValue = paths[i];
- values[i] = pathFactory.create(pathValue);
- }
- }
- setProperty(path, name, values);
- }
+ /**
+ * {@inheritDoc}
+ */
+ public void setReference( String nodePath,
+ String propertyName,
+ String... paths ) {
+ PathFactory pathFactory = this.factories.getPathFactory();
+ Path path = pathFactory.create(nodePath);
+ Name name = this.factories.getNameFactory().create(propertyName);
+ Object[] values = null;
+ if (paths != null && paths.length != 0) {
+ values = new Path[paths.length];
+ for (int i = 0, len = paths.length; i != len; ++i) {
+ String pathValue = paths[i];
+ values[i] = pathFactory.create(pathValue);
+ }
+ }
+ setProperty(path, name, values);
+ }
- public Object[] getPropertyValues( String nodePath,
- String property ) {
- Path key = createKey(nodePath, property);
- return this.properties.get(key);
- }
+ public Object[] getPropertyValues( String nodePath,
+ String property ) {
+ Path key = createKey(nodePath, property);
+ return this.properties.get(key);
+ }
- public boolean hasProperty( String nodePath,
- String property ) {
- Path key = createKey(nodePath, property);
- return this.properties.containsKey(key);
- }
+ public boolean hasProperty( String nodePath,
+ String property ) {
+ Path key = createKey(nodePath, property);
+ return this.properties.containsKey(key);
+ }
- public boolean hasProperties() {
- return this.properties.size() > 0;
- }
+ public boolean hasProperties() {
+ return this.properties.size() > 0;
+ }
- protected Path createKey( String nodePath,
- String propertyName ) {
- Path path = this.factories.getPathFactory().create(nodePath);
- Name name = this.factories.getNameFactory().create(propertyName);
- return createKey(path, name);
- }
+ protected Path createKey( String nodePath,
+ String propertyName ) {
+ Path path = this.factories.getPathFactory().create(nodePath);
+ Name name = this.factories.getNameFactory().create(propertyName);
+ return createKey(path, name);
+ }
- protected Path createKey( Path nodePath,
- Name propertyName ) {
- return this.factories.getPathFactory().create(nodePath, propertyName);
- }
+ protected Path createKey( Path nodePath,
+ Name propertyName ) {
+ return this.factories.getPathFactory().create(nodePath, propertyName);
+ }
}
15 years, 7 months